<template>
  <div class="row q-pa-md justify-center" v-show="common.active === 'documents'">
    <div class="col-12 max-1280-width">
      <a v-show="false" ref="export" />
      <div>
        <div v-if="!hasDocuments" class="full-width text-center">
          {{ $t('documents.noDocuments') }}
        </div>
        <div v-else-if="!loading && hasDocuments">
          <DocumentTables
            :documents="documentsFiltered"
            :columns="documentsColumns"
            :common="common"
            :model="model"
            :userTask="userTask"
            :actions="actions"
          />
          <ExternalDocumentsTable 
            :data="model.externalFiles"
          />
        </div>
        <div class="row justify-end q-gutter-x-md">
          <DocumentDialog
            v-if="actions.includes(upload.button.id)"
            :key="upload.button.id"
            :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('documents.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('documents.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('documents.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('documents.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('documents.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('documents.download') }}
                        </q-item-label>
                      </q-item-section>
                    </q-item>
                  </td>
                  <td>
                    <q-item>
                      <q-item-section>
                        <q-item-label>
                          <q-btn
                            :label="$t('documents.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>
    </div>
  </div>
</template>

<script lang="ts">
// @ts-nocheck
import isEmpty from 'lodash/isEmpty';
import isEqual from 'lodash/isEqual';
import isArray from 'lodash/isArray';
import get from 'lodash/get';
import DocumentTables from './components/DocumentTables';
import ExternalDocumentsTable from './components/ExternalDocumentsTable';
import { DocTypeCode, DocTypeLabel } from '@/constants/DocumentTypes';
import { convertDateFromBackendFormat } from '@utils/format-date';
import { fetchDocumentAttachment } from '@utils/fetch-document-attachment';
import DocumentDialog from '@components/cards/statements/DocumentDialog.vue';

export default {
  props: ['common', 'model', 'user-task'],
  components: { DocumentTables, DocumentDialog, ExternalDocumentsTable },
  data() {
    return {
      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('base.add'),
          },
        },
        comment: '',
        files: [],
        isUploaded: false,
        documentTypeObject: null,
        isEdit: false,
        form: {
          regNumber: '',
          dateRegistered: '',
        },
      },
      uploadFormComponent: undefined,
      uploader: {
        showDialog: false,
      },
      preview: {
        showDialog: false,
        documentTypeObject: null,
        form: {},
        data: {
          typeName: '',
          source: '',
          modifiedDate: '',
        },
      },
      documentTypeOptions: [],
      userTaskId: '',
    };
  },
  computed: {
    serviceCard() {
      return this.$store.getters['registryService/services/servicesCard'];
    },
    hasDocuments() {
      if (
        Array.isArray(this.documentsFiltered) &&
        this.documentsFiltered.length
      ) {
        return this.documentsFiltered.some((doc) => doc.documents.length);
      }

      return false;
    },
    documentsWithoutResolutions() {
      const documents = get(this.model, 'documents');
      if (!Array.isArray(documents)) {
        return [];
      }

      return documents
        .filter((document) => !this.checkDocumentSource(document, 'result'))
        .sort(function (doc, next) {
          return doc.type.name < next.type.name ? -1 : 1;
        });
    },
    documentsFiltered() {
      return this.documentsWithoutResolutions
        .filter(
          (document) => !isEqual(document.type.code, 'archivedApplication')
        )
        .reduce(
          (res, e) => {
            switch (e.source) {
              case DocTypeCode.EPGU:
                res[0].documents.push(e);
                break;
              case DocTypeCode.CHECK:
                res[2].documents.push(e);
                break;
              case DocTypeCode.EPGU_EXTRA:
                res[3].documents.push(e);
                break;
              case DocTypeCode.SPECIALIST:
                res[4].documents.push(e);
                break;
              default:
                res[1].documents.push(e);
                break;
            }
            return res;
          },
          [
            {
              title: DocTypeLabel.EPGU,
              documents: [],
            },
            {
              title: DocTypeLabel.MVZ,
              documents: [],
            },
            {
              title: DocTypeLabel.CHECK,
              documents: [],
            },
            {
              title: DocTypeLabel.EPGU_EXTRA,
              documents: [],
            },
            {
              title: DocTypeLabel.SPECIALIST,
              documents: [],
            },
          ]
        );
    },
    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) =>
            Array.isArray(this.availableDocs) &&
            this.availableDocs.includes(doc.type)
        );
      }
      return [];
    },
    dateMask() {
      return this.$store.getters['i18N/localeMask'].date;
    },
    documentsColumns() {
      return [
        {
          align: 'left',
          field: (val) => `${get(val, 'type.name')} / ${get(val, 'file.name') || ''}` || '',
          label: `Тип документа / ${ this.$t('documents.documentName') }`,
          name: 'type',
          sortable: true,
          classes: 'text-primary-9',
        },
        {
          align: 'left',
          field: (val) => get(val, 'modified') || '',
          label: 'Изменено',
          name: 'file-modified',
          sortable: true,
          classes: 'text-primary-9',
        },
        {
          align: 'right',
          field: 'file',
          label: this.$t('documents.documentAction'),
          name: 'file',
          sortable: false,
          classes: 'text-primary-9',
        },
      ];
    },
    documentsFormKey() {
      if (this.userTask && this.userTask.userTask) {
        return this.userTask.userTask.formKey;
      }

      return undefined;
    },
    inputMask() {
      return this.$store.getters['i18N/localeMask'].input;
    },
    loading() {
      return !this.model;
    },
  },
  watch: {
    'model.system.serviceId': {
      handler(serviceId) {
        if (serviceId) {
          this.initDocumentType();
        }
      },
      immediate: true,
    },
  },
  created() {
    this.init();
  },
  methods: {
    fetchDocumentAttachment,
    isArray,
    get,

    checkDocumentSource(document, source) {
      return String(get(document, 'source')).toLowerCase() === source;
    },
    humanStorageSize(bytes) {
      if (bytes === 0) {
        return '0 б';
      }
      if (!bytes) {
        return this.$t('documents.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;
        });
    },
    async initDocumentType() {
      const comparator = this.$store.getters['i18N/localeComparator'];

      let serviceCard = this.serviceCard;

      if (isEmpty(serviceCard)) {
        serviceCard = await this.$store.dispatch(
          'registryService/services/getServiceMeta',
          {
            id: get(this.model, 'system.serviceId'),
          }
        );
      }

      const docs = 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];
      });
    },
    fetchForm(previewDocumentsFormKey) {
      console.log('qq 💩 fetchForm');
      if (this.uploadFormComponent) {
        return;
      }

      const formKey = this.documentsFormKey || previewDocumentsFormKey;

      this.uploadFormComponent = this.$GlobalComponentImporter.registerComponent(
        formKey,
        'forms/'
      );
    },
    initUploader() {
      console.log('qq initUploader');
      this.fetchForm();
      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 = ({ ...rest }) => rest;

      return cleanDoc(doc);
    },

    showUploaderModal(props, settingObj) {
      console.log('qq showUploaderModal');
      const { row } = props;

      const doc = this.model.documents.find((el) => 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, 'file.comment') || '';
      } else {
        this.upload.comment = '';
      }
      this.upload.files = [];
      this.upload.isUploaded = false;
      this.upload.documentId = row.id || '';
      this.upload.schema = row.schema || '';
      this.upload.source = row.source || '';
      this.upload.documentModified = row.modified || '';
      this.uploader.showDialog = true;

      this.fetchForm();
    },
    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>
