<template>
  <div class="ele-body">
    <a-card :bordered="false" :body-style="{ padding: '16px' }">
      <ele-split-layout
        width="266px"
        allow-collapse
        :right-style="{ overflow: 'hidden' }"
        :style="{ minHeight: 'calc(100vh - 152px)' }"
      >
        <div>
          <ele-toolbar theme="default">
            <a-space :size="10">
              <a-button
                type="primary"
                :size="`small`"
                class="ele-btn-icon"
                @click="openEdit()"
              >
                <template #icon>
                  <plus-outlined />
                </template>
              </a-button>
              <a-button
                type="primary"
                :size="`small`"
                :disabled="!current"
                class="ele-btn-icon"
                @click="openEdit(current)"
              >
                <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-category-list">
            <a-tree
              :tree-data="data"
              v-model:expanded-keys="expandedRowKeys"
              v-model:selected-keys="selectedRowKeys"
              @select="onTreeSelect"
            >
              <template #title="{ type, key: treeKey, title }">
                <a-dropdown :trigger="['contextmenu']">
                  <span>{{ title }}</span>
                  <template #overlay v-if="type == 0">
                    <a-menu
                      @click="
                        ({ key: menuKey }) =>
                          onContextMenuClick(treeKey, menuKey)
                      "
                    >
                      <a-menu-item key="1">修改</a-menu-item>
                      <a-menu-item key="2">删除</a-menu-item>
                    </a-menu>
                  </template>
                </a-dropdown>
              </template>
            </a-tree>
          </div>
        </div>
        <template #content>
          <list
            v-if="current"
            :category-list="data"
            :data="current"
            :category-id="current.categoryId"
          />
        </template>
      </ele-split-layout>
    </a-card>
    <!-- 编辑弹窗 -->
    <category-edit
      v-model:visible="showEdit"
      :data="editData"
      :category-list="data"
      :category-id="current?.categoryId"
      @done="query"
    />
  </div>
</template>

<script lang="ts" setup>
  import { createVNode, ref } from 'vue';
  import { message, Modal } from 'ant-design-vue';
  import {
    PlusOutlined,
    EditOutlined,
    DeleteOutlined,
    ExclamationCircleOutlined
  } from '@ant-design/icons-vue';
  import { toTreeData, eachTreeData } from 'ele-admin-pro';
  import List from './list.vue';
  import CategoryEdit from './components/category-edit.vue';
  import {
    listArticleCategory,
    removeArticleCategory
  } from '@/api/cms/category';
  import { ArticleCategory } from '@/api/cms/category/model';

  // 加载状态
  const loading = ref(true);

  // 树形数据
  const data = ref<ArticleCategory[]>([]);

  // 树展开的key
  const expandedRowKeys = ref<number[]>([]);

  // 树选中的key
  const selectedRowKeys = ref<number[]>([]);

  // 选中数据
  const current = ref<ArticleCategory | any>(null);

  // 是否显示表单弹窗
  const showEdit = ref(false);

  // 编辑回显数据
  const editData = ref<ArticleCategory | null>(null);

  /* 查询 */
  const query = () => {
    loading.value = true;
    listArticleCategory()
      .then((list) => {
        loading.value = false;
        const eks: number[] = [];
        list.forEach((d) => {
          d.key = d.categoryId;
          d.value = d.categoryId;
          if (typeof d.categoryId === 'number') {
            eks.push(d.categoryId);
          }
        });
        expandedRowKeys.value = eks;
        data.value = toTreeData({
          data: list.map((d) => {
            d.disabled = d.type != 0;
            return d;
          }),
          idField: 'categoryId',
          parentIdField: 'parentId'
        });
        if (list.length) {
          if (typeof list[0].categoryId === 'number') {
            selectedRowKeys.value = [list[0].categoryId];
          }
          current.value = list[0];
        } else {
          selectedRowKeys.value = [];
          current.value = null;
        }
      })
      .catch((e) => {
        loading.value = false;
        message.error(e.message);
      });
  };

  /* 选择数据 */
  const onTreeSelect = () => {
    current.value = {};
    eachTreeData(data.value, (d) => {
      if (
        typeof d.categoryId === 'number' &&
        selectedRowKeys.value.includes(d.categoryId)
      ) {
        current.value = d;
        return false;
      }
    });
  };

  const onContextMenuClick = (treeKey: number, menuKey: number) => {
    // 修改
    if (menuKey == 1) {
      openEdit(current.value);
    }
    // 删除
    if (menuKey == 2) {
      remove();
    }
  };

  /* 打开编辑弹窗 */
  const openEdit = (item?: ArticleCategory | null) => {
    editData.value = item ?? null;
    showEdit.value = true;
  };

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

  query();
</script>

<script lang="ts">
  export default {
    name: 'ArticleIndex'
  };
</script>

<style lang="less" scoped>
  .sys-category-list {
    padding: 12px 6px;
    height: calc(100vh - 242px);
    border-width: 1px;
    border-style: solid;
    overflow: auto;
  }
</style>
