<template>
  <q-dialog v-model="openDialog">
    <q-card class="full-width no-shadow" style="max-width: 100%">
      <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-model="dialogData.title"
            :rules="[validateFileName]"
            :disable="loading"
            error-message="Поле должно быть заполнено"
            filled
            label="Наименование"
          />
          <q-input
            v-model="dialogData.description"
            :disable="loading"
            filled
            label="Описание"
          />
          <q-editor v-model="dialogData.content" :definitions="definitions" />
        </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="Сохранить"
            :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 { ArticleApi } from '@openapi/reference-information';
import { notifyError, notifySuccess } from '@utils/notify';
import cloneDeep from 'lodash/cloneDeep';

const articleApi = new ArticleApi();

export default {
  name: 'ArticleDialog',
  data() {
    return {
      isEditForm: false,
      openDialog: false,
      dialogData: {
        content: '',
      },
      definitions: {},
      loading: false,
    };
  },
  computed: {
    articleRecords() {
      return cloneDeep(
        this.$store.getters['referenceInformation/article/setArticleRecords']
      );
    },
    activeArticle() {
      return cloneDeep(
        this.$store.getters['referenceInformation/article/setActiveArticle']
      );
    },
  },
  methods: {
    open(row) {
      this.clearForm();
      if (row && row.title) {
        this.isEditForm = true;
        this.dialogData = cloneDeep({ ...this.dialogData, ...row });
      } else {
        this.isEditForm = false;
        this.dialogData = cloneDeep({ ...row, ...this.dialogData });
      }

      this.openDialog = true;
    },
    create() {
      if (!this.validateFileName(this.dialogData.title)) {
        this.$q.notify({
          color: 'negative',
          icon: 'error',
          message: 'Поле наименование должно быть заполнено',
        });
        return;
      }

      this.loading = true;
      const params = {
        ...this.dialogData,
        sortOrder: this.dialogData.sortOrder || 0,
      };
      if (this.dialogData.parentId) {
        params.parentId = this.dialogData.parentId;
      }
      articleApi
        .createArticle([params])
        .then((res) => {
          const articles = this.articleRecords || [];

          if (params.parentId) {
            const findParent = (art) => {
              art.forEach((art) => {
                if (art.id === params.parentId) {
                  if (art.children && art.children.length) {
                    art.children.push({ ...params, id: res.data.objectIds[0] });
                    return {};
                  } else {
                    art.children = [{ ...params, id: res.data.objectIds[0] }];
                  }
                } else if (art.id !== params.parentId && art.children) {
                  findParent(art.children);
                } else {
                  return {};
                }
              });
            };
            findParent(articles);
          } else {
            articles.push({ ...params, id: res.data.objectIds[0] });
          }

          this.$store.dispatch(
            'referenceInformation/article/setArticleRecordsJson',
            articles
          );
          notifySuccess('Статья успешно создана');
        })
        .catch((err) => {
          notifyError(err.message.toString());
        })
        .finally(() => {
          this.loading = false;
          this.openDialog = false;
        });
    },
    edit() {
      if (!this.validateFileName(this.dialogData.title)) {
        this.$q.notify({
          color: 'negative',
          icon: 'error',
          message: 'Поле наименование должно быть заполнено',
        });
        return;
      }
      this.loading = true;
      const params = {
        title: this.dialogData.title,
        description: this.dialogData.description,
        content: this.dialogData.content,
        sortOrder: this.dialogData.sortOrder,
        id: this.dialogData.id,
      };
      if (this.dialogData.parentId) params.parentId = this.dialogData.parentId;

      articleApi
        .updateArticle(params)
        .then(() => {
          const newArticle = {
            ...params,
            files: this.activeArticle.files || [],
          };
          const articles = this.articleRecords || [];
          const findParent = (art) => {
            art.forEach((art) => {
              if (art.id === newArticle.id) {
                art.title = newArticle.title;
                return {};
              } else if (art.id !== newArticle.id && art.children) {
                findParent(art.children);
              } else {
                return {};
              }
            });
          };
          findParent(articles);

          this.$store.dispatch(
            'referenceInformation/article/setArticleRecordsJson',
            articles
          );
          this.$store.dispatch(
            'referenceInformation/article/setActiveArticleJson',
            newArticle
          );
          notifySuccess('Статья успешно отредактрованна');
        })
        .catch((err) => {
          notifyError(err.message.toString());
        })
        .finally(() => {
          this.loading = false;
          this.openDialog = false;
        });
    },
    validateFileName(value) {
      if (value) {
        return value.trim() !== '';
      }
      return false;
    },
    clearForm() {
      this.dialogData = {
        content: '',
      };
    },
  },
};
</script>
