<template>
  <div class="SigningTable">
    <div class="SigningTable__Header">
      <div class="SigningTable__CheckBox">
        <input
          class="LabelSelect__Select"
          id="massSelect"
          type="checkbox"
          v-model="massSelected"
        />
        <label for="massSelect" class="LabelSelect__Label" />
      </div>
      <div class="SigningTable__HeaderTitle SigningTable__HeaderTitle_Padding">
        Серия / Номер повестки / Причина вызова
      </div>
      <div class="SigningTable__HeaderTitle SigningTable__HeaderTitle_Center">
        Дата и время явки
      </div>
      <div class="SigningTable__HeaderTitle SigningTable__HeaderTitle_Center">
        ФИО / ИД ЕРН
      </div>
      <div class="SigningTable__HeaderTitle SigningTable__HeaderTitle_Center">
        Статус
      </div>
    </div>
    <q-table
      grid
      v-bind="{ ...$props, ...$attrs, data }"
      @request="requestHandler"
      @update:pagination="$emit('update:pagination', $event)"
      row-key="id"
      selection="multiple"
      :selected.sync="selected"
    >
      <template v-slot:item="props">
        <div class="SigningTable__Row">
          <div class="SigningTable__Cell SigningTable__Cell_CheckBox">
            <input
              class="LabelSelect__Select"
              :id="props.row.id"
              type="checkbox"
              v-model="selected"
              :value="props.row.id"
            />
            <label :for="props.row.id" class="LabelSelect__Label" />
          </div>
          <div class="SigningTable__Cell SigningTable__Cell_PersonInfo">
            <div class="SigningTable__CellName">
              Повестка
              <router-link
                class="cursor-pointer"
                :to="{ name: 'subpoena-card', params: { id: props.row.id } }"
              >
                {{ props.row.series }} {{ props.row.number }}
              </router-link>
            </div>
            <div class="SigningTable__CellInfoBlock">
              <span
                class="SigningTable__EllipsisText SigningTable__EllipsisText_Wrap"
              >
                {{ options[props.row.summonObjective] }}
              </span>
            </div>
          </div>
          <div class="SigningTable__Cell">
            <q-icon name="pgs-time" size="20px" />
            <span class="SigningTable__EllipsisText">
              {{ formatDate(props.row.turnoutDate, 'DD.MM.YYYY') }}
              <span class="SigningTable__TimeField">
                {{ formatDate(props.row.turnoutDate, 'HH:mm') }}
              </span>
            </span>
          </div>
          <div class="SigningTable__Cell SigningTable__Cell_PersonInfo">
            <div class="SigningTable__CellName">
              <router-link
                class="cursor-pointer"
                :to="{
                  name: 'recruit-personal',
                  params: { id: props.row.recruitId },
                }"
              >
                {{ props.row.fullName }}
              </router-link>
            </div>
            <div class="SigningTable__CellInfoBlock">
              <span class="SigningTable__EllipsisText">
                {{ props.row.idERN }}
              </span>
            </div>
          </div>
          <div class="SigningTable__Cell SigningTable__Cell_Status">
            <status-box :status="props.row.status" borderless />
          </div>
          <div class="SigningTable__Cell SigningTable__Cell_Action">
            <base-preview
              v-if="props.row.s3Url"
              :extension="getDocumentType(props.row.s3Url)"
              :s3-url="props.row.s3Url"
            >
              <q-icon
                class="SigningTable__Icon"
                color="primary"
                name="pgs-view"
                size="26px"
              >
                <q-tooltip>Предпросмотр</q-tooltip>
              </q-icon>
            </base-preview>
            <q-icon
              v-else
              class="SigningTable__Icon"
              color="primary"
              name="pgs-view"
            />
            <q-icon
              class="SigningTable__Icon"
              name="pgs-import"
              color="primary"
              @click="downloadFile(props.row.s3Url, props.row.s3Name)"
            />
          </div>
        </div>
      </template>
    </q-table>
  </div>
</template>

<script lang="ts">
import { Component, Emit, Prop, Vue, Watch } from 'vue-property-decorator';
import { copyToClipboard } from 'quasar';
import { formatDate, mask } from '@/recruits/utils';
import StatusBox from '@/recruits/components/common/status-box/index.vue';
import { statusDictionary } from '@/recruits/models';
import S3UrlSignerFilesService from '@services/s3urlsigner/files';
import { saveBlob } from '@utils/files';
import get from 'lodash/get';
import { BatchSigning } from '@/recruits/openapi/person-registry';

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

  formatDate: typeof formatDate;
  selected: string[] = [];
  massSelected = false;

  @Prop()
  resetSelect: string;

  @Prop()
  data: BatchSigning[];

  @Watch('resetSelect')
  resetSelectedRows(val: boolean): void {
    if (val) {
      this.selected = [];
      this.massSelected = false;
    }
  }

  @Watch('selected')
  onSelectedChange(evt: string[]): void {
    this.$emit('row-selected', evt);
  }

  @Watch('massSelected')
  massSelect(newData: boolean): void {
    if (newData) {
      this.selected = (this.data ?? []).map(({ id }: BatchSigning) => id);
    } else {
      this.selected = [];
    }
  }

  get options(): string {
    return (
      this.$store.getters[
        'ervuDictionaries/militaryRegistrationUpdatingGoalsDictionary'
      ] || []
    );
  }

  public getStatusTitle(status: string): string {
    return statusDictionary[status] || status;
  }

  @Emit('request')
  requestHandler(): void {
    this.selected = [];
  }

  public sendToClipBoard(textValue: string): void {
    copyToClipboard(textValue);
    this.$q.notify({
      message: `'${textValue}' скопирован`,
    });
  }

  getDocumentType(url: string) {
    const array = url.split('.');
    return array[array.length - 1];
  }

  async downloadFile(s3url: string, fileName: string): Promise<void> {
    try {
      const { file: blob } = await S3UrlSignerFilesService.fetchFileFromS3ByUrl(
        {
          url: s3url,
        }
      );
      saveBlob({
        blob,
        fileName,
      });
    } catch (e) {
      console.log(e);
    }
  }
}
</script>

<style lang="scss" scoped>
.LabelSelect {
  &__Label {
    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;
  }
  &__Select {
    display: none;
    &:checked + .LabelSelect__Label {
      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);
      }
    }
  }
}

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

.SigningTable {
  color: rgba(2, 12, 18, 0.58);
  overflow: hidden;
  font-family: 'Golos Text';
  font-style: normal;
  font-weight: 600;
  font-size: 10px;
  line-height: 12px;
  &__Header {
    display: grid;
    grid-template-columns: 44px 1fr 0.3fr 0.5fr 0.3fr 0.3fr;
    padding: 16px 0 6px 0;
    text-transform: uppercase;
  }
  &__HeaderTitle {
    display: flex;
    &:not(:last-child) {
      border-right: 1px solid rgba(1, 72, 116, 0.11);
    }
    &_Padding {
      padding: 0 8px;
    }
    &_Center {
      justify-content: center;
    }
  }
  &__Row {
    display: grid;
    grid-template-columns: 44px 1fr 0.3fr 0.5fr 0.3fr 0.3fr;
    position: relative;
    overflow: hidden;
    width: 100%;
    color: rgba(2, 12, 18, 0.9);
    font-family: 'Golos UI';
    font-style: normal;
    font-weight: 400;
    font-size: 14px;
    line-height: 16px;
    margin: 2px 0 2px 0;
    background: #ffffff;
    border: 1px solid rgba(1, 72, 116, 0.11);
    border-radius: 8px;
    box-shadow: none;
    text-transform: none;
  }
  &__CheckBox {
    margin-top: -4px;
    margin-bottom: -4px;
    padding-left: 12px;
    padding-right: 12px;
  }
  &__Cell {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 8px;
    overflow: hidden;
    &:not(:last-child) {
      border-right: 1px solid rgba(1, 72, 116, 0.11);
    }

    &_CheckBox {
      padding-left: 4px;
      padding-right: 4px;
    }
    &_Action {
      justify-content: center;
    }
    &_PersonInfo {
      flex-direction: column;
      justify-content: flex-start;
      align-items: normal;
    }
    &_Status {
      padding: 0;
    }
  }
  &__CellName {
    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);
      }
    }
  }
  &__CellInfoBlock {
    display: flex;
    align-items: center;
    font-weight: 400;
    font-size: 14px;
    line-height: 16px;
    color: rgba(2, 12, 18, 0.58);
    gap: 1em;
  }
  &__CellInfo {
    display: flex;
    flex-wrap: nowrap;
    align-items: center;
  }
  &__EllipsisText {
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
    &_Wrap {
      white-space: normal;
    }
  }
  &__TimeField {
    font-weight: 400;
    font-size: 14px;
    line-height: 16px;
    color: rgba(2, 12, 18, 0.58);
  }
  &__Icon {
    font-size: 26px;
    cursor: pointer;
    color: #1491cf;
    &:not(:last-child) {
      margin-right: 10px;
    }
    &__Not {
      cursor: not-allowed;
    }
  }
}
</style>
