<template>
  <div v-if="common.active === 'documents_template'">
    <a ref="downloadBpmn" />
    <q-card class="no-shadow q-gutter-y-md q-mx-md no-border-radius">
      <a ref="export" v-show="false" />
      <div
        class="q-gutter-y-md bg-white q-px-lg q-pb-md q-pt-sm q-mt-md q-mx-md rounded-borders"
      >
        <div class="flex justify-end q-px-md q-my-md row" style="width: 100%">
          <div>
            <q-btn
              v-if="
                card.state === 'IN_PROCESS' &&
                $AC.haveScope(USER_SCOPES.SOCIAL_SETTINGS_PAYMENT_ADMIN)
              "
              color="primary"
              text-color="white"
              icon="add_box"
              label="Новый шаблон"
              class="q-mr-md"
              @click="addTemplate"
            >
            </q-btn>
          </div>
        </div>
        <q-table
          :data="documents"
          :columns="columns"
          class="no-shadow text-grey-9"
          row-key="id"
          title-class="text-subtitle1"
          :rows-per-page-options="[10, 20, 50]"
          wrap-cells
        >
          <template #body-cell-file="props">
            <q-td :props="props">
              <div class="row no-wrap text-no-wrap float-right">
                <q-btn
                  flat
                  icon="arrow_downward"
                  style="color: rgba(0, 0, 0, 0.54)"
                  color="primary"
                  @click="downloadFile(props.row)"
                >
                  <q-tooltip>
                    {{ $t('documents.download') }}
                  </q-tooltip>
                </q-btn>
                <q-btn
                  v-if="
                    $AC.haveScope(USER_SCOPES.SOCIAL_SETTINGS_PAYMENT_ADMIN)
                  "
                  icon="attach_file"
                  text-color="primary"
                  @click="addDocumentAttachment(props.row)"
                >
                  <q-tooltip :delay="500">Загрузить</q-tooltip>
                </q-btn>
                <q-btn
                  v-if="
                    $AC.haveScope(USER_SCOPES.SOCIAL_SETTINGS_PAYMENT_ADMIN)
                  "
                  icon="edit"
                  text-color="primary"
                  @click="edit(props.row)"
                >
                  <q-tooltip :delay="500"> Редактировать</q-tooltip>
                </q-btn>
                <q-btn
                  v-if="
                    $AC.haveScope(USER_SCOPES.SOCIAL_SETTINGS_PAYMENT_ADMIN)
                  "
                  text-color="negative"
                  icon="delete"
                  flat
                  @click="toggleDeleteConfim(props.row)"
                >
                  <q-tooltip :delay="500"> Удалить</q-tooltip>
                </q-btn>
              </div>
            </q-td>
          </template>
        </q-table>
      </div>

      <q-dialog class="full-width" @hide="clearModel" v-model="openModal">
        <q-card class="no-shadow full-width">
          <q-card-section>
            <div class="text-h6">Загрузить файл шаблона</div>
            <span v-if="documentForAttachment">
              {{ documentForAttachment.name }}
            </span>
          </q-card-section>
          <q-card-section>
            <q-file
              filled
              :accept="acceptRender"
              v-model="attachFile"
              :label="$t('file.actions.upload')"
              lazy-rules
              :rules="[validateFileName]"
              :error-message="
                attachFile
                  ? $t('processes.validationErrors.errorFileName')
                  : $t('processes.validationErrors.errorFileRequired')
              "
            />
          </q-card-section>
          <q-card-section
            v-if="
              documentForAttachment && documentForAttachment.type === 'DOCX'
            "
          >
            <div class="q-gutter-sm">
              <q-checkbox v-model="normalize" label="Нормализовать">
                <q-tooltip :delay="500">
                  Удалить форматирование word внутри тегов mustache
                </q-tooltip>
              </q-checkbox>
            </div>
          </q-card-section>
          <q-card-actions align="right">
            <q-btn
              @click="save"
              color="primary"
              :label="$t('base.actions.upload')"
            />
            <q-btn
              color="white"
              text-color="primary"
              outline
              @click="openModal = false"
              :label="$t('base.actions.cancel')"
            />
          </q-card-actions>
        </q-card>
      </q-dialog>

      <q-dialog class="full-width" v-model="deleteConfim">
        <q-card class="no-shadow full-width">
          <q-card-section>
            <div class="text-h6">Вы уверены, что хотите удалить шаблон?</div>
          </q-card-section>
          <q-card-actions align="right">
            <q-btn
              @click="deleteTemplate"
              color="primary"
              :label="$t('base.delete')"
            />
            <q-btn
              color="white"
              text-color="primary"
              outline
              @click="toggleDeleteConfim"
              :label="$t('base.undo')"
            />
          </q-card-actions>
        </q-card>
      </q-dialog>
    </q-card>

    <documents-dialog
      ref="documentsDialog"
      :cardModel="card"
      :common="common"
    />
  </div>
</template>

<script lang="js">
import DocumentsDialog from './DocumentsDialog.vue';
import { saveFileViaLink } from '@utils/files';
import { notifyError } from '@utils/notify';
import PrinterService from '@services/printer/index';
import cloneDeep from 'lodash/cloneDeep';
import axios from 'axios'
import {
  fetchAttachment,
  updateAttachment,
  updateDocument,
} from '@services/registry-service';
import { USER_SCOPES } from '@constants/entities/Scope';
import { SettingsForServiceTemplateApi } from '@openapi/registry-service';

const settingsForServiceTemplateApi = new SettingsForServiceTemplateApi();

export default {
  components: {
    DocumentsDialog,
  },
  props: ['common'],
  data() {
    return {
      USER_SCOPES: USER_SCOPES,
      fetchingInProgress: {},
      schemaName: 'ServiceDocument',
      deleteItem: null,
      deleteConfim: false,
      openModal: false,
      attachFile: null,
      documentForAttachment: null,
      attachedFileName: '',
      attachmentLoading: false,
      normalize: false,
    }
  },
  computed: {
    columns() {
      return [
        {
          align: 'left',
          field: 'code',
          label: this.$t('additionalSettings.code'),
          name: 'code',
          sortable: true,
          style: 'width: 20%; font-size: 14px',
          headerStyle: 'width: 20%; font-size: 12px; padding-left: 15px;',
          classes: 'text-primary-9',
        },
        {
          align: 'left',
          field: 'name',
          label: this.$t('additionalSettings.name'),
          name: 'name',
          sortable: true,
          style: 'width: 20%;word-break: break-all; font-size: 14px',
          headerStyle: 'width: 20%; font-size: 12px;',
          classes: 'text-primary-9',
        },
        {
          align: 'left',
          field: 'type',
          label: this.$t('additionalSettings.typeDoc'),
          name: 'type',
          sortable: true,
          style: 'width: 20%;word-break: break-all; font-size: 14px',
          headerStyle: 'width: 20%; font-size: 12px;',
          classes: 'text-primary-9',
        },
        {
          align: 'left',
          field: 'operation',
          label: this.$t('additionalSettings.operation'),
          name: 'operation',
          sortable: true,
          style: 'width: 20%;word-break: break-all; font-size: 14px',
          headerStyle: 'width: 20%; font-size: 12px;',
          classes: 'text-primary-9',
        },
        {
          align: 'right',
          field: 'file',
          label: this.$t('documents.documentAction'),
          name: 'file',
          sortable: false,
          headerStyle: 'font-size: 12px;',
          classes: 'text-primary-9',
        },
      ];
    },
    documents() {
      return (
        this.$store.getters['registryService/additionalSettings/settingsForServiceCard'].settingsforservicetemplate || []
      );
    },
    card() {
      return cloneDeep(
        this.$store.getters['registryService/additionalSettings/settingsForServiceCard']
      );
    },
    cardInitial() {
      return cloneDeep(
        this.$store.getters['registryService/additionalSettings/settingsForServiceCardInitial']
      );
    },
    acceptRender() {
      if (this.documentForAttachment && this.documentForAttachment.type) {
        const type = this.documentForAttachment.type
        if(type === 'EXCEL') {
          return '.xls, .xlsx'
        } else if (type === 'DOCX') {
          return '.doc, .docx'
        } else {
          return `.${type.toLowerCase()}`
        }
      }
      return ''
    },
  },
  methods: {
    addTemplate() {
      this.$refs.documentsDialog.open()
    },
    edit(row) {
      this.$refs.documentsDialog.open(row)
    },
    toggleDeleteConfim(item) {
      this.deleteConfim = !this.deleteConfim;
      this.deleteItem = item;
    },
    async deleteTemplate() {
      let documents = cloneDeep(this.documents);
      const findItem = (this.cardInitial?.settingsforservicetemplate || [])
        .find(e => e.id === this.deleteItem.id);

      if (findItem) {
        await axios.patch('/service/registry/service/settings-for-service', [{
          id: this.card.id, settingsforservicetemplate: [this.deleteItem.id]
        }])
      };
      await settingsForServiceTemplateApi.deleteSettingsForServiceTemplateById(this.deleteItem.id);
      documents = documents.filter(e => e.id !== this.deleteItem.id);
      this.card.settingsforservicetemplate = documents;
      this.$store.dispatch(
        'registryService/additionalSettings/setCardForJson',
        this.card
      );
      this.toggleDeleteConfim();
    },
    addDocumentAttachment(document) {
      this.clearModel();
      this.documentForAttachment = document;
      this.attachedFileName = document.code;
      this.openModal = true;
    },
    async save() {
      let file = new File([this.attachFile], this.attachedFileName);

      if (this.normalize && this.documentForAttachment.type === 'DOCX') {
        const blob = await PrinterService.normalizeFile({
          template: file,
          parameters: JSON.stringify({ todo: 'allowEmptyParams' }),
        }).catch(() => {
          throw new Error(
            this.$t('DocumentsCard.templateNormalizationFailed')
          );
        });
        file = new File([blob], this.attachedFileName);
      }

      const { data: result } = await updateAttachment(
        this.schemaName,
        this.documentForAttachment.templateId,
        undefined,
        [file]
      )
      if (result.success) {
        updateDocument(this.schemaName, [
          {
            templateUrl: this.attachedFileName,
            templateFormat: this.documentForAttachment.type,
            id: this.documentForAttachment.templateId,
            modified: result.modified,
          },
        ])
      }
      this.openModal = false;
    },
    clearModel() {
      this.attachedFileName = '';
      this.attachFile = null;
      this.normalize = false;
    },
    async downloadFile(document) {
      try {
        const xml = await fetchAttachment(
          this.schemaName,
          document.templateId,
          document.code,
        );

        if (xml) {
          const { data: blob } = await axios.get(xml, {
            responseType: 'blob',
          });
          saveFileViaLink({
            anchor: this.$refs.export,
            blob,
            fileName: document.code,
          });
        }

      } catch (e) {
        notifyError(e.message.toString());
      }
    },
    validateFileName(value) {
      if (typeof value === 'string') {
        return value.trim() !== ''
      } else if (value instanceof File) {
        return value.name.trim() !== ''
      }
      return true;
    },
  }
}
</script>
