<template>
  <div class="m-4 mr-0 overflow-hidden bg-white">
    <BasicTree
      ref="asyncExpandTreeRef"
      title="菜单列表"
      toolbar
      search
      treeWrapperClassName="h-[calc(100%-35px)] overflow-auto"
      :actionList="actionList"
      :renderIcon="createIcon"
      :clickRowToExpand="false"
      :treeData="treeData"
      :fieldNames="{ key: 'id', title: 'name' }"
      :defaultExpandAll="true"
      @select="handleSelect"
    />
  </div>
</template>
<script lang="ts" setup>
  import { onMounted, ref, h, nextTick, unref } from 'vue';
  import { BasicTree, TreeItem, TreeActionItem, TreeActionType } from '@/components/Tree';
  import { getMenuList, deleteMenu, getAllModuleDetail, getSpecialData } from '@/api/demo/system';
  import { FormOutlined, DeleteOutlined } from '@ant-design/icons-vue';
  import { router } from '@/router';
  import { useMessage } from '@/hooks/web/useMessage';

  const { createMessage, createConfirm } = useMessage();
  const emit = defineEmits(['select', 'edit']);

  defineOptions({ name: 'DeptTree' });
  const treeData = ref<TreeItem[]>([]);
  let selectItemId = ref('');
  const asyncExpandTreeRef = ref<Nullable<TreeActionType>>(null);
  async function fetch() {
    treeData.value = (await getMenuList()) as unknown as TreeItem[];
    setTimeout(() => {
      treeData.value.forEach((item, index) => {
        let moduleDetail = allModuleDetail.value?.find((detail) => {
          return detail.id == item.id;
        });
        if (moduleDetail) {
          let title = specialMenu.value.find((sp) => {
            return sp.id == moduleDetail.moduleTypeId;
          })?.title;
          if (title) {
            treeData.value[index].name = item.name = item.name + ' （' + title + ')';
          }
        }
      });
    }, 500);
    // 展开全部
    nextTick(() => {
      unref(asyncExpandTreeRef)?.expandAll(true);
    });
  }

  function handleSelect(keys) {
    emit('select', keys[0]);
  }
  const btnList = router.currentRoute.value.meta.elements;
  const actionList: TreeActionItem[] = [];
  btnList.forEach((element) => {
    if (element.domId == 'btnEdit') {
      actionList.push({
        render: (node) => {
          return h(FormOutlined, {
            class: 'ml-2',
            onClick: () => {
              emit('edit', node);
            },
          });
        },
      });
    } else if (element.domId == 'btnDelete') {
      actionList.push({
        render: (node) => {
          return h(DeleteOutlined, {
            class: 'ml-2',
            onClick: () => {
              selectItemId.value = node.id;
              createConfirm({
                iconType: 'warning',
                title: '删除',
                content: '确认要删除菜单吗?',
                onOk: async () => {
                  var query = [selectItemId.value];
                  const data = await deleteMenu(query);
                  if (data) {
                    fetch();
                    createMessage.success('删除成功');
                  } else {
                    createMessage.info('删除失败');
                  }
                },
              });
            },
          });
        },
      });
    }
  });

  function createIcon({ level }) {
    if (level === 1) {
      return 'ion:git-compare-outline';
    }
    if (level === 2) {
      return 'ion:home';
    }
    if (level === 3) {
      return 'ion:airplane';
    }
    return '';
  }

  // 专题
  const specialMenu = ref();
  async function specialData() {
    specialMenu.value = await getSpecialData();
  }
  const allModuleDetail = ref();
  async function funGetAllModuleDetail() {
    allModuleDetail.value = await getAllModuleDetail();
  }

  onMounted(() => {
    funGetAllModuleDetail();
    specialData();
    fetch();
  });
  defineExpose({
    fetch,
    treeData,
  });
</script>
