<template>
  <div>
    <centered-1280-box class="Documents">
      <r-spoiler-section
        title="Личные документы"
        :counter="personalDocuments.length"
        :bordered="true"
      >
        <template slot="actions">
          <add-document
            v-if="isButtonsVisible"
            :model="data"
            :activity-recorder-options="getRecruitInfo"
            @uploaded="onUploaded"
          />
        </template>
        <re-table
          :data="personalDocuments"
          :columns="personalDocumentsColumns"
          :hide-pagination="true"
          :rows-per-page-options="[0]"
        >
          <template #body-item-info="{ row }">
            <div class="Documents_InfoCell InfoCell">
              <h5 class="InfoCell_Header">
                {{ documentTypeLabel(row.type) }}
                <q-icon
                  size="24px"
                  class="InfoCell_Info"
                  name="pgs-info"
                  v-if="
                    row.type === '20' ? row.customDocumentType : row.comment
                  "
                  @click="
                    copyCustomDocumentType(
                      row.type === '20' ? row.customDocumentType : row.comment
                    )
                  "
                >
                  <q-tooltip>
                    {{
                      row.type === '20' ? row.customDocumentType : row.comment
                    }}
                  </q-tooltip>
                </q-icon>
              </h5>
              <p
                class="InfoCell_Comment"
                v-if="row.type === '20' && row.comment"
              >
                {{ row.comment }}
              </p>
              <div class="InfoCell_FileName">{{ row.file.s3Name }}</div>
            </div>
          </template>
          <template #body-item-signerInfo="{ row }">
            <div class="two-lines-cell">
              <template v-if="displayInfo(row.signerInfo)">
                <span>{{ row.signerInfo.fullName }}</span>
                <span>{{ row.signerInfo.nameVK }}</span>
              </template>
              <span v-else>—</span>
            </div>
          </template>
        </re-table>
      </r-spoiler-section>
      <base-preview
        v-if="fileToPreview && fileToPreview.s3url"
        :without-trigger="true"
        :s3Url="fileToPreview.s3url"
        :extension="fileToPreview.format"
        @close="fileToPreview = null"
      />
    </centered-1280-box>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';
import {
  AttachmentsDocumentsV3,
  PersonRegistryApi,
  RecruitV3,
  SignerInfo,
  DictionariesElement,
} from '@/recruits/openapi/person-registry';
import StatusBox from '@/recruits/components/common/status-box/index.vue';
import get from 'lodash/get';
import Centered1280Box from '@/recruits/components/common/centered-1280-box.vue';
import { formatDate } from '@/recruits/utils';
import S3UrlSignerFilesService from '@services/s3urlsigner/files';
import { saveBlob } from '@utils/files';
import RSelect from '@/recruits/components/common/r-select.vue';
import RInput from '@/recruits/components/common/r-input.vue';
import AddDocument from '@/recruits/components/dialogs/AddDocument.vue';
import ReTable from '@/recruits/components/common/r-table/index.vue';
import { RTableColumn } from '@/interfaces';
import RSpoilerSection from '@/recruits/components/common/r-spoiler-section.vue';
import SignInfo from '@/recruits/components/dialogs/SignInfo.vue';
import { DataForRecruit } from './masthead/interfaces';
import copyToClipboard from '@/utils/copy-to-clipboard';

@Component({
  methods: {
    get,
    formatDate,
  },
  components: {
    RSelect,
    RInput,
    ReTable,
    AddDocument,
    SignInfo,
    StatusBox,
    Centered1280Box,
    RSpoilerSection,
  },
})
export default class DocumentsTab extends Vue {
  get: typeof get;
  formatDate: typeof formatDate;

  registryApi = new PersonRegistryApi();
  fileToPreview: { s3url: string; format: string } | null = null;

  copyCustomDocumentType(text: string): void {
    copyToClipboard(text, (text) => `Описание ${text} скопировано`);
  }

  @Prop()
  readonly data: DataForRecruit;

  get isButtonsVisible(): boolean {
    return !this.data?.stateRecruit?.recruitmentConversion;
  }

  get personalDocuments(): AttachmentsDocumentsV3[] {
    return this.data.personalDocuments ?? [];
  }

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

  get getRecruitInfo(): Record<string, string> {
    const systemInfo: RecruitV3['systemInfo'] = this.data.systemInfo;
    const mainInfo: RecruitV3['mainInfo'] = this.data.mainInfo;
    return mainInfo && systemInfo
      ? {
          id: systemInfo.id || '',
          idERN: systemInfo.idERN,
          birthDate: formatDate(this.data.mainInfo.birthDate || ''),
          fio: mainInfo.fullName,
          type: 'recruit',
        }
      : {};
  }

  displayInfo(info: SignerInfo): boolean {
    return !!info?.fullName || !!info?.nameVK;
  }

  documentTypeLabel(type: string): string {
    return this.documentTypes.find(({ code }) => code === type)?.value ?? type;
  }

  get personalDocumentsColumns(): RTableColumn<AttachmentsDocumentsV3>[] {
    const hasScopes = true;
    return [
      {
        name: 'info',
        align: 'left',
        fields: [
          {
            label: `Тип`,
            field: 'type',
            name: 'type',
            width: '100%',
            format: (val) =>
              typeof val === 'string' ? this.documentTypeLabel(val) : '',
          },
          {
            label: 'Описание',
            field: 'comment',
            name: 'comment',
            type: 'bold',
            width: '100%',
          },
          {
            label: 'Файл',
            name: 'name',
            field: 'file.s3Name',
            width: '100%',
            type: 'gray-numbrts',
          },
        ],
      },
      {
        name: 'createdDate',
        label: 'Дата и время создания',
        field: 'createDate',
        componentPath: 'date-time',
        align: 'center',
        componentOptions: {
          time: true,
        },
        width: '180px',
      },
      {
        name: 'signerInfo',
        label: 'Сотрудник',
        field: 'signerInfo',
        sortable: false,
        align: 'left',
        style: 'width: 600px',
      },
      {
        label: 'Действия',
        name: 'actions',
        width: '92px',
        align: 'center',
        componentPath: 'action-buttons',
        componentOptions: {
          actions:
            (hasScopes && [
              {
                icon: 'pgs-import',
                color: 'primary',
                cb: ({ file }: AttachmentsDocumentsV3) => {
                  this.downloadFile(file.s3url, file.s3Name);
                  this.$recordActivity({
                    buttonCode: 'citizen_card_doc',
                    extraInfo: { ...this.getRecruitInfo },
                  });
                },
                tooltipText: 'Скачать',
              },
              {
                icon: 'pgs-view',
                color: 'primary',
                disabled: ({ file }: AttachmentsDocumentsV3) => !file.format,
                cb: this.openFilePreview,
                tooltipText: 'Предпросмотр',
              },
            ]) ||
            [],
        },
      },
    ];
  }

  public openFilePreview({ file }: AttachmentsDocumentsV3): void {
    this.fileToPreview = {
      s3url: file.s3url ?? '',
      format: file.format ?? '',
    };
  }

  async downloadFile(s3url: string, fileName: string): Promise<void> {
    try {
      const { file: blob } = await S3UrlSignerFilesService.fetchFileFromS3ByUrl(
        {
          url: s3url,
        }
      );
      saveBlob({
        blob,
        fileName,
        blobType: 'application/pdf',
      });
      this.$recordActivity({
        buttonCode: 'doc_prepare',
        extraInfo: { fileName, ...this.getRecruitInfo },
      });
    } catch (e) {
      console.log(e);
    }
  }

  onUploaded(): void {
    this.$emit('refresh');
  }

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

<style lang="scss" scoped>
.two-lines-cell {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  font-family: 'Golos UI', sans-serif;
  font-size: 12px;
  line-height: 14px;
  font-style: normal;
  span:first-child {
    font-weight: 800;
    color: rgba(2, 12, 18, 0.9);
  }
  span:nth-child(2) {
    font-weight: 400;
    color: rgba(2, 12, 18, 0.58);
  }
}

::v-deep {
  .RTable .q-table__top {
    padding-left: 0;
    padding-right: 0;
  }
  .RTable-Row {
    max-height: unset;
  }
  .RTable-SubCol {
    overflow: hidden;
  }
}

.InfoCell {
  width: 100%;
  line-height: 1.5em;
  &_Header {
    line-height: 1em;
    font-size: inherit;
    margin: 0;
    font-weight: 500;
    margin-bottom: 0.5em;
  }

  &_Comment {
    color: rgba(2, 12, 18, 0.58);
    line-height: inherit;
    margin-bottom: 0.5em;
    font-size: 0.9em;
    line-height: 14px;
  }

  &_Info {
    cursor: pointer;
  }
}
</style>
