<template>
  <div>
    <centered-1280-box class="Documents">
      <r-spoiler-section
        title="Личные документы"
        :counter="personalDocuments.length"
        :bordered="true"
      >
        <re-table
          :data="personalDocuments"
          :columns="personalDocumentsColumns"
          :hide-pagination="true"
          :rows-per-page-options="[0]"
        >
          <template #body-item-type="{ row }">
            <div class="two-lines-cell">
              <span>{{ documentTypeLabel(row.type) }}</span>
              <span>{{ row.comment }}</span>
            </div>
          </template>
          <template #body-item-signerInfo="{ row }">
            <div class="two-lines-cell">
              <span>{{ fullName(row.signerInfo) }}</span>
              <span>{{ nameVk(row.signerInfo) }}</span>
            </div>
          </template>
        </re-table>
      </r-spoiler-section>

      <r-spoiler-section
        title="Системные документы"
        :counter="systemDocuments.length"
        :bordered="true"
      >
        <re-table
          :data="systemDocuments"
          :columns="systemDocumentsColumns"
          :hide-pagination="true"
          :rows-per-page-options="[0]"
        >
          <template #body-item-signerInfo="{ row }">
            <div class="two-lines-cell">
              <span>{{ fullName(row.signerInfo) }}</span>
              <span>{{ nameVk(row.signerInfo) }}</span>
            </div>
          </template>
          <template #body-item-status="{ row }">
            <status-box
              :status="getStatusLabel(row.status)"
              borderless
              :class="getStatusClass(row.status)"
            />
          </template>
        </re-table>
      </r-spoiler-section>
      <q-dialog v-model="sigDialogShow">
        <sign-info-dialog :signature="signature" />
      </q-dialog>
      <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,
  SignerInfo,
  DictionariesElement,
} from '@/recruits/openapi/person-registry';
import { ArchivedRecruitV3 } from '@/recruits/openapi/person-archive';
import StatusBox from '@/recruits/components/common/status-box/index.vue';
import get from 'lodash/get';
import SignInfoDialog from '@components/registries/sign_info_dialog.vue';
import Centered1280Box from '@/recruits/components/common/centered-1280-box.vue';
import { fetchDocumentAttachment } from '@utils/fetch-document-attachment';
import { formatDate } from '@/recruits/utils';
import S3UrlSignerFilesService from '@services/s3urlsigner/files';
import { saveBlob } from '@utils/files';
import { isString } from 'lodash';
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';

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

  registryApi = new PersonRegistryApi();
  documentType: { label: string; value: string } | null = null;
  customDocumentType = '';
  fileForUpload: File | null = null;
  commentForFile = '';
  fileToPreview: { s3url: string; format: string } | null = null;

  @Prop()
  readonly data: ArchivedRecruitV3;

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

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

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

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

  fullName(signerInfo: SignerInfo): string {
    return signerInfo?.fullName || 'Не известно';
  }

  nameVk(signerInfo: SignerInfo): string {
    return signerInfo?.nameVK || 'Не определено';
  }

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

  sigDialogShow = false;
  signature = {
    attachment: {},
  };

  propIsSet(prop: boolean | string): boolean {
    if (isString(prop)) return prop === '';
    return prop;
  }

  showCertificate(doc: AttachmentsDocumentsV3['file']): void {
    this.signature.attachment = doc;
    this.sigDialogShow = true;
  }

  statusDocument(documentType: string): string {
    return (
      this.$store.getters['ervuDictionaries/resolutionsDocumentsDictionary'][
        documentType
      ] || '-'
    );
  }

  documentTypeIsSigned(document: AttachmentsDocumentsV3): boolean {
    return !!document?.type?.includes('Signed');
  }

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

  get systemDocumentsColumns(): RTableColumn<AttachmentsDocumentsV3>[] {
    const hasScopes = true;
    return [
      {
        name: 'name',
        label: 'Имя файла',
        field: 'file.s3Name',
        sortable: true,
        align: 'left',
      },
      {
        name: 'createdDate',
        label: 'Создано',
        field: 'createDate',
        sortable: false,
        align: 'left',
        componentPath: 'date-time',
        componentOptions: {},
        width: '120px',
      },
      {
        name: 'signerInfo',
        label: 'Сотрудник',
        field: 'signerInfo',
        sortable: false,
        align: 'left',
        style: 'width: 600px',
        width: '1fr',
        borderless: true,
      },
      {
        align: 'center',
        label: `Статус`,
        name: 'status',
        field: 'status',
        width: '200px',
        sortable: true,
        borderless: true,
        collaps: true,
      },
      {
        label: 'Действия',
        name: 'actions',
        width: '110px',
        align: 'center',
        componentPath: 'action-buttons',
        componentOptions: {
          actions:
            (hasScopes && [
              {
                icon: 'pgs-sign',
                color: 'positive',
                hide: (row: AttachmentsDocumentsV3) =>
                  !this.documentTypeIsSigned(row),
                cb: (row: AttachmentsDocumentsV3) =>
                  this.showCertificate(row.file),
                tooltipText: 'Документ подписан',
              },
              {
                icon: 'pgs-view',
                color: 'primary',
                disabled: ({ file }: AttachmentsDocumentsV3) => !file.format,
                cb: this.openFilePreview,
                tooltipText: 'Предпросмотр',
              },
              {
                icon: 'pgs-import',
                color: 'primary',
                cb: ({ file }: AttachmentsDocumentsV3) => {
                  this.fetchDocumentAttachment(
                    file,
                    'download',
                    's3Name',
                    's3url'
                  );
                  this.$recordActivity({
                    buttonCode: 'citizen_card_doc',
                    extraInfo: {
                      fileName: file.s3Name,
                      ...this.getRecruitInfo,
                    },
                  });
                },
                tooltipText: 'Скачать',
              },
            ]) ||
            [],
        },
      },
    ];
  }

  public getStatusClass(status: AttachmentsDocumentsV3['status']): string {
    switch (status) {
      case 'formed':
        return 'status-pending';
      case 'signed':
        return 'status-good';
      case 'declined':
        return 'status-bad';
      default:
        return '';
    }
  }

  public getStatusLabel(status: AttachmentsDocumentsV3['status']): string {
    const label = this.$store.getters[
      'ervuDictionaries/systemDocumentStatusesDictionary'
    ].find(({ code }: DictionariesElement) => code === status)?.value;
    return label ?? status ?? '-';
  }

  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/loadSystemDocumentStatusesDictionary'
    );
    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;
  }
}

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

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