<i18n>
{
  "en": {
    "DocumentEdit": {
      "title": "Edit document",
      "createTitle": "Create document",
      "name": "Name",
      "templateName": "File template",
      "code": "Code",
      "value": "Value",
      "source": "Document source",
      "resultType": "Result type",
      "documentsTitle": "Documents",
      "executionPeriodInDays": "Execution period in days",
      "notifyInHours": "Notify in hours",
      "jsonEditorMode": "Json editor mode",
      "formMode": "Form mode",
      "applicantDoc": "Applicant",
      "personal": "Personal welcome",
      "mvzDoc": "Documents added by a specialist",
      "resultDoc": "Result documents",
      "printApplicationTemplate": "Application print template",
      "AddDocumentEmptyError": "Fill in all the fields",
      "resultAccept": "Accept",
      "resultRejectDoc": "Documents rejected",
      "resultRejectService": "Service rejected",
      "goal": "Goal",
      "DocumentsSentApplicant": "Documents sent to the applicant",
      "interagency": "Interagency",
      "TemplateInteragency": "Template interagency",
      "receptionTemplate": "Face to face printable template"
    }
  },
  "ru": {
    "DocumentEdit": {
      "title": "Редактирование документа",
      "createTitle": "Создание документа",
      "source": "Источник документа",
      "resultType": "Тип результата",
      "name": "Имя",
      "templateName": "Шаблон имени документа",
      "code": "Код",
      "value": "Значение",
      "documentsTitle": "Записи",
      "executionPeriodInDays": "Период предоставления (рабочие дни)",
      "notifyInHours": "Время уведомления (часы)",
      "jsonEditorMode": "Режим редактора json",
      "formMode": "Режим формы",
      "applicantDoc": "Входящие документы",
      "personal": "Личный прием",
      "mvzDoc": "Документы добавляемые специалистом",
      "resultDoc": "Результирующие документы",
      "printApplicationTemplate": "Шаблон печати заявления",
      "AddDocumentEmptyError": "Заполните все поля",
      "resultAccept": "Положительное решение",
      "resultRejectDoc": "Отказ в приеме документов",
      "resultRejectService": "Отказ в предоставлении услуги",
      "goal": "Цель",
      "DocumentsSentApplicant": "Документы, отправляемые заявителю",
      "interagency": "Межведомственный запрос",
      "TemplateInteragency": "Шаблон МЗ",
      "receptionTemplate": "Шаблон печатной формы очного приёма"
    }
  }
}
</i18n>

<template>
  <q-dialog v-model="dialogOpen" @hide="clearModel">
    <q-card class="full-width no-shadow" style="max-width: 800px">
      <q-card-section>
        <div class="text-h6">
          {{
            isEditForm
              ? $t('DocumentEdit.title')
              : $t('DocumentEdit.createTitle')
          }}
        </div>
      </q-card-section>

      <q-card-section class="q-pb-md q-gutter-y-md">
        <q-btn-toggle
          v-if="isEditForm"
          v-model="jsoneditorMode"
          toggle-color="primary"
          :options="toggleBtnOptions"
        />
        <v-json-editor
          v-if="jsoneditorMode"
          ref="jsoneditor"
          v-model="dialogData"
          :options="{ mode: 'code' }"
          height="400px"
        />
        <div v-if="dialogData && !jsoneditorMode" class="q-gutter-y-md">
          <q-input
            v-model="dialogData.name"
            :label="$t('DocumentEdit.name')"
            :rules="nameRules"
            class="q-pb-none"
            filled
          />
          <FileTemplateInput
            v-if="dialogData"
            :rules="nameRules"
            :value.sync="dialogData.nameTemplate"
          />
          <q-input
            v-model="dialogData.code"
            :label="$t('DocumentEdit.code')"
            filled
          />

          <q-select
            v-model="dialogData.source"
            filled
            :options="statusList"
            :label="$t('DocumentEdit.source')"
            emit-value
            map-options
          />

          <q-select
            v-if="dialogData.source === 'result'"
            v-model="dialogData.resultType"
            filled
            :options="resultTypeList"
            :label="$t('DocumentEdit.resultType')"
            emit-value
            map-options
          />

          <q-input
            v-model.number="dialogData.goal"
            :label="$t('DocumentEdit.goal')"
            :rules="nameRules"
            filled
          />

          <q-file
            v-if="dialogData.source === 'result'"
            filled
            accept=".doc,.docx"
            :display-value="file ? file.name : dialogData.templateUrl || ''"
            label="Загрузить шаблон"
            @input="(newFile) => (file = newFile)"
          />

          <q-select
            v-model="dialogData.interagency"
            filled
            :options="interagencies"
            :label="$t('DocumentEdit.interagency')"
            option-value="id"
            option-label="description"
            emit-value
            map-options
          />

          <q-file
            v-if="dialogData.interagency"
            filled
            accept=".docx"
            :display-value="fileMZ ? fileMZ.name : dialogData.templateUrlMZ || ''"
            :label="$t('DocumentEdit.TemplateInteragency')"
            v-model="fileMZ"
          />
        </div>
      </q-card-section>
      <q-card-actions align="right">
        <q-btn
          v-if="isEditForm"
          label="Cохранить"
          unelevated
          color="primary"
          @click="edit"
        />
        <q-btn
          v-else
          label="Создать"
          unelevated
          color="primary"
          @click="create"
        />

        <q-btn
          label="Закрыть"
          color="white"
          text-color="primary"
          outline
          @click="dialogOpen = false"
        />
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>
<script lang="ts">
// @ts-nocheck
// @ts-ignore
import VJsonEditor from 'v-jsoneditor';
import { resDocNameLengthStringRule } from '@utils/field-validation/documents';
import FileTemplateInput from './DocumentDialogg/FileTemplateInput.vue';
import {
  createDocument,
  updateAttachment,
  updateDocument,
} from '@services/registry-service';
import get from 'lodash/get';
import cloneDeep from 'lodash/cloneDeep';
import { notifyError } from '@utils/notify';
import { PRINT_APPLICATION, RECEPTION_PRINT_APPLICATION } from '@utils/statement-print';

export default {
  name: 'DocumentDialog',
  components: {
    VJsonEditor,
    FileTemplateInput,
  },
  props: ['common', 'model'],
  data() {
    return {
      dialogData: {},
      file: null,
      fileMZ: null,

      editOnly: false,

      schemaName: 'ServiceDocument',

      loading: false,

      mode: 'edit',

      dialogOpen: false,

      jsoneditorMode: false,

      statusList: [
        {
          label: this.$t('DocumentEdit.DocumentsSentApplicant'),
          value: 'Specialist',
        },
        {
          label: this.$t('DocumentEdit.mvzDoc'),
          value: 'MVZ',
        },
        {
          label: this.$t('DocumentEdit.applicantDoc'),
          value: 'Applicant',
        },
        {
          label: this.$t('DocumentEdit.resultDoc'),
          value: 'result',
        },
        {
          label: this.$t('DocumentEdit.printApplicationTemplate'),
          value: PRINT_APPLICATION,
        },
        {
          label: this.$t('DocumentEdit.receptionTemplate'),
          value: RECEPTION_PRINT_APPLICATION,
        },
      ],

      resultTypeList: [
        {
          label: this.$t('DocumentEdit.resultAccept'),
          value: 'accept',
        },
        {
          label: this.$t('DocumentEdit.resultRejectDoc'),
          value: 'rejectDoc',
        },
        {
          label: this.$t('DocumentEdit.resultRejectService'),
          value: 'rejectService',
        },
      ],

      toggleBtnOptions: [
        {
          label: this.$t('DocumentEdit.jsonEditorMode'),
          value: true,
        },
        {
          label: this.$t('DocumentEdit.formMode'),
          value: false,
        },
      ],
    };
  },
  computed: {
    nameRules() {
      return [
        ...(this.dialogData.source === 'result'
          ? [resDocNameLengthStringRule]
          : []),
      ];
    },
    isEditForm() {
      return this.mode === 'edit';
    },
    card() {
      return cloneDeep(
        this.$store.getters['registryService/services/servicesCard']
      );
    },
    interagencies() {
      return get(this.card, 'interagencies', []);
    },
  },
  watch: {
    'common.models.DocumentDialog': {
      immediate: true,
      handler: function (val) {
        if (val) {
          this.dialogOpen = true;
          if (val.data === 'createMode') {
            this.mode = 'create';
            this.dialogData = {};
            return;
          }
          this.dialogData = val.data;
          this.editOnly = val.editOnly;
          this.mode = 'edit';
        }
      },
    },
  },

  destroyed() {
    this.clearModel();
  },

  methods: {
    async edit() {
      if (
        !get(this.dialogData, 'name') ||
        !get(this.dialogData, 'code') ||
        !get(this.dialogData, 'source')
      ) {
        notifyError(this.$t('DocumentEdit.AddDocumentEmptyError'));
        return;
      }
      try {
        this.loading = true;

        if (this.file) {
          const file = new File([this.file], this.dialogData.templateUrl);
          const { data: attachmentResult } = await updateAttachment(
            get(this.dialogData, 'schema'),
            get(this.dialogData, 'id'),
            undefined,
            [file]
          );

          this.dialogData.modified = attachmentResult.modified;
        }

        if (this.fileMZ) {
          const file = new File([this.file], this.dialogData.templateUrlMZ);
          const { data: attachmentResult } = await updateAttachment(
            get(this.dialogData, 'schema'),
            get(this.dialogData, 'id'),
            undefined,
            [file]
          );

          this.dialogData.modified = attachmentResult.modified;
        }

        const document = cloneDeep(this.dialogData);
        if (get(document, 'form')) {
          document.form = document.form.map((i) => i.id);
        }
        if (get(document, 'attachments')) {
          document.attachments = document.attachments.map((i) => i.id);
        }
        const { data: result } = await updateDocument(
          get(this.dialogData, 'schema'),
          [document]
        );

        this.dialogData.modified = result.modified;

        if (!this.editOnly) {
          const card = cloneDeep(
            this.$store.getters['registryService/services/servicesCard']
          );
          card.documents = (card.documents || []).map((i) =>
            i.id === this.dialogData.id
              ? Object.assign({}, i, this.dialogData)
              : i
          );
          this.$store.dispatch('registryService/services/setCardForJson', card);
        }
      } catch (e) {
        notifyError(e.message.toString());
      } finally {
        this.dialogOpen = false;
      }
    },

    async create() {
      if (
        !get(this.dialogData, 'name') ||
        !get(this.dialogData, 'code') ||
        !get(this.dialogData, 'source')
      ) {
        notifyError(this.$t('DocumentEdit.AddDocumentEmptyError'));
        return;
      }
      try {
        this.loading = true;

        if (this.file) {
          const fileName = `template_${this.dialogData.code}.docx`;
          this.dialogData.templateUrl = fileName;
        }

        if (this.fileMZ) {
          const fileNameMZ= `template_mz_${this.dialogData.code}.docx`
          this.dialogData.templateUrlMZ = fileNameMZ;
        }
        
        const { data: docResult } = await createDocument(this.schemaName, [
          this.dialogData,
        ]);

        this.dialogData.id = get(docResult, 'objectIds[0]');
        this.dialogData.schema = this.schemaName;

        if (this.file) {
          const file = new File([this.file], this.dialogData.templateUrl);
          const { data: attachResult } = await updateAttachment(
            this.schemaName,
            get(this.dialogData, 'id'),
            undefined,
            [file]
          );
          this.dialogData.modified = attachResult.modified;
        }

        if (this.fileMZ) {
          const file = new File([this.fileMZ], this.dialogData.templateUrlMZ);
          const { data: attachResult } = await updateAttachment(
            this.schemaName,
            get(this.dialogData, 'id'),
            undefined,
            [file]
          );
          this.dialogData.modified = attachResult.modified;
        }

        const card = cloneDeep(
          this.$store.getters['registryService/services/servicesCard']
        );

        const documents = card.documents || [];
        documents.push(this.dialogData);
        card.documents = documents;
        this.$store.dispatch('registryService/services/setCardForJson', card);
      } catch (e) {
        notifyError(e.message.toString());
      } finally {
        this.dialogOpen = false;
      }
    },

    clearModel() {
      this.$emit('commonModels', {
        DocumentDialog: null,
      });
      this.jsoneditorMode = false;
    },
  },
};
</script>
