<template>
  <div class="m-5 mr-0 overflow-hidden bg-white">
    <BasicTree
      title=""
      ref="treeRef"
      treeWrapperClassName="h-[calc(100%-35px)] overflow-auto"
      :defaultExpandAll="true"
      :treeData="treeData"
      :fieldNames="{ key: 'businessId', title: 'workSpaceName' }"
      @select="handleSelect"
      :actionList="actionList"
    />
  </div>
</template>
<script lang="ts" setup>
  import { h, nextTick, onMounted, ref, unref } from 'vue';
  import { BasicTree, TreeActionType, TreeItem } from '@/components/Tree';
  import { Nullable } from '@vben/types';
  import { GroupTreeData } from './sqlDevelopmentData';
  import { ReloadOutlined } from '@ant-design/icons-vue';
  import { useMessage } from '@/hooks/web/useMessage';

  defineOptions({ name: 'DataSourceTree' });

  const emit = defineEmits(['select']);
  const { createMessage } = useMessage();
  const treeData = ref<TreeItem[]>([]);
  const treeRef = ref<Nullable<TreeActionType>>(null);
  function getTree() {
    const tree = unref(treeRef);
    if (!tree) {
      throw new Error('tree is null!');
    }
    return tree;
  }
  async function fetch() {
    const data = GroupTreeData;
    treeData.value = handleTree(data, 'businessId', undefined, undefined, undefined);
    await nextTick(() => {
      getTree().expandAll(true);
    });
  }

  function handleTree(data, id, parentId, children, rootId) {
    id = id || 'id';
    parentId = parentId || 'parentId';
    children = children || 'children';
    rootId =
      rootId ||
      Math.min.apply(
        Math,
        data.map((item) => {
          return item[parentId];
        }),
      ) ||
      0;
    // 对源数据深度克隆
    const cloneData = JSON.parse(JSON.stringify(data));
    // 循环所有项
    const treeData = cloneData.filter((father) => {
      const branchArr = cloneData.filter((child) => {
        // 返回每一项的子级数组
        return father[id] === child[parentId];
      });
      branchArr.length > 0 ? (father.children = branchArr) : '';
      // 返回第一层
      return father[parentId] === rootId;
    });
    return treeData !== '' ? treeData : data;
  }

  function handleSelect() {
    const keys = getTree().getSelectedKeys();
    const node = getTree().getSelectedNode(keys[0]);
    // console.log('node', node);
    emit('select', node);
  }
  // 树的操作列表
  const actionList = [
    {
      render: () => {
        return h(ReloadOutlined, {
          class: 'ml-2',
          onClick: () => {
            refresh();
          },
        });
      },
    },
  ];
  const refresh = () => {
    createMessage.success('刷新成功');
  };
  onMounted(() => {
    fetch();
  });
</script>
