<template>
  <div class="q-pa-md q-gutter-y-md">
    <q-card class="no-shadow q-gutter-y-md">
      <a ref="export" v-show="false" />
      <div class="bg-grey-1 items-center justify-between row q-pa-md">
        <div class="text-h6 text-grey-9 col q-pr-md">
          {{ $t('backgroundInfo.backgroundInfoTitle') }}
        </div>
        <q-btn
          v-if="$AC.haveScope(USER_SCOPES.CLOUD_ADMIN)"
          color="primary"
          text-color="white"
          label="Создать корневую страницу"
          type="button"
          icon="add_circle"
          @click="create"
        />
      </div>
    </q-card>

    <div class="row">
      <div class="col-5 q-mt-md">
        <div class="q-gutter-y-md bg-white q-px-lg q-pb-md q-pt-sm q-mr-md">
          <q-tree
            v-if="articleRecords && articleRecords.length"
            class="q-tree-info"
            :nodes="articleRecords"
            node-key="id"
          >
            <template v-slot:default-header="prop">
              <div class="q-table flex justify-between items-center no-wrap">
                <div
                  @click="expanded(prop.node)"
                  :class="{
                    'text-primary cursor-pointer':
                      prop.node.id !== activeArticle.id,
                  }"
                >
                  {{ prop.node.title }}
                </div>
                <div
                  v-if="$AC.haveScope(USER_SCOPES.CLOUD_ADMIN)"
                  class="row no-wrap"
                >
                  <q-btn
                    icon="add_circle_outline"
                    text-color="primary"
                    dense
                    @click="create(prop.node)"
                  >
                    <q-tooltip :delay="500">Создать подстраницу</q-tooltip>
                  </q-btn>
                  <q-btn
                    :disabled="
                      prop.node &&
                      prop.node.children &&
                      prop.node.children.length > 0
                    "
                    text-color="negative"
                    icon="delete"
                    dense
                    @click.stop="toggleDeleteConfimArt(prop.node)"
                  >
                    <q-tooltip :delay="500">Удалить</q-tooltip>
                  </q-btn>
                </div>
              </div>
            </template>
          </q-tree>
        </div>
      </div>
      <div class="article-info-wrap col-7 q-mt-md">
        <div class="q-gutter-y-md bg-white q-px-lg q-pb-md q-pt-sm">
          <div v-if="!loading && activeArticle.id">
            <div class="items-center justify-between q-mb-md row">
              <div class="flex text-h6 no-wrap">
                <span>{{ activeArticle.title }}</span>
                <q-btn
                  v-if="$AC.haveScope(USER_SCOPES.CLOUD_ADMIN)"
                  class="q-ml-sm"
                  text-color="primary"
                  icon="create"
                  dense
                  @click="edit(activeArticle)"
                />
              </div>
            </div>
            <div class="col text-primary q-pt-md q-mb-lg">
              <div class="q-gutter-y-md">
                <div class="text-dark">{{ activeArticle.description }}</div>
                <div v-html="activeArticle.content" />
              </div>
            </div>
            <div class="items-center justify-between q-mb-md row">
              <div class="text-h6">
                <span v-if="activeArticle.files">Вложенные файлы</span>
              </div>
              <q-btn
                v-if="$AC.haveScope(USER_SCOPES.CLOUD_ADMIN)"
                color="primary"
                text-color="white"
                label="Добавить файл"
                type="button"
                icon="attach_file"
                @click="attachFile(activeArticle)"
              />
            </div>
            <div v-if="activeArticle.files" class="col text-primary q-mb-md">
              <div
                v-for="file in activeArticle.files"
                :key="file.id"
                class="items-center justify-between q-mb-sm row hoverable-attach"
              >
                <div @click="downloadFile(file)" class="cursor-pointer">
                  <div class="">{{ file.filename }}</div>
                  <span class="">{{ file.description }}</span>
                </div>
                <div class="">
                  <q-btn
                    icon="arrow_downward"
                    text-color="primary"
                    @click="downloadFile(file)"
                  >
                    <q-tooltip :delay="500">Скачать</q-tooltip>
                  </q-btn>
                  <q-btn
                    v-if="$AC.haveScope(USER_SCOPES.CLOUD_ADMIN)"
                    text-color="negative"
                    icon="delete"
                    @click="toggleDeleteConfim(file)"
                  >
                    <q-tooltip :delay="500">Удалить</q-tooltip>
                  </q-btn>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <q-dialog class="full-width" v-model="deleteConfimArt">
      <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
            :loading="loadBtn"
            @click="deleted"
            color="primary"
            :label="$t('base.delete')"
          />
          <q-btn
            color="white"
            text-color="primary"
            :loading="loadBtn"
            outline
            @click="toggleDeleteConfimArt"
            :label="$t('base.undo')"
          />
        </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="deleteFile"
            :loading="loadBtn"
            color="primary"
            :label="$t('base.delete')"
          />
          <q-btn
            color="white"
            text-color="primary"
            :loading="loadBtn"
            outline
            @click="toggleDeleteConfim"
            :label="$t('base.undo')"
          />
        </q-card-actions>
      </q-card>
    </q-dialog>

    <q-inner-loading :showing="loading">
      <q-spinner-gears color="primary" size="50px" />
    </q-inner-loading>

    <article-dialog ref="articleDialog" />
    <add-file-dialog ref="addFileDialog" />
  </div>
</template>

<script>
import { ArticleApi, AttachmentApi } from '@openapi/reference-information';
import { notifyError, notifySuccess } from '@utils/notify';
import { USER_SCOPES } from '@constants/entities/Scope';
import ArticleDialog from './ArticleDialog.vue';
import AddFileDialog from './AddFileDialog.vue';
import cloneDeep from 'lodash/cloneDeep';

const articleApi = new ArticleApi();
const attachmentApi = new AttachmentApi();

export default {
  name: 'backgroundInfo',
  components: {
    ArticleDialog,
    AddFileDialog,
  },
  data() {
    return {
      USER_SCOPES: USER_SCOPES,
      selected: {},
      deleteConfim: false,
      deleteConfimArt: false,
      deleteItem: null,
      deleteArt: null,
      loadBtn: false,
    };
  },

  computed: {
    articleRecords() {
      return cloneDeep(
        this.$store.getters['referenceInformation/article/setArticleRecords']
      );
    },
    activeArticle() {
      return cloneDeep(
        this.$store.getters['referenceInformation/article/setActiveArticle']
      );
    },
    loading() {
      return (
        this.$store.getters['referenceInformation/article/servicesLoading'] ||
        false
      );
    },
  },
  created() {
    this.$store.dispatch('referenceInformation/article/getArticleRecords');
  },
  methods: {
    expanded(article) {
      this.$store.dispatch(
        'referenceInformation/article/getArticle',
        article.id
      );
    },
    create(article) {
      if (article && article.id) {
        this.$refs.articleDialog.open({
          parentId: article.id,
          sortOrder: article.sortOrder + 1,
        });
      } else {
        this.$refs.articleDialog.open();
      }
    },
    edit() {
      this.$refs.articleDialog.open(this.activeArticle);
    },
    deleted() {
      this.loadBtn = true;
      articleApi
        .deleteArticle([this.deleteArt.id])
        .then(() => {
          let articles = this.articleRecords;

          if (this.deleteArt.parentId) {
            const findParent = (art) => {
              art.forEach((art) => {
                if (art.id === this.deleteArt.parentId) {
                  art.children = art.children.filter(
                    (e) => e.id !== this.deleteArt.id
                  );
                  return {};
                } else if (art.id !== this.deleteArt.parentId && art.children) {
                  findParent(art.children);
                } else {
                  return {};
                }
              });
            };
            findParent(articles);
          } else {
            articles = articles.filter((e) => e.id !== this.deleteArt.id);
          }

          this.$store.dispatch(
            'referenceInformation/article/setArticleRecordsJson',
            articles
          );
          if (this.deleteArt.id === this.activeArticle.id) {
            this.$store.dispatch(
              'referenceInformation/article/setActiveArticleJson',
              {}
            );
          }
          notifySuccess('Статья успешно удалена');
        })
        .catch((e) => {
          notifyError(e.message.toString());
        })
        .finally(() => {
          this.toggleDeleteConfimArt();
          this.loadBtn = false;
        });
    },
    deleteFile() {
      this.loadBtn = true;
      attachmentApi
        .deleteAttachment(this.deleteItem.id)
        .then(() => {
          let files = this.activeArticle.files || [];
          files = files.filter((e) => e.id !== this.deleteItem.id);
          const newArticle = { ...this.activeArticle, files: files };
          this.$store.dispatch(
            'referenceInformation/article/setActiveArticleJson',
            newArticle
          );
          notifySuccess('Файл успешно удален');
        })
        .catch((e) => {
          notifyError(e.message.toString());
        })
        .finally(() => {
          this.toggleDeleteConfim();
          this.loadBtn = false;
        });
    },
    toggleDeleteConfim(item) {
      this.deleteConfim = !this.deleteConfim;
      this.deleteItem = item;
    },
    toggleDeleteConfimArt(item) {
      this.deleteConfimArt = !this.deleteConfimArt;
      this.deleteArt = item;
    },
    attachFile() {
      this.$refs.addFileDialog.open(this.activeArticle.id);
    },
    async downloadFile(file) {
      this.$store.dispatch('referenceInformation/article/setLoadArticle', true);
      await attachmentApi
        .getAttachmentContent(file.id, { responseType: 'blob' })
        .then((res) => {
          // fixme: пример исходника взят в src\components\cards\services\Index.vue
          const blob = new Blob([res.data]);
          const link = document.createElement('a');
          link.href = URL.createObjectURL(blob);
          link.download = file.filename;
          link.click();
          URL.revokeObjectURL(link.href);
        })
        .catch((e) => {
          notifyError(e.message.toString());
        })
        .finally(() => {
          this.$store.dispatch(
            'referenceInformation/article/setLoadArticle',
            false
          );
        });
    },
    editFile(file) {
      this.$refs.addFileDialog.open(file);
    },
  },
};
</script>

<style lang="scss">
.q-tree-info .q-tree__node-header:hover,
.hoverable-attach:hover {
  background: #f5f5f5;
}
.q-tree, .article-info-wrap {
  word-break: break-word;
}
</style>
