<template>
  <div class="Documents">
    <r-spoiler-section
      title="Системные документы"
      :counter="systemDocuments.length"
      :bordered="true"
    >
      <r-table
        :data="systemDocuments"
        :columns="systemDocumentsColumns"
        :hide-pagination="true"
        :rows-per-page-options="[0]"
      >
        <template #body-item-employeeInfo="{ row }">
          <div class="Documents__Cell Documents__Cell_Signer">
            <template
              v-if="row.status === 'signed' && displayInfo(row.signerInfo)"
            >
              <span>{{ row.signerInfo.fullName }}</span>
              <span>{{ row.signerInfo.nameVK }}</span>
            </template>
            <template v-else-if="displayInfo(row.employeeInfo)">
              <span>{{ row.employeeInfo.fullName }}</span>
              <span>{{ row.employeeInfo.nameVK }}</span>
            </template>
            <span v-else>—</span>
          </div>
        </template>
        <template #body-item-status="{ row }">
          <status-box
            :status="getStatusLabel(row.status)"
            borderless
            :class="[
              getStatusClass(row.status),
              'Documents Documents__Cell Documents__Cell_Status',
            ]"
          />
        </template>
      </r-table>
    </r-spoiler-section>
    <base-preview
      v-if="fileToPreview && fileToPreview.s3url"
      :without-trigger="true"
      :s3Url="fileToPreview.s3url"
      :extension="fileToPreview.format"
      @close="fileToPreview = null"
    />
    <sign-info
      v-if="certificatePreview"
      :without-trigger="true"
      :certificate-info="certificatePreview.info"
      :file-info="certificatePreview.file"
      @close="certificatePreview = null"
    />
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';
import { DataForRecruit } from '../masthead/interfaces';
import RTable from '@/recruits/components/common/r-table/index.vue';
import RSpoilerSection from '@/recruits/components/common/r-spoiler-section.vue';
import SignInfo from '@/recruits/components/dialogs/SignInfo.vue';
import StatusBox from '@/recruits/components/common/status-box/index.vue';
import {
  AttachmentsDocumentsV3,
  CertificateInfo,
  DictionariesElement,
  RecruitV3,
  S3File,
  SignerInfo,
} from '@/recruits/openapi/person-registry';
import { RTableColumn } from '@/interfaces';
import { formatDate } from '@/recruits/utils';
import { fetchDocumentAttachment } from '@/utils/fetch-document-attachment';

@Component({
  components: {
    RTable,
    RSpoilerSection,
    SignInfo,
    StatusBox,
  },
})
export default class SystemDocuments extends Vue {
  @Prop()
  readonly data: DataForRecruit;

  fileToPreview: { s3url: string; format: string } | null = null;
  certificatePreview: {
    info: CertificateInfo | undefined;
    file: S3File;
  } | null = null;

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

  get systemDocumentsColumns(): RTableColumn<AttachmentsDocumentsV3>[] {
    return [
      {
        name: 'name',
        label: 'Имя файла',
        field: 'file.s3Name',
        sortable: true,
        align: 'left',
      },
      {
        name: 'createdDate',
        label: 'Дата и время создания',
        field: 'createDate',
        align: 'center',
        componentPath: 'date-time',
        componentOptions: {
          time: true,
        },
        width: '180px',
      },
      {
        name: 'employeeInfo',
        label: 'Сотрудник',
        field: 'employeeInfo',
        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: '128px',
        align: 'center',
        componentPath: 'action-buttons',
        componentOptions: {
          actions: [
            {
              icon: 'pgs-sign',
              hide: (row: AttachmentsDocumentsV3) => row.status !== 'signed',
              color: 'positive',
              cb: (row: AttachmentsDocumentsV3) => this.showCertificate(row),
              tooltipText: 'Документ подписан',
            },
            {
              icon: 'pgs-import',
              color: 'primary',
              cb: ({ file }: AttachmentsDocumentsV3) => {
                fetchDocumentAttachment(file, 'download', 's3Name', 's3url');
                this.$recordActivity({
                  buttonCode: 'citizen_card_doc',
                  extraInfo: {
                    fileName: file.s3Name,
                    ...this.getRecruitInfo,
                  },
                });
              },
              tooltipText: 'Скачать',
            },

            {
              icon: 'pgs-view',
              color: 'primary',
              disabled: ({ file }: AttachmentsDocumentsV3) => !file.format,
              cb: this.openFilePreview,
              tooltipText: 'Предпросмотр',
            },
          ],
        },
      },
    ];
  }

  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;
  }

  showCertificate(row: AttachmentsDocumentsV3): void {
    this.certificatePreview = {
      info: row?.certificateInfo,
      file: row?.file,
    };
  }

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

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

  getStatusClass(status: AttachmentsDocumentsV3['status']): string {
    switch (status) {
      case 'signed':
        return '_Good';
      case 'declined':
        return '_Bad';
      default:
        return '';
    }
  }

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

<style lang="scss" scoped>
.Documents {
  &__Cell {
    &_Signer {
      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);
      }
    }

    &_Status {
      &._Bad {
        background: #fdf3ed;
        color: #cf5f14;
        border-color: #cf5f14;
      }
      &._Good {
        background: #e3fefa;
        color: #04967d;
        border-color: #04967d;
      }
    }
  }
}

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