<i18n>
{
    "en": {
        "DocumentsCard": {
            "tab": "Documents",
            "documentName": "Name",
            "dateOfChange": "Date of change",
            "source": "Source",
            "documentType": "Type",
            "documentAction": "Action",
            "documentTypeLabel": "Document type",
            "addingDocument": "Adding a document",
            "documentsUploadedSuccessfully": "Documents uploaded successfully",
            "errorLoadingDocuments": "Error loading documents",
            "confirmation": "Confirmation",
            "deleteQuestion": "Are you sure you want to delete the document?",
            "yes": "Yes",
            "no": "No",
            "delete": "Delete",
            "save": "Save",
            "description": "Description",
            "signedFile": "Signed file",
            "certificatePublisher": "Certificate publisher",
            "signed": "Signed",
            "signatureIsValid": "Signature is valid",
            "signADocument": "Sign a document",
            "listOfCertificates": "List of certificates",
            "document": "Document",
            "documentSignature": "Document signature",
            "addEDS": "Add EDS",
            "viewingEDSData": "Viewing EDS data",
            "upload": "Download solution draft",
            "edit": "Edit solution attributes",
            "download": "Download",
            "preview": "Preview",
            "printForm": "Print form",
            "noData": "No data",
            "dateOfRegistrationGPZU": "Date of registration of the GPZU",
            "dateOfRegistrationContract": "Date of registration of the contract",
            "GPZURegistrationNumber": "GPZU registration number",
            "cadastralNumber": "Cadastral number",
            "noCertificatesFound": "No certificates found, please install the certificate",
            "add": "Add",
            "documentFileUrlIsEmpty": "Document file URL is empty",
            "unnamed": "Unnamed"
        }
    },
    "ru": {
        "DocumentsCard": {
            "tab": "Документы",
            "documentName": "Наименование",
            "dateOfChange": "Дата изменения",
            "source": "Источник",
            "documentType": "Тип",
            "documentAction": "Действие",
            "documentTypeLabel": "Тип документа",
            "addingDocument": "Добавление документа",
            "documentsUploadedSuccessfully": "Документы успешно загружены",
            "errorLoadingDocuments": "Ошибка при загрузке документов",
            "confirmation": "Подтверждение",
            "deleteQuestion": "Вы действительно хотите удалить документ?",
            "yes": "Да",
            "no": "Нет",
            "delete": "Удалить",
            "save": "Сохранить",
            "description": "Описание",
            "signedFile": "Файл с подписью",
            "certificatePublisher": "Издатель сертификата",
            "signed": "Подписано",
            "signatureIsValid": "Подпись достоверна",
            "signADocument": "Подписать документ",
            "listOfCertificates": "Список сертификатов",
            "document": "Документ",
            "documentSignature": "Подпись документа",
            "addEDS": "Добавить ЭЦП",
            "viewingEDSData": "Просмотр данных об ЭЦП",
            "upload": "Загрузить проект решения",
            "edit": "Редактировать атрибуты решения",
            "download": "Скачать",
            "preview": "Предпросмотр",
            "printForm": "Печатная форма",
            "noData": "Нет данных",
            "dateOfRegistrationGPZU": "Дата регистрации ГПЗУ",
            "dateOfRegistrationContract": "Дата регистрации договора",
            "GPZURegistrationNumber": "Регистрационный номер ГПЗУ",
            "cadastralNumber": "Кадастровый номер",
            "noCertificatesFound": "Сертификаты не найдены, пожалуйста, установите сертификат",
            "add": "Добавить",
            "documentFileUrlIsEmpty": "Отсутствует ссылка на файл",
            "unnamed": "Безымянный"
        }
    }
}
</i18n>

<template>
  <div class="row q-pa-md justify-center" v-if="common.active === 'documents_resolution'">
    <div class="col-12 max-1280-width">
      <a v-show="false" ref="export" />
      <div class="column q-gutter-y-md">
        <div class="ResolutionDocument-DocumentBlock">
          <span class="ResolutionDocument-Header">Решение</span>
          <div class="ResolutionDocument-Data"
            v-for="document in documentsResolutions"
            v-if="document.source === 'Result' && document.type.code !== 'AdditionalResultDocument'"
          >
            <div class="row q-col-gutter-sm">
              <div class="col-8 col-md-9 col-lg-10">
                <data-block :form-data="{ label: 'Тип документа' }">{{ document.type.name }}</data-block>
              </div>
              <div class="col-4 col-md-3 col-lg-2">
                <data-block :form-data="{ label: 'Дата изменения' }">{{ parseUnixTime(document.modified).format("DD.MM.YYYY HH:mm") }}</data-block>
              </div>
              <div class="col-12">
                <data-block :form-data="{ label: 'Номер решения'}">
                  {{ document.number }}
                </data-block>
              </div>
              <div class="col-12">
                <data-block :form-data="{ label: 'Заявитель'}">{{ document.resApplicant || '&nbsp;' }}</data-block>
              </div>
              <div class="col-12">
                <data-block class="ResolutionDocument-File" :form-data="{ icon: 'pgs-document' }">
                  <template v-slot:badge>
                    <div class="column q-px-sm" style="flex-grow: 1">
                      <span class="ResolutionDocument-FileType">{{ document.type.name }}</span>
                      <span class="ResolutionDocument-FileName">{{ stripFileName(document) }}</span>
                    </div>
                    <div class="ResolutionDocument-FileButtons">
                      <base-preview
                        :extension="document.file.name.split('.').pop()"
                        :s3-url="document.file.url"
                      >
                        <q-btn
                          flat
                          dense
                          :icon="icons.view"
                          color="primary"
                        >
                          <template #loading>
                            <q-spinner-gears />
                          </template>
                          <q-tooltip>
                            {{ $t('DocumentsCard.preview') }}
                          </q-tooltip>
                        </q-btn>
                      </base-preview>
                      <q-btn
                        v-if="false"
                        :disable="!get(documents, 'file.url')"
                        flat
                        dense
                        :icon="icons.view"
                        style="color: rgba(0, 0, 0, 0.54)"
                        @click="fetchDocumentAttachment(documents)"
                      >
                        <q-tooltip>
                          {{ $t('DocumentsCard.preview') }}
                        </q-tooltip>
                      </q-btn>
                      <q-btn
                        :disable="!get(document, 'file.url')"
                        target="_blank"
                        flat
                        dense
                        :icon="icons.download"
                        @click="fetchDocumentAttachment(document, 'download')"
                      >
                        <q-tooltip>
                          {{ $t('DocumentsCard.download') }}
                        </q-tooltip>
                      </q-btn>
                      <q-btn
                        flat
                        v-if="document.sign"
                        dense
                        :icon="icons.validSignature"
                        @click="signatureHandler(document, 'info')"
                      >
                        <q-tooltip>
                          {{ $t('DocumentsCard.viewingEDSData') }}
                        </q-tooltip>
                      </q-btn>
                      <div
                        v-show="
                        document.source !== 'ЕПГУ' &&
                        (actions.includes('uploadDocument') ||
                          actions.includes('addDocument')) &&
                        document.generated
                      "
                      >
                        <DocumentEditDialog
                          :key="document.id"
                          :common="common"
                          :row="document"
                          :model="model"
                          :user-task="userTask"
                        >
                          <template #button>
                            <q-btn
                              flat
                              dense
                              :icon="icons.edit"
                            >
                              <q-tooltip max-width="200px">
                                {{ $t('DocumentsCard.edit') }}
                              </q-tooltip>
                            </q-btn>
                          </template>
                        </DocumentEditDialog>
                      </div>
                      <div
                        v-show="
                        document.source !== 'ЕПГУ' &&
                        actions.includes('uploadDocument') &&
                        document.generated
                      "
                      >
                        <DocumentUploaderDialog
                          :key="document.id"
                          :common="common"
                          :row="document"
                          :model="model"
                          :user-task="userTask"
                        >
                          <template #button>
                            <q-btn
                              flat
                              dense
                              :icon="icons.up"
                            >
                              <q-tooltip>
                                {{ $t('DocumentsCard.upload') }}
                              </q-tooltip>
                            </q-btn>
                          </template>
                        </DocumentUploaderDialog>
                      </div>
                      <div
                        v-if="
                        !document.generated &&
                        actions.includes('updateAdditionalResultDocument')
                      "
                      >
                        <AdditionalResultDocumentDialog
                          :key="document.id"
                          :common="common"
                          :row="document"
                          :model="model"
                          :user-task="userTask"
                        >
                          <template #button>
                            <q-btn
                              flat
                              dense
                              :icon="icons.up"
                            >
                              <q-tooltip>
                                {{ $t('DocumentsCard.upload') }}
                              </q-tooltip>
                            </q-btn>
                          </template>
                        </AdditionalResultDocumentDialog>
                      </div>
                      <q-btn
                        flat
                        v-show="false"
                        dense
                        :icon="icons.template"
                        @click="
                        fetchDocumentAttachment(
                          document,
                          'download',
                          'template.name',
                          'template.url'
                        )
                      "
                      />
                      <q-btn
                        flat
                        v-if="
                        !document.generated &&
                        actions.includes('deleteAdditionalResultDocument')
                      "
                        dense
                        :icon="icons.delete"
                        @click="showDeleteDialog(document)"
                      >
                        <q-tooltip>
                          {{ $t('DocumentsCard.delete') }}
                        </q-tooltip>
                      </q-btn>
                    </div>
                  </template>
                </data-block>
              </div>
            </div>
          </div>
        </div>
        <div class="ResolutionDocument-DocumentBlock">
          <span class="ResolutionDocument-Header">Дополнительные документы</span>
          <div class="ResolutionDocument-Data q-gutter-xs">
            <div class="ResolutionDocument-RowHeader">
              <span>Тип документа</span>
              <span>Наименование</span>
              <span class="text-right">Изменено</span>
              <span class="text-right">Действия</span>
            </div>
            <div class="ResolutionDocument-Row"
              v-for="document in documentsResolutions"
              v-if="document.source === 'Result' && document.type.code === 'AdditionalResultDocument'"
            >
              <span class="ResolutionDocument-TypeName">{{ document.type.name }}</span>
              <span class="ResolutionDocument-FileName">{{ document.file.name }}</span>
              <span class="ResolutionDocument-Modified">{{ parseUnixTime(document.modified).format("DD.MM.YYYY HH:mm") }}</span>
              <div class="ResolutionDocument-FileButtons justify-end">
                <base-preview
                  :extension="document.file.name.split('.').pop()"
                  :s3-url="document.file.url"
                >
                  <q-btn
                    flat
                    dense
                    :icon="icons.view"
                  >
                    <template #loading>
                      <q-spinner-gears />
                    </template>
                    <q-tooltip>
                      {{ $t('DocumentsCard.preview') }}
                    </q-tooltip>
                  </q-btn>
                </base-preview>
                <div>
                <q-btn
                  v-if="false"
                  :disable="!get(documents, 'file.url')"
                  flat
                  dense
                  :icon="icons.view"
                  @click="fetchDocumentAttachment(documents)"
                  class="ResolutionDocument-IconButton"
                >
                  <q-tooltip>
                    {{ $t('DocumentsCard.preview') }}
                  </q-tooltip>
                </q-btn>
                </div>
                <div>
                <q-btn
                  :disable="!get(document, 'file.url')"
                  target="_blank"
                  flat
                  dense
                  :icon="icons.download"
                  @click="fetchDocumentAttachment(document, 'download')"
                >
                  <q-tooltip>
                    {{ $t('DocumentsCard.download') }}
                  </q-tooltip>
                </q-btn>
                </div>
                <div>
                <q-btn
                  flat
                  v-if="document.sign"
                  dense
                  :icon="icons.validSignature"
                  @click="signatureHandler(document, 'info')"
                >
                  <q-tooltip>
                    {{ $t('DocumentsCard.viewingEDSData') }}
                  </q-tooltip>
                </q-btn>
                </div>
                <div
                  v-show="
                    document.source !== 'ЕПГУ' &&
                    (actions.includes('uploadDocument') ||
                      actions.includes('addDocument')) &&
                    document.generated
                  "
                >
                  <DocumentEditDialog
                    :key="document.id"
                    :common="common"
                    :row="document"
                    :model="model"
                    :user-task="userTask"
                  >
                    <template #button>
                      <q-btn
                        flat
                        dense
                        :icon="icons.edit"
                      >
                        <q-tooltip max-width="200px">
                          {{ $t('DocumentsCard.edit') }}
                        </q-tooltip>
                      </q-btn>
                    </template>
                  </DocumentEditDialog>
                </div>
                <div
                  v-show="
                    document.source !== 'ЕПГУ' &&
                    actions.includes('uploadDocument') &&
                    document.generated
                  "
                >
                  <DocumentUploaderDialog
                    :key="document.id"
                    :common="common"
                    :row="document"
                    :model="model"
                    :user-task="userTask"
                  >
                    <template #button>
                      <q-btn
                        flat
                        dense
                        :icon="icons.up"
                      >
                        <q-tooltip>
                          {{ $t('DocumentsCard.upload') }}
                        </q-tooltip>
                      </q-btn>
                    </template>
                  </DocumentUploaderDialog>
                </div>
                <div
                  v-if="
                    !document.generated &&
                    actions.includes('updateAdditionalResultDocument')
                  "
                >
                  <AdditionalResultDocumentDialog
                    :key="document.id"
                    :common="common"
                    :row="document"
                    :model="model"
                    :user-task="userTask"
                  >
                    <template #button>
                      <q-btn
                        flat
                        dense
                        :icon="icons.up"
                      >
                        <q-tooltip>
                          {{ $t('DocumentsCard.upload') }}
                        </q-tooltip>
                      </q-btn>
                    </template>
                  </AdditionalResultDocumentDialog>
                </div>
                <div>
                <q-btn
                  flat
                  v-show="false"
                  dense
                  :icon="icons.template"
                  @click="
                    fetchDocumentAttachment(
                      document,
                      'download',
                      'template.name',
                      'template.url'
                    )
                  "
                />
                </div>
                <div>
                <q-btn
                  flat
                  v-if="
                    !document.generated &&
                    actions.includes('deleteAdditionalResultDocument')
                  "
                  dense
                  :icon="icons.delete"
                  color="negative"
                  @click="showDeleteDialog(document)"
                >
                  <q-tooltip>
                      {{ $t('DocumentsCard.delete') }}
                  </q-tooltip>
                </q-btn>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="row justify-end q-gutter-x-md">
          <AdditionalResultDocumentDialog
            v-if="actions.includes('addAdditionalResultDocument')"
            :key="'addAdditionalResultDocument'"
            :common="common"
            :button-settings="upload.button"
            :model="model"
            :user-task="userTask"
            @submit="submit"
          />          
        </div>
      </div>
      <q-dialog v-model="signature.dialog.value">
        <q-card class="full-width no-shadow" style="max-width: 480px">
          <q-card-section>
            <div class="text-h6">
              {{ $t('DocumentsCard.documentSignature') }}
            </div>
          </q-card-section>
          <template v-if="signature.dialog.type === 'info'">
            <q-card-section class="q-gutter-y-md">
              <q-banner class="bg-grey-1">
                <template #avatar>
                  <q-icon color="positive" name="check_circle_outline" />
                </template>
                <div>{{ $t('DocumentsCard.signatureIsValid') }}</div>
              </q-banner>
              <table v-if="signature.attachment" class="text-primary">
                <tr>
                  <td>
                    <q-item>
                      <q-item-section>
                        <q-item-label class="text-grey-9">
                          {{ $t('DocumentsCard.signed') }}
                        </q-item-label>
                      </q-item-section>
                    </q-item>
                  </td>
                  <td>
                    <q-item>
                      <q-item-section>
                        <q-item-label>
                          {{
                            get(
                              signature.attachment,
                              'sign.certificate.subjectName'
                            )
                          }}
                        </q-item-label>
                      </q-item-section>
                    </q-item>
                  </td>
                </tr>
                <tr>
                  <td>
                    <q-item>
                      <q-item-section>
                        <q-item-label class="text-grey-9">
                          {{ $t('DocumentsCard.certificatePublisher') }}
                        </q-item-label>
                      </q-item-section>
                    </q-item>
                  </td>
                  <td>
                    <q-item>
                      <q-item-section>
                        <q-item-label>
                          {{
                            get(
                              signature.attachment,
                              'sign.certificate.issuerName'
                            )
                          }}
                        </q-item-label>
                      </q-item-section>
                    </q-item>
                  </td>
                </tr>
                <tr>
                  <td>
                    <q-item>
                      <q-item-section>
                        <q-item-label class="text-grey-9">
                          {{ $t('DocumentsCard.document') }}
                        </q-item-label>
                      </q-item-section>
                    </q-item>
                  </td>
                  <td>
                    <q-item>
                      <q-item-section>
                        <q-item-label>
                          {{ get(signature.attachment, 'file.name') }}
                        </q-item-label>
                      </q-item-section>
                    </q-item>
                  </td>
                </tr>
                <tr>
                  <td>
                    <q-item>
                      <q-item-section>
                        <q-item-label class="text-grey-9">
                          {{ $t('DocumentsCard.download') }}
                        </q-item-label>
                      </q-item-section>
                    </q-item>
                  </td>
                  <td>
                    <q-item>
                      <q-item-section>
                        <q-item-label>
                          <q-btn
                            :label="$t('DocumentsCard.signedFile')"
                            icon="attach_file"
                            outline
                            @click="
                              fetchDocumentAttachment(
                                signature.attachment,
                                'download',
                                'sign.name',
                                'sign.url'
                              )
                            "
                          />
                        </q-item-label>
                      </q-item-section>
                    </q-item>
                  </td>
                </tr>
              </table>
            </q-card-section>
          </template>
        </q-card>
      </q-dialog>
      <q-dialog v-model="deleteDocuments.dialog.value">
        <q-card class="no-shadow">
          <q-card-section>
            <div class="text-h6">{{ $t('DocumentsCard.confirmation') }}</div>
          </q-card-section>
          <q-card-section class="q-pt-none">
            {{ $t('DocumentsCard.deleteQuestion') }}
          </q-card-section>
          <q-card-actions align="right">
            <q-btn
              flat
              :label="$t('DocumentsCard.no')"
              color="primary"
              @click="hideDeleteDialog"
            />
            <q-btn
              flat
              :label="$t('DocumentsCard.yes')"
              color="red"
              @click="deleteDocument"
            />
          </q-card-actions>
        </q-card>
      </q-dialog>
    </div>
  </div>
</template>

<script lang="ts">
// @ts-nocheck
import { saveAs } from 'file-saver';
import {
  convertDateFromTimestamp,
  convertDateFromBackendFormat,
} from '@utils/format-date';
import { DateFormat } from '@constants/utils/format-date';
import { saveFileViaLink } from '@utils/files';
import { mapState } from 'vuex';
import { Application } from '@interfaces/entities/Application';
import { ServiceFileNameFactory } from '@utils/file/ServiceFileNameFactory';
import { Document } from '@interfaces/entities/Document/Document';
import ServiceService from '@services/entities/ServiceService';
import { DocumentPrototype } from '@interfaces/entities/Document/DocumentPrototype';
import S3UrlSignerFilesService from '@services/s3urlsigner/files';
import get from 'lodash/get';
import { WorkflowServiceApi } from '@openapi/wf';
import { notifyError } from '@utils/notify';
import moment from 'moment';
import DocumentPreviewDialog from '@components/cards/statements/DocumentPreviewDialog.vue';
import DocumentEditDialog from '@components/cards/statements/DocumentEditDialog.vue';
import DocumentUploaderDialog from '@components/cards/statements/DocumentUploaderDialog.vue';
import AdditionalResultDocumentDialog from '@components/cards/statements/AdditionalResultDocumentDialog.vue';
import dataBlock from "@components/cards/statements/components/dataBlock.vue";
const wfApi = new WorkflowServiceApi();

export default {
  name: 'DocumentsResolution',
  components: {
    DocumentPreviewDialog,
    DocumentEditDialog,
    DocumentUploaderDialog,
    AdditionalResultDocumentDialog,
    dataBlock
  },
  props: ['common', 'model', 'user-task'],
  data() {
    return {
      icons: {
        eds: 'gesture',
        validSignature: 'gesture',
        view: 'pgs-search',
        template: 'pgs-print',
        download: 'pgs-import',
        delete: 'pgs-delete',
        up: 'pgs-paperclip',
        edit: 'pgs-edit',
      },
      pagination: {
        rowsPerPage: 0,
      },
      signature: {
        attachment: null,
        certificate: null,
        certificates: [],
        dialog: {
          type: '',
          value: false,
        },
        isValidSystemSetup: false,
        loading: false,
      },
      upload: {
        button: {
          actions: {
            click: this.initUploader,
          },
          id: 'addDocument',
          props: {
            color: 'primary',
            label: this.$t('DocumentsCard.add'),
          },
        },
        comment: '',
        files: [],
        isUploaded: false,
        documentTypeObject: null,
        isEdit: false,
        form: {
          regNumber: '',
          dateRegistered: '',
        },
      },
      uploader: {
        showDialog: false,
      },
      preview: {
        showDialog: false,
        documentTypeObject: null,
        form: {},
        data: {
          typeName: '',
          source: '',
          modifiedDate: '',
        },
      },
      documentTypeOptions: [],
      userTaskId: '',
      deleteDocuments: {
        button: {
          id: 'deleteAdditionalResultDocument',
        },
        documents: [],
        dialog: {
          value: false,
        },
      },
    };
  },
  computed: {
    ...mapState('documentRegistry', {
      application: (state) => state.dictionaries as Application, // Хз, правильное ли это имя, взял, орентируясь на эндпоинт
    }),
    documentsResolutions() {
      const documents = get(this.model, 'documents');

      if (!Array.isArray(documents)) {
        return [];
      }

      return documents.filter((document) => {
        return String(get(document, 'source')).toLowerCase() === 'result';
      });
    },
    actions() {
      return get(this.userTask, 'userTask.outData.actions') || [];
    },
    availableDocs() {
      return get(
        this.userTask,
        `userTask.outData.availableDocs["${this.upload.button.id}"]`,
        []
      );
    },
    availableDocumentTypeOptions() {
      if (this.documentTypeOptions && this.availableDocs) {
        return this.documentTypeOptions.filter((doc) => {
          return (
            Array.isArray(this.availableDocs) &&
            this.availableDocs.includes(doc.type)
          );
        });
      }
      return [];
    },
    dateMask() {
      return this.$store.getters['i18N/localeMask'].date;
    },
    markeredDocuments() {
      return (get(this.$route, 'query.markeredDocuments') || '').split(',');
    },
    documentsColumns() {
      return [
        {
          align: 'left',
          field: (val) => get(val, 'type.name') || '',
          label: this.$t('DocumentsCard.documentType'),
          name: 'type',
          sortable: true,
        },
        {
          align: 'left',
          field: (val) => get(val, 'file.name') || '',
          label: this.$t('DocumentsCard.documentName'),
          name: 'file.name',
          sortable: true,
        },
        {
          align: 'left',
          field: 'file',
          label: this.$t('DocumentsCard.documentAction'),
          name: 'file',
          sortable: false,
        },
      ];
    },
    documentsFormKey() {
      if (this.userTask && this.userTask.userTask) {
        return this.userTask.userTask.formKey;
      } else {
        return undefined;
      }
    },
    inputMask() {
      return this.$store.getters['i18N/localeMask'].input;
    },
    loading() {
      return !this.model;
    },
    serviceCard() {
      return this.$store.getters['registryService/services/servicesCard'];
    },
  },
  created() {
    this.init();
  },
  methods: {
    get,
    // Доделать утилиту под данный случай
    async fetchDocumentAttachment(
      document: Document,
      mode = 'preview',
      nameField = 'file.name',
      urlField = 'file.url'
    ) {
      const service = await ServiceService.get(
        this.model?.system?.serviceId,
        'documents'
      );
      const documentPrototype = ((service as unknown) as {
        documents: DocumentPrototype[];
      }).documents.find((doc) => doc.code === document.type.code);

      const fileName =
        ServiceFileNameFactory.create(this.model, documentPrototype) ??
        get(document, nameField) ??
        this.$t('DocumentsCard.unnamed').toString();
      const url = get(document, urlField);

      if (url) {
        S3UrlSignerFilesService.fetchFileFromS3ByUrl({ url })
          .then(({ presignedUrl, file }) => {
            switch (mode) {
              case 'download': {
                saveAs(file, fileName);
                break;
              }
              case 'preview': {
                saveFileViaLink({
                  anchor: this.$refs.export,
                  hrefData: presignedUrl,
                  fileName,
                  target: '_blank',
                });
                break;
              }
            }
          })
          .catch((e) => {
            notifyError(e.message.toString());
          });
      } else {
        notifyError(this.$t('DocumentsCard.documentFileUrlIsEmpty').toString());
      }
    },
    signatureHandler(attachment, dialogType) {
      this.signature.attachment = attachment;
      this.signature.dialog.type = dialogType;

      switch (dialogType) {
        case 'create':
          this.$store
            .dispatch('utils/cryptoPro/fetchCertificates')
            .then((certificates) => {
              this.signature.certificates = certificates.map((certificate) => {
                return {
                  label: certificate.subjectName,
                  value: certificate,
                };
              });

              if (this.signature.certificates.length) {
                this.signature.dialog.value = true;
              } else {
                notifyError(
                  this.$t('DocumentsCard.noCertificatesFound'),
                  'warning',
                  'warning'
                );
              }
            })
            .catch((e) => {
              notifyError(e.message.toString());
            });

          break;
        case 'info':
          this.signature.dialog.value = true;
          // attachment.signatureInfo - тут лежит инфа о подписи

          break;
      }
    },
    showDeleteDialog(document) {
      this.deleteDocuments.documents = [document];

      this.deleteDocuments.dialog.value = true;
    },
    hideDeleteDialog() {
      this.deleteDocuments.documents = [];

      this.deleteDocuments.dialog.value = false;
    },
    deleteDocument() {
      wfApi.submitForm(get(this.userTask, 'userTask.taskId'), {
        id: this.deleteDocuments.button.id,
        data: {
          docIds: this.deleteDocuments.documents.map((document) => document.id),
        },
      });

      this.hideDeleteDialog();
    },
    humanStorageSize(bytes) {
      if (bytes === 0) return '0 б';
      if (!bytes) return this.$t('DocumentsCard.noData');

      const k = 1024;
      const dm = 2;
      const sizes = ['б', 'Кб', 'Мб', 'Гб', 'Тб', 'Пб'];

      const i = Math.floor(Math.log(bytes) / Math.log(k));

      return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
    },
    init() {
      this.$store
        .dispatch('utils/cryptoPro/isValidSystemSetup')
        .then((isValid) => {
          this.signature.isValidSystemSetup = isValid;
        });

      this.initDocumentType();
    },
    initDocumentType() {
      const comparator = this.$store.getters['i18N/localeComparator'];
      const docs = this.serviceCard?.documents;

      if (docs) {
        this.documentTypeOptions = docs
          .map((document) => ({
            label: document.name,
            type: document.code,
            data: document,
          }))
          .sort((a, b) => comparator(a.label, b.label));
      }
    },
    updateUploadFormModel(model, formKey) {
      Object.keys(model).forEach((key) => {
        this[formKey].form[key] = model[key];
      });
    },
    initUploader() {
      this.upload.isEdit = false;
      this.upload.documentTypeObject = null;
      this.upload.comment = '';
      this.upload.files = [];
      this.upload.isUploaded = false;
      this.upload.form.regNumber = '';
      this.upload.form.dateRegistered = '';
      this.upload.documentId = '';
      this.uploader.showDialog = true;
    },
    getDocumentUploadFormFields(doc) {
      const cleanDoc = ({
        type,
        hidden,
        id,
        modified,
        schema,
        source,
        ...rest
      }) => {
        return rest;
      };

      return cleanDoc(doc);
    },

    showUploaderModal(props, settingObj) {
      const row = props.row;

      const doc = this.model.documents.find((el) => {
        return el.id === row.id;
      });

      if (doc) {
        const form = this.getDocumentUploadFormFields(doc);
        this.updateUploadFormModel(form, 'upload');
      } else {
        this.upload.form.regNumber = row.regNumber || '';
        this.upload.form.dateRegistered =
          convertDateFromBackendFormat(row.dateRegistered) || '';
      }

      this.upload.isEdit = true;
      this.upload.documentTypeObject =
        this.documentTypeOptions.find(
          (document) => document.type === row.type.code
        ) || null;
      if (get(settingObj, 'isEditButton')) {
        this.upload.comment = get(row, 'comment') || '';
      } else {
        this.upload.comment = '';
      }
      this.upload.files = [];
      this.upload.isUploaded = false;
      this.upload.documentId = row.id || '';
      this.upload.schema = row.schema || '';
      this.upload.documentModified = row.modified || '';
      this.uploader.showDialog = true;
    },
    showDocPreviewModal(props) {
      const row = get(props, 'row');

      this.preview.data.typeName = get(row, 'type.name') || '';
      this.preview.data.source = get(row, 'source') || '';
      this.preview.data.modifiedDate = '';
      const modifiedTimestamp = row.modified;

      if (modifiedTimestamp) {
        this.preview.data.modifiedDate = convertDateFromTimestamp(
          modifiedTimestamp,
          DateFormat.date
        );
      }

      const doc = this.model.documents.find((el) => {
        return el.id === row.id;
      });

      if (doc) {
        this.preview.documentTypeObject =
          this.documentTypeOptions.find(
            (document) => document.type === doc.type.code
          ) || null;
        const form = this.getDocumentUploadFormFields(doc);
        this.updateUploadFormModel(form, 'preview');
        this.preview.showDialog = true;
      }
    },
    stripFileName(document) {
      if (document.file?.name && document.type?.name) {
        return document.file.name.replace(document.type.name, '').trim();
      }
      return document.file?.name || '';
    },
    parseUnixTime(integer) {
      return moment.unix(integer);
    },
    submit({ buttonId, data }) {
      const requestBody = {
        id: buttonId,
      };

      if (data) {
        requestBody.data = data;
      }

      const taskId = get(this.userTask, 'userTask.taskId');

      this.$emit('submit', {
        requestBody,
        taskId,
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.ResolutionDocument {
  &-Modified {
    font-family: 'Golos UI', sans-serif;
    font-style: normal;
    font-weight: 400;
    font-size: 12px;
    line-height: 14px;
    color: rgba(2, 12, 18, 0.58);
    text-align: right;
  }
  &-FileType {
    font-size: 12px;
    line-height: 14px;
    font-weight: 500;
  }
  &-FileName {
    word-break: break-word;
    font-family: 'Golos UI', sans-serif;
    font-style: normal;
    font-weight: 400;
    font-size: 12px;
    line-height: 14px;
    color: rgba(2, 12, 18, 0.58);
  }
  &-TypeName {
    font-family: 'Golos UI', sans-serif;
    font-style: normal;
    font-weight: 500;
    font-size: 14px;
    line-height: 16px;
    color: rgba(2, 12, 18, 0.9);
  }
  &-RowHeader {
    display: grid;
    grid-template-columns: 2fr 2fr 1fr 1.4fr;
    padding: 8px;
    font-family: 'Golos Text', sans-serif;
    font-style: normal;
    font-weight: 600;
    font-size: 10px;
    line-height: 12px;
    letter-spacing: 0.05em;
    text-transform: uppercase;
    color: rgba(2, 12, 18, 0.58);
  }
  &-Row {
    display: grid;
    grid-template-columns: 2fr 2fr 1fr 1.4fr;
    padding: 8px;

    background: rgba(38, 117, 166, 0.025);
    border: 1px solid rgba(1, 72, 116, 0.11);
    border-radius: 8px;
  }
  &-DocumentBlock {
    display: flex;
    font-family: 'Golos Text', sans-serif;
  }
  &-Header {
    flex-basis: 30%;
    font-style: normal;
    font-weight: 400;
    font-size: 18px;
    line-height: 22px;
    letter-spacing: -0.015em;
    color: rgba(2, 12, 18, 0.9);
  }
  &-Data {
    flex-basis: 70%;
    width: 100%;
  }
  &-FileButtons {
    display: flex;
    color: #107ABC;
    font-size: 12px
  }
  &-IconButton {
    font-size: 12px;
  }
}
</style>
