<template>
  <div class="Extracts">
    <centered-1280-box>
      <div class="Extracts-Header">
        <p>Сформированные выписки</p>
        <generate-extract
          v-if="isButtonsVisible"
          :is-loading="isLoading"
          @generate="generateExtract($event)"
        />
      </div>
      <re-table
        v-if="extracts.length"
        :data="extracts"
        :columns="columns"
        :pagination.sync="pagination"
        :rows-per-page-options="[10, 25, 50, 100]"
        row-key="id"
        grid-header
        @request="onRequest"
      >
        <template #body-item-actions="props">
          <div class="Extracts-Actions">
            <sign-info
              :certificate-info="props.row.certificateInfo"
              :file-info="props.row.fileInfo"
            >
              <q-icon color="green" name="pgs-sign" size="26px">
                <q-tooltip>Документ подписан</q-tooltip>
              </q-icon>
            </sign-info>
            <base-preview
              v-if="props.row.fileInfo && props.row.fileInfo.format"
              :extension="props.row.fileInfo.format"
              :s3Url="props.row.fileInfo.s3url"
            >
              <q-icon
                color="primary"
                class="Extracts-Icon"
                name="pgs-view"
                size="26px"
              >
                <q-tooltip>Предпросмотр</q-tooltip>
              </q-icon>
            </base-preview>
            <q-icon
              v-if="props.row.fileInfo && props.row.fileInfo.s3url"
              class="Extracts-Icon"
              color="primary"
              name="pgs-import"
              size="26px"
              @click="
                fetchDocumentAttachment(
                  props.row,
                  'download',
                  'fileName',
                  'fileInfo.s3url'
                )
              "
            >
              <q-tooltip>Скачать</q-tooltip>
            </q-icon>
          </div>
        </template>
      </re-table>
    </centered-1280-box>
  </div>
</template>

<script lang="ts">
import { Component, Mixins, Prop, Watch } from 'vue-property-decorator';
import ReTable from '@/recruits/components/common/r-table/index.vue';
import Centered1280Box from '@/recruits/components/common/centered-1280-box.vue';
import { RTableColumn } from '@/interfaces';
import { fetchDocumentAttachment } from '@utils/fetch-document-attachment';
import AddDocument from '@/recruits/components/dialogs/AddDocument.vue';
import GenerateExtract from '@/recruits/components/dialogs/GenerateExtract.vue';
import {
  ExtendByRecruitV3,
  ExtractServiceApi,
} from '@/recruits/openapi/ervu-service';
import { RecruitV3, Document } from '@/recruits/openapi/person-registry';
import { notifyError } from '@utils/notify';
import get from 'lodash/get';
import UrlIntegratedSearch from '@/recruits/mixins/url-integrated-search';
import { UrlQueryParams } from '@/recruits/models';
import SignInfo from '@/recruits/components/dialogs/SignInfo.vue';

const EXTRACT_SERVICE_API = new ExtractServiceApi();

@Component({
  components: {
    SignInfo,
    GenerateExtract,
    AddDocument,
    ReTable,
    Centered1280Box,
  },
  methods: {
    fetchDocumentAttachment,
    get,
  },
})
export default class Extracts extends Mixins(UrlIntegratedSearch) {
  @Prop({ type: Object, default: () => ({}) }) readonly data: RecruitV3;

  @Watch('data.systemInfo.idERN')
  onDataUpdated(): void {
    this.refresh();
  }

  isLoading = false;
  extracts: Array<ExtendByRecruitV3> = [];

  get idErn(): string {
    return this.data?.systemInfo?.idERN || '';
  }

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

  get passport(): Document | undefined {
    return this.data?.mainInfo.documents?.find(
      (document) => document.type === 'PASSPORT'
    );
  }

  generateExtract(extractType: string): void {
    if (this.idErn && this.passport) {
      this.isLoading = true;
      EXTRACT_SERVICE_API.generateExtractV2({
        format: extractType,
        idErn: this.idErn,
        series: this.passport.series,
        number: this.passport.number,
      })
        .then(({ data: { traceId } }) => {
          if (traceId) {
            const handler = (messageEvent: MessageEvent) => {
              const data = JSON.parse(get(messageEvent, 'data', '{}'));
              if (data.traceId === traceId) {
                this.refresh();
                this.isLoading = false;
                this.$websockets.removeListener(handler);
              }
            };
            this.$websockets.addListener(handler);
          }
        })
        .catch(() => {
          notifyError('Выписка не сформирована');
          this.isLoading = false;
        });
    }
  }

  async fetchData(
    query: UrlQueryParams
  ): Promise<{ totalRows: number | undefined }> {
    if (this.idErn) {
      const { data } = await EXTRACT_SERVICE_API.getExtractsV3({
        pagination: {
          sortBy: query.sortby,
          descending: query.descending === 'true',
          page: Number(query.page),
          rowsPerPage: Number(query.perpage),
        },
        search: {
          idErn: this.idErn,
        },
      });
      this.extracts = data.data || [];
      return {
        totalRows: data.totalRows || 0,
      };
    }
    return {
      totalRows: 0,
    };
  }

  get columns(): RTableColumn<ExtendByRecruitV3>[] {
    return [
      {
        label: 'Дата и время создания',
        align: 'left',
        name: 'date',
        field: 'date',
        componentPath: 'date-time',
        sortable: true,
        componentOptions: {
          time: true,
        },
        width: '15%',
      },
      {
        label: 'Номер выписки',
        name: 'number',
        field: 'number',
        align: 'left',
        type: 'gray-numbrts',
        width: '15%',
      },
      {
        label: 'Вид выписки',
        name: 'fileName',
        field: 'fileName',
        align: 'left',
        type: 'gray-numbrts',
        width: '20%',
        sortable: true,
      },
      {
        name: 'fullName',
        label: 'Инициатор',
        align: 'left',
        width: '30%',
        sortable: true,
        borderless: true,
        fields: [
          {
            label: 'Инициатор',
            name: 'peron',
            field: 'signerInfo.fullName',
            width: '100%',
            type: 'bold',
          },
          {
            name: 'nameVk',
            field: 'signerInfo.nameVK',
            width: 'auto',
            type: 'gray-numbrts',
          },
        ],
      },
      {
        label: 'Статус',
        name: 'status',
        field: 'status',
        align: 'center',
        width: '10%',
        collaps: true,
        borderless: true,
        componentPath: 'status-box',
      },
      {
        align: 'center',
        label: 'Действия',
        name: 'actions',
        width: '10%',
      },
    ];
  }
}
</script>

<style lang="scss" scoped>
.Extracts {
  &-Header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-family: 'Golos text', sans-serif;
    font-style: normal;
    font-weight: 500;
    font-size: 20px;
    line-height: 24px;
    letter-spacing: -0.015em;
    color: rgba(2, 12, 18, 0.9);
    padding-bottom: 12px;
    margin-bottom: 26px;
    border-bottom: 1px solid rgba(1, 72, 116, 0.11);
  }
  p {
    margin: 0;
  }

  &-Actions {
    display: flex;
    gap: 8px;
  }
  &-Icon {
    cursor: pointer;
    &__Not {
      color: rgba(2, 12, 18, 0.58);
      cursor: not-allowed;
    }
  }
}
</style>
