<template>
  <div class="full-width TableGrid">
    <div
      class="TableGrid-Row full-width headers"
      :class="selection === 'multiple' && 'with-checkboxes'"
    >
      <div class="header-checkbox" v-if="selection !== 'none'">
        <r-checkbox
          :value="massSelected"
          :disabled="disabledMassCheckbox"
          :size="20"
          @input="massSelected = !massSelected"
        />
      </div>
      <!-- <div class="q-pl-sm">Номер</div> -->
      <div class="q-pl-sm">Инициатор запроса</div>
      <!-- <div class="q-pl-sm">Процедура</div> -->
      <div class="q-pl-sm">ФИО / ИД ЕРН</div>
      <div class="q-pl-sm">Дата запроса</div>
      <div class="text-center">Статус</div>
      <div class="text-center">Действия</div>
    </div>
    <q-table
      class="TableGrid"
      grid
      row-key="id"
      v-bind="{ ...$props, ...$attrs }"
      @request="$emit('request', $event)"
      @update:selected="$emit('update:selected', $event)"
      @update:pagination="$emit('update:pagination', $event)"
    >
      <template v-slot:item="props">
        <div
          class="TableGrid-Row full-width body"
          :class="selection === 'multiple' && 'with-checkboxes'"
        >
          <div class="checkbox-column" v-if="selection !== 'none'">
            <r-checkbox
              :value="selectedIds[props.row.id]"
              :size="20"
              :disabled="!props.row.choosable"
              @input="toggleSelected(props.row.id)"
            />
          </div>
          <!-- <div class="TableGrid-Col__Number">
            <span class="ellipsis">{{ props.row.number }}</span>
          </div> -->
          <div class="flex">
            <span class="multiline" :title="props.row.requester">{{
              props.row.requester
            }}</span>
          </div>
          <!-- <div class="flex">
            <span
              class="multiline"
              :title="
                props.row.procedure && props.row.procedure.type
                  ? props.row.procedure.type
                  : 'Постановка на ВУ'
              "
              >{{
                props.row.procedure && props.row.procedure.type
                  ? props.row.procedure.type
                  : 'Постановка на ВУ'
              }}</span
            >
          </div> -->
          <div>
            <div class="name">
              <router-link
                class="cursor-pointer"
                :to="{
                  name: 'recruit-personal',
                  params: { id: props.row.recruitId },
                }"
              >
                {{ props.row.fullName }}
              </router-link>
            </div>
            <div class="row q-pt-xs">
              <div class="flex col">
                <span class="text-no-wrap ellipsis">
                  {{ props.row.idern }}
                </span>
              </div>
            </div>
          </div>
          <div>
            <div class="TableGrid-Col__Date">
              <q-icon name="pgs-request-date" size="20px" />
              <span class="ellipsis">
                {{ formatDate(props.row.requestDate) }}
              </span>
            </div>
          </div>
          <div class="status">
            <status-box
              :status="getStatusLabel(props.row.status)"
              borderless
              :class="getStatusClass(props.row.status)"
            />
          </div>
          <div
            class="button"
            :class="
              !$AC.haveOneOfScope([$AC.scopes.MILITARY_RECRUIT_SPECIALIST]) &&
              'q-px-none'
            "
          >
            <attach-personal-file
              v-if="
                $AC.haveOneOfScope([$AC.scopes.MILITARY_RECRUIT_SPECIALIST])
              "
              :disable="!props.row.confirmEnable"
              :model="props.row"
              @close="$emit('request', { pagination })"
            >
              <template #button="btn">
                <q-icon
                  :class="{
                    'TableGrid-Button__Disable': !props.row.confirmEnable,
                  }"
                  class="TableGrid-Button TableGrid-Button__Attach"
                  name="pgs-import"
                  @click="btn.open"
                >
                  <q-tooltip>Направить код загрузки личного дела</q-tooltip>
                </q-icon>
              </template>
            </attach-personal-file>
            <reject-personal-file
              v-if="
                $AC.haveOneOfScope([$AC.scopes.MILITARY_RECRUIT_SPECIALIST])
              "
              :disable="!props.row.rejectEnable"
              :model="props.row"
              @close="$emit('request', { pagination })"
            >
              <template #button="btn">
                <q-icon
                  :class="{
                    'TableGrid-Button__Disable': !props.row.rejectEnable,
                  }"
                  class="TableGrid-Button TableGrid-Button__Undo"
                  name="pgs-undo"
                  @click="btn.open"
                >
                  <q-tooltip>Отклонить</q-tooltip>
                </q-icon>
              </template>
            </reject-personal-file>
            <q-icon
              v-if="hasButtons"
              :class="{
                'TableGrid-Button__Disable': !props.row.requestDownloadEnable,
              }"
              class="TableGrid-Button"
              name="pgs-import-from-epgu"
              @click="$emit('download-personal-file', props.row)"
            >
              <q-tooltip> Скачать файл запроса личного дела </q-tooltip>
            </q-icon>
            <q-icon
              v-if="hasButtons"
              :class="{
                'TableGrid-Button__Disable': !props.row.quittanceDownloadEnable,
              }"
              class="TableGrid-Button"
              name="pgs-roll"
              @click="$emit('download-quittance', props.row)"
            >
              <q-tooltip> Скачать квитанцию </q-tooltip>
            </q-icon>
          </div>
        </div>
      </template>
    </q-table>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';
import { TablePagination } from '@/models/base/TablePagination';
import { formatDate, mask } from '@/recruits/utils';
import StatusBox from '@/recruits/components/common/status-box/index.vue';
import AttachPersonalFile from '../dialogs/AttachPersonalFile.vue';
import RejectPersonalFile from '../dialogs/RejectPersonalFile.vue';
import {
  DictionariesElement,
  LoadLdResponseV1,
} from '@/recruits/openapi/person-registry';
import RCheckbox from '@/recruits/components/common/r-checkbox.vue';

@Component({
  components: {
    StatusBox,
    AttachPersonalFile,
    RejectPersonalFile,
    RCheckbox,
  },
  methods: { mask, formatDate },
})
export default class DataTable extends Vue {
  formatDate: typeof formatDate;
  mask: typeof mask;

  @Prop() pagination: TablePagination;
  @Prop({ default: () => [] }) data: LoadLdResponseV1[];
  @Prop({ default: () => [] }) selected: string[];
  @Prop({ default: 'none' }) selection: 'none' | 'multiple';
  @Prop({ default: false }) disabledMassCheckbox: boolean;

  get massSelected(): boolean {
    return !!(
      this.selected.length && this.selected.length === this.data.length
    );
  }

  set massSelected(val: boolean) {
    this.$emit(
      'update:selected',
      val
        ? this.data.filter(({ choosable }) => choosable).map(({ id }) => id)
        : []
    );
  }

  get hasButtons(): boolean {
    return this.$AC.haveOneOfScope([
      this.$AC.scopes.MILITARY_RECRUIT_SPECIALIST,
      this.$AC.scopes.MILITARY_COMMISSAR,
      this.$AC.scopes.SYSTEM_ADMINISTRATOR,
    ]);
  }

  get selectedIds(): Record<string, boolean> {
    return this.selected.reduce((acc, val) => ({ ...acc, [val]: true }), {});
  }

  get statuses(): DictionariesElement[] {
    return this.$store.getters['ervuDictionaries/privateFileStatusDictionary'];
  }

  getStatusClass(status: string): string {
    const labels: Record<string, string> = {
      nonrequested: '',
      sended: 'status-good',
      accepted: 'status-good',
      cancelled: '',
      requested: '',
      rejected: 'status-bad',
    };
    return labels?.[status] ?? '';
  }

  getStatusLabel(status: string): string {
    const statusFromDict = this.statuses.find(({ code }) => code === status);
    return statusFromDict?.value ?? status;
  }

  isSelected(id: string): boolean {
    console.log(id, this.selected.includes(id));
    return this.selected.includes(id);
  }

  toggleSelected(id: string): void {
    if (this.selectedIds[id]) {
      this.$emit(
        'update:selected',
        this.selected.filter((val) => val !== id)
      );
    } else this.$emit('update:selected', [...this.selected, id]);
    this.$forceUpdate();
  }

  mounted(): void {
    this.$store.dispatch('ervuDictionaries/loadPrivateFileStatusDictionary');
  }
}
</script>

<style lang="scss" scoped>
div.header-checkbox {
  margin-top: -4px;
  margin-bottom: -4px;
  padding-left: 12px;
  padding-right: 12px;
}

.disabled-checkBox {
  opacity: 0.5;
}

.headers {
  padding: 16px 0 6px 0;

  > div {
    color: rgba(2, 12, 18, 0.58);
    overflow: hidden;
    font-family: 'Golos Text', sans-serif;
    font-style: normal;
    font-weight: 600;
    font-size: 10px;
    line-height: 12px;
    padding: 0 4px;

    letter-spacing: 0.05em;
    text-transform: uppercase;
  }
}

::v-deep i.pgs-calendar {
  top: -3px;
}

::v-deep .q-px-none {
  padding-left: 0 !important;
  padding-right: 0 !important;
}

::v-deep i.pgs-request-date {
  //background: red;
  top: -1px;
  right: 1px;
}

.body {
  max-height: 5em;
  padding: 4px 0 4px 0;
  margin: 2px 0 2px 0;
  background: #ffffff;
  border: 1px solid rgba(1, 72, 116, 0.11);
  border-radius: 8px;
  box-shadow: none;

  > div::v-deep {
    position: relative;
    padding: 0 4px 0 4px;
    overflow: hidden;
    color: rgba(2, 12, 18, 0.9);
    font-family: 'Golos UI', sans-serif;
    font-style: normal;
    font-weight: 400;
    font-size: 14px;
    line-height: 16px;

    .procedure {
      font-size: 14px;
      line-height: 16px;
    }

    .name {
      font-weight: 500;
      font-size: 14px;
      line-height: 16px;
      color: rgba(2, 12, 18, 0.9);
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      a {
        text-decoration: none;
        &:link {
          color: #015e98;
        }
        &:visited {
          color: rgba(2, 12, 18, 0.9);
        }
      }
    }

    .multiline {
      align-self: center;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 3;
      -webkit-box-orient: vertical;
    }

    .gray-numbers {
      font-weight: 400;
      font-size: 14px;
      line-height: 16px;
      // color: rgba(2, 12, 18, 0.58);
    }

    .snils {
      font-size: 14px;
      line-height: 16px;
      // color: rgba(2, 12, 18, 0.9);

      .copy-button {
        padding-left: 2px;
        color: #1491cf;
      }
    }

    &.status {
      margin-top: -4px;
      margin-bottom: -4px;
      padding: 0;
    }

    &.button {
      overflow: unset;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 0.75rem;
    }

    &.lists {
      font-weight: 400;
      font-size: 12px;
      line-height: 16px;
      // color: rgba(2, 12, 18, 0.58);

      a {
        text-decoration: none;

        &:link {
          color: #015e98;
        }

        &:visited {
          color: rgba(2, 12, 18, 0.9);
        }
      }
    }
  }

  &:hover {
    border: 1px solid #1491cf;
    box-shadow: 0 0.6px 1.8px rgba(7, 46, 71, 0.12),
      0 3.2px 8px rgba(7, 46, 71, 0.15);
  }

  > div:not(:nth-last-of-type(-n + 3))::after {
    // Кроме последних двух
    position: absolute;
    content: '';
    width: 1px;
    height: 100%;
    top: 0;
    right: 0;
    background-color: rgba(1, 72, 116, 0.11);
  }
}

::v-deep .q-table__bottom {
  font-family: 'Golos UI', sans-serif;
  font-style: normal;
  font-weight: 400;
  font-size: 14px;
  line-height: 16px;
  color: rgba(2, 12, 18, 0.58);
}

.TableGrid {
  &-Row {
    display: grid;
    // grid-template-columns: 1fr 180px 300px 140px 110px 180px 110px;
    grid-template-columns: 1fr 300px 110px 180px 160px;

    &.with-checkboxes {
      // grid-template-columns: 46px 1fr 180px 300px 140px 110px 180px 110px;
      grid-template-columns: 46px 1fr 300px 110px 180px 160px;
    }
  }

  &-Col {
    &__Initiator {
      font-family: 'Golos UI', sans-serif;
      font-style: normal;
      font-weight: 500;
      font-size: 14px;
      line-height: 16px;
      color: rgba(2, 12, 18, 0.9);

      align-items: center;
      display: flex;
      justify-content: flex-start;
      height: 100%;
    }

    &__Date {
      font-family: 'Golos UI', sans-serif;
      font-style: normal;
      font-weight: 400;
      font-size: 14px;
      line-height: 16px;
      // color: rgba(2, 12, 18, 0.58);

      align-items: center;
      display: flex;
      justify-content: flex-start;
      height: 100%;
    }

    &__Number {
      font-family: 'Golos UI', sans-serif;
      font-style: normal;
      font-weight: 400;
      font-size: 12px;
      line-height: 14px;
      // color: rgba(2, 12, 18, 0.58) !important;
      align-items: center;
      display: flex;
      justify-content: left;
      height: 100%;
    }

    &__Bold {
      font-family: 'Golos UI', sans-serif;
      font-style: normal;
      font-weight: 800;
      font-size: 12px;
      line-height: 14px;
      // color: rgba(2, 12, 18, 0.9);
    }
  }

  &-Button {
    font-size: 26px;
    cursor: pointer;

    &__Attach {
      color: #1491cf;
      // margin-right: 12px;
    }

    &__Undo {
      color: #cf5f14;
      // margin-right: 12px;
    }

    &__Disable {
      color: rgba(2, 12, 18, 0.58);
      cursor: not-allowed;
    }
  }
}

.LabelSelect {
  display: block;
  width: 20px;
  height: 20px;
  background-color: rgba(15, 32, 160, 0.08);
  border: 1px solid rgba(1, 72, 116, 0.18);
  border-radius: 4px;
  position: relative;
  cursor: pointer;
  &-Select {
    display: none;
    &:disabled + .LabelSelect {
      background-color: #efefef;
      border: none;
      cursor: not-allowed;
    }
    &:checked + .LabelSelect {
      background-color: #1491cf;
      box-shadow: 0 0 3.5px rgba(1, 94, 152, 0.5);
      &:before,
      &:after {
        position: absolute;
        content: '';
        display: block;
        background-color: #fff;
        height: 3px;
        border-radius: 10px;
      }
      &:before {
        width: 10px;
        top: 10px;
        left: 1px;
        transform: rotate(60deg);
      }
      &:after {
        width: 14px;
        top: 8px;
        left: 5px;
        transform: rotate(-60deg);
      }
    }
  }
}

.checkbox-column,
.header-checkbox {
  display: flex;
  justify-content: center;
  align-items: center;
  > * {
    align-self: unset;
  }
}

.status {
  &-bad {
    background: #fdf3ed;
    color: #cf5f14;
    border-color: #cf5f14;
  }

  &-good {
    background: #e3fefa;
    color: #04967d;
    border-color: #04967d;
  }
}
</style>
