<template>
  <q-dialog v-model="settingsDialog">
    <q-card class="full-width no-shadow" style="max-width: 800px">
      <q-card-section>
        <div class="text-h6">
          {{ isEditForm ? 'Редактирование шаблона' : 'Создание шаблона' }}
        </div>
      </q-card-section>
      <div v-if="dialogData">
        <q-card-section class="q-pb-md q-gutter-y-md">
          <q-input
            v-if="!isEditForm"
            v-model="dialogData.code"
            disable
            filled
            label="Код документа"
          />
          <q-input v-model="dialogData.name" filled label="Наименование" />
          <q-btn-toggle
            v-model="dialogData.operation"
            toggle-color="primary"
            :options="operations"
          />
          <q-file
            v-if="!isEditForm"
            clearable
            filled
            counter
            :accept="accept"
            label="Загрузить"
            ref="processDialogFile"
            :rules="[validateFileName]"
            :error-message="
              upload.file
                ? $t('processes.validationErrors.errorFileName')
                : $t('processes.validationErrors.errorFileRequired')
            "
            v-model="upload.file"
            @input="fileHandler"
          />
        </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
            @click="settingsDialog = false"
            label="Закрыть"
            color="white"
            text-color="primary"
            outline
          />
        </q-card-actions>
      </div>
    </q-card>
  </q-dialog>
</template>

<script>
import cloneDeep from 'lodash/cloneDeep';
import axios from 'axios';
import {
  SettingsForServiceTemplateApi,
  DocumentApi,
} from '@openapi/registry-service';

const settingsForServiceTemplateApi = new SettingsForServiceTemplateApi();
const documentApi = new DocumentApi();

export default {
  name: 'DocumentsDialog',
  data() {
    return {
      isEditForm: false,
      settingsDialog: false,
      dialogData: {
        code: '',
        name: '',
        type: '',
        operation: 'IMPORT',
      },
      upload: {
        file: null,
        loading: false,
      },
      operations: [
        { value: 'IMPORT', label: 'IMPORT' },
        { value: 'EXPORT', label: 'EXPORT' },
      ],
      types: [],
      accept: '.csv, .xml, .pdf, .doc, .docx, .xls, .xlsx',
    };
  },
  mounted() {
    documentApi
      .pagingDocuments(
        'dictionary',
        undefined,
        undefined,
        'code==DictTemplateTypeForSettingForService'
      )
      .then((response) => {
        if (response.data.records) {
          this.types = response.data.records[0].documents;
        }
      });
  },
  methods: {
    async open(row) {
      this.clearForm();
      if (row) {
        this.isEditForm = true;
        this.dialogData = cloneDeep(row);
      } else {
        this.isEditForm = false;
      }
      this.settingsDialog = true;
    },
    async create() {
      const validation = await this.validate();

      if (!validation.isValid) {
        this.$q.notify({
          color: 'negative',
          icon: 'error',
          message: validation.message,
        });
        return;
      }
      try {
        const formdata = new FormData();

        formdata.append('files', this.upload.file);
        formdata.append('parameters', JSON.stringify(this.dialogData));

        // await settingsForServiceTemplateApi.createTemplateWithAttachment([this.upload.file], this.dialogData)
        // TODO: Не хватает параметра parameters в openapi
        await axios
          .post(
            '/service/registry/service/settings-for-service-template/template-with-attachment',
            formdata
          )
          .then((response) => {
            const card = cloneDeep(
              this.$store.getters[
                'registryService/additionalSettings/settingsForServiceCard'
              ]
            );
            const templates = card.settingsforservicetemplate || [];

            templates.push(response.data.document);
            card.settingsforservicetemplate = templates;
            this.$store.dispatch(
              'registryService/additionalSettings/setCardForJson',
              card
            );
            this.$store.dispatch(
              'registryService/additionalSettings/setunsavedChanges',
              'documents_template'
            );
          });
      } catch (e) {
        this.$q.notify({
          color: 'negative',
          icon: 'error',
          message: e.message,
        });
      } finally {
        this.settingsDialog = false;
      }
    },
    async edit() {
      if (!this.validateFileName(this.dialogData.name)) {
        this.$q.notify({
          color: 'negative',
          icon: 'error',
          message: this.$t('processes.validationErrors.fileError'),
        });
        return;
      }

      await settingsForServiceTemplateApi
        .updateSettingsForServiceTemplate([this.dialogData])
        .then(() => {
          const card = cloneDeep(
            this.$store.getters[
              'registryService/additionalSettings/settingsForServiceCard'
            ]
          );
          const templates = card.settingsforservicetemplate || [];
          templates.find(
            (e) => e.id === this.dialogData.id
          ).name = this.dialogData.name;
          templates.find(
            (e) => e.id === this.dialogData.id
          ).operation = this.dialogData.operation;
          card.settingsforservicetemplate = templates;

          this.$store.dispatch(
            'registryService/additionalSettings/setCardForJson',
            card
          );
          this.settingsDialog = false;

          this.$q.notify({
            color: 'positive',
            icon: 'check_circle_outline',
            message: 'Успешно',
          });
        });
    },
    async validate() {
      if (!this.validateFileName(this.dialogData.name)) {
        return {
          isValid: false,
          message: this.$t('processes.validationErrors.fileError'),
        };
      }
      if (!this.upload?.file) {
        return {
          isValid: false,
          message: this.$t('processes.validationErrors.errorFileRequired'),
        };
      }
      if (!this.validateFileName(this.upload.file)) {
        return {
          isValid: false,
          message: this.$t('processes.validationErrors.fileError'),
        };
      }
      return {
        isValid: true,
        message: '',
      };
    },
    fileHandler(file) {
      this.dialogData.code = '';
      this.dialogData.type = '';
      if (file && file.name) {
        const index = file.name.lastIndexOf('.');
        const type = file.name.substr(index + 1, file.name.length);

        this.dialogData.type =
          type.indexOf('doc') >= 0
            ? 'DOCX'
            : type.indexOf('xls') >= 0
            ? 'EXCEL'
            : type.toUpperCase();
        this.dialogData.code = file.name;
      }
    },
    validateFileName(value) {
      if (typeof value === 'string') {
        return value.trim() !== '';
      } else if (value instanceof File) {
        return value.name.trim() !== '';
      }
      return true;
    },
    clearForm() {
      this.upload = {
        file: null,
        loading: false,
      };
      this.dialogData = {
        code: '',
        name: '',
        type: '',
        operation: 'IMPORT',
      };
    },
  },
};
</script>
