<template>
  <q-dialog v-model="openDialog">
    <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-file
            v-if="!isEditForm"
            v-model="upload.file"
            :disable="loading"
            class="q-mb-xs q-pr-xs"
            label="Выберите файл"
            max-file-size="209715200"
            counter
            clearable
            filled
            @input="fileHandler"
          />
          <q-input
            v-model="dialogData.description"
            :disable="loading"
            :rules="[validateFileName]"
            error-message="Поле должно быть заполнено"
            filled
            label="Описание"
          />
          <q-input
            v-model="dialogData.filename"
            disable
            :rules="[validateFileName]"
            filled
            label="Наименование"
          />
        </q-card-section>
        <q-card-actions align="right">
          <q-btn
            @click="openDialog = false"
            label="Закрыть"
            :loading="loading"
            color="white"
            text-color="primary"
            outline
          />
          <q-btn
            v-if="isEditForm"
            label="Cохранить"
            :loading="loading"
            unelevated
            color="primary"
            @click="edit"
          />
          <q-btn
            v-else
            label="Создать"
            :loading="loading"
            unelevated
            color="primary"
            @click="create"
          />
        </q-card-actions>
      </div>
    </q-card>
  </q-dialog>
</template>

<script>
import { AttachmentApi } from '@openapi/reference-information';
import { notifyError, notifySuccess } from '@utils/notify';
import cloneDeep from 'lodash/cloneDeep';
import axios from 'axios';

const attachmentApi = new AttachmentApi();

export default {
  name: 'AddFileDialog',
  data() {
    return {
      isEditForm: false,
      openDialog: false,
      dialogData: {
        filename: '',
        description: '',
      },
      upload: {
        file: null,
        loading: false,
      },
      idFile: '',
      loading: false,
    };
  },
  computed: {
    activeArticle() {
      return cloneDeep(
        this.$store.getters['referenceInformation/article/setActiveArticle']
      );
    },
  },
  methods: {
    open(row) {
      this.clearForm();
      if (row && row.filename) {
        this.isEditForm = true;
        this.dialogData = cloneDeep(row);
      } else if (row !== '') {
        this.idFile = row;
        this.isEditForm = false;
      }
      this.openDialog = true;
    },
    async create() {
      if (
        !this.validateFileName(this.dialogData.filename) ||
        !this.validateFileName(this.dialogData.description) ||
        !this.validateFileName(this.upload.file.name)
      ) {
        this.$q.notify({
          color: 'negative',
          icon: 'error',
          message: this.$t('processes.validationErrors.fileError'),
        });
        return;
      }
      this.loading = true;
      await attachmentApi
        .create(
          this.idFile,
          this.dialogData.filename,
          this.dialogData.description,
          this.upload.file
        )
        .then((res) => {
          const files = this.activeArticle.files || [];
          files.push({ ...this.dialogData, id: res.data.objectIds[0] });
          const newArticle = { ...this.activeArticle, files: files };
          this.$store.dispatch(
            'referenceInformation/article/setActiveArticleJson',
            newArticle
          );
          notifySuccess('Файл успешно добавлен');
        })
        .catch((e) => {
          notifyError(e.message.toString());
        })
        .finally(() => {
          this.loading = false;
          this.openDialog = false;
        });
    },
    edit() {
      // console.log(this.dialogData);
    },
    fileHandler(file) {
      this.dialogData.filename = '';
      if (file?.name) {
        this.dialogData.filename = file.name;
      }
    },
    validateFileName(value) {
      if (value) {
        return value.trim() !== '';
      }
      return false;
    },
    clearForm() {
      this.dialogData = {
        filename: '',
        description: '',
      };
      this.upload = {
        file: null,
        loading: false,
      };
    },
  },
};
</script>
