<template>
  <div class="ele-body">
    <ele-split-layout
      width="266px"
      allow-collapse
      :right-style="{ overflow: 'hidden' }"
      :style="{ height: 'calc(100vh - 152px)' }"
    >
      <a-card :body-style="{ padding: '0' }">
        <ele-toolbar theme="default">
          <a-space :size="10">
            <b>目录</b>
            <a-button
              type="primary"
              :size="`small`"
              class="ele-btn-icon"
              @click="openAdd()"
            >
              <template #icon>
                <plus-outlined />
              </template>
            </a-button>
            <a-button
              type="primary"
              :size="`small`"
              :disabled="!current"
              class="ele-btn-icon"
              @click="openEdit()"
            >
              <template #icon>
                <edit-outlined />
              </template>
            </a-button>
            <a-button
              danger
              type="primary"
              :size="`small`"
              :disabled="!current"
              class="ele-btn-icon"
              @click="remove"
            >
              <template #icon>
                <delete-outlined />
              </template>
            </a-button>
          </a-space>
        </ele-toolbar>
        <div class="ele-border-split sys-docs-list">
          <a-tree
            :tree-data="data"
            v-model:expanded-keys="expandedRowKeys"
            v-model:selected-keys="selectedRowKeys"
            @select="onTreeSelect"
          />
        </div>
      </a-card>
      <template #content>
        <tinymce v-if="form.docsId" @done="reload" @echo="onEcho" />
      </template>
    </ele-split-layout>
    <!-- 编辑弹窗 -->
    <DocsEdit
      :docs="data"
      :data="form"
      v-model:visible="showEdit"
      @done="reload"
    />
  </div>
</template>

<script lang="ts" setup>
  import { createVNode, ref, unref, watch } from 'vue';
  import { message, Modal } from 'ant-design-vue';
  import {
    PlusOutlined,
    EditOutlined,
    DeleteOutlined,
    ExclamationCircleOutlined
  } from '@ant-design/icons-vue';
  import {assignObject, eachTreeData, toTreeData} from 'ele-admin-pro';
  import DocsEdit from './components/docs-edit.vue';
  import { listDocs, removeDocs } from '@/api/cms/docs';
  import type { Docs, DocsParam } from '@/api/cms/docs/model';
  import useSearch from '@/utils/use-search';
  import { useRouter } from 'vue-router';
  import { openUrl } from '@/utils/common';
  import Tinymce from '@/views/cms/docs/tinymce.vue';
  import useFormData from "@/utils/use-form-data";

  const { currentRoute } = useRouter();
  // 加载状态
  const loading = ref(true);
  // 书籍编号
  const bookCode = ref<string>();
  // 书籍ID
  const bookId = ref<number>();
  // 文档ID
  const docsId = ref<number>(0);
  // 树形数据
  const data = ref<any[]>([]);
  // 树展开的key
  const expandedRowKeys = ref<number[]>([]);
  // 树选中的key
  const selectedRowKeys = ref<number[]>([]);
  // 选中数据
  const current = ref<Docs | null>(null);
  // 是否显示表单弹窗
  const showEdit = ref(false);

  // 表单数据
  const { form, resetFields, assignFields } = useFormData<Docs>({
    docsId: undefined,
    title: '',
    parentId: 0,
    userId: '',
    content: '',
    shopId: '',
    sortNumber: 100,
    comments: '',
    bookId: undefined,
    code: '',
    isUpdate: false
  });

  // 表单数据
  const { where } = useSearch<DocsParam>({
    bookId: undefined,
    docsId: undefined,
    title: '',
    code: ''
  });

  const openAdd = () => {
    form.isUpdate = false
    showEdit.value = true;
  };

  /* 打开编辑弹窗 */
  const openEdit = () => {
    form.isUpdate = true
    showEdit.value = true;
  };

  /* 选择数据 */
  const onTreeSelect = (e) => {
    eachTreeData(
      data.value,
      (item, index, parent) => {
        // index 是当前循环索引, parent 是父级数据
        if (item.docsId == e[0]) {
          if(!item.children){
            openUrl(`/cms/docs/${bookCode.value}?id=${e[0]}`);
          }else {
            expandedRowKeys.value.push(item.docsId);
            assignObject(form,item);
          }
        }
      },
      'children'
    );
  };

  const onEcho = (item: Docs) => {
    current.value = item;
  };

  /* 查询 */
  const reload = () => {
    loading.value = true;
    if (bookCode.value) {
      where.code = bookCode.value;
      listDocs(where)
        .then((list) => {
          loading.value = false;
          const eks: number[] = [];
          if (list.length == 0) {
            return;
          }
          list.forEach((d, i) => {
            // 设置模块的bookId
            if(i == 0 && !form.docsId){
              form.bookId = d.bookId;
            }
            d.key = d.docsId;
            d.value = d.docsId;
          });
          data.value = toTreeData({
            data: list,
            idField: 'docsId',
            parentIdField: 'parentId',
            addParentIds: true
          });
          queryDocs();

          // 加载默认文档
          // if (docsId.value == 0) {
          //   let selectId = 0;
          //   selectedRowKeys.value = [];
          //   // 一级分类
          //   const p1 = data.value[0];
          //   eks.push(p1.docsId);
          //   selectId = p1.docsId;
          //   if (p1.children) {
          //     // 二级分类
          //     const p2 = p1.children[0];
          //     eks.push(p2.docsId);
          //     selectId = p2.docsId;
          //     if (p2.children) {
          //       const p3 = p2.children[0];
          //       eks.push(p3.docsId);
          //       selectId = p3.docsId;
          //     }
          //   }
          //   selectedRowKeys.value.push(selectId);
          //   expandedRowKeys.value = eks;
          //   current.value = data.value[0];
          //   docsId.value = data.value[0].docsId;
          // }
        })
        .catch((e) => {
          loading.value = false;
          message.error(e.message);
        });
    }
  };

  // 查询文档
  const queryDocs = () => {
    selectedRowKeys.value = [];
    const eks: number[] = [];
    // 展开当前分类及选中当前分类
    selectedRowKeys.value.push(Number(form.docsId));
    eachTreeData(
      data.value,
      (item, index, parent) => {
        // index 是当前循环索引, parent 是父级数据
        if (item.docsId == form.docsId) {
          expandedRowKeys.value = item.parentIds;
          assignObject(form,item);
        }
      },
      'children'
    );
  };

  /* 删除 */
  const remove = () => {
    Modal.confirm({
      title: '提示',
      content: '确定要删除选中的文档吗?',
      icon: createVNode(ExclamationCircleOutlined),
      maskClosable: true,
      onOk: () => {
        const hide = message.loading('请求中..', 0);
        removeDocs(current.value?.docsId)
          .then((msg) => {
            hide();
            message.success(msg);
            reload();
          })
          .catch((e) => {
            hide();
            message.error(e.message);
          });
      }
    });
  };

  watch(
    currentRoute,
    (route) => {
      const { params, query } = unref(route);
      // 获取书籍的英文标识
      if (params.name) {
        bookCode.value = String(params.name);
        reload();
      }
      // 获取当前文档ID
      const id = Number(query.id);
      if (id > 0) {
        form.docsId = id;
      } else {
        form.docsId = undefined;
      }
    },
    { immediate: true }
  );
</script>

<script lang="ts">
  export default {
    name: 'Docs'
  };
</script>
<style lang="less" scoped>
  .transparent-bg {
    background-color: transparent; /* 设置背景透明 */
  }
  .sys-docs-list {
    padding: 12px 6px;
    height: calc(100vh - 160px);
    border-width: 1px;
    border-style: solid;
    overflow: auto;
  }
  :deep(.ant-tree-node-selected) {
    color: var(--orange-7);
    font-weight: 700;
    background: none !important;
  }
</style>
