<template>
  <div class="m-4 mr-0 overflow-hidden bg-white">
    <BasicTree
      v-if="treeData.length"
      ref="treeRef"
      title=""
      toolbar
      search
      :treeData="treeData"
      :clickRowToExpand="false"
      :fieldNames="{ key: 'id', title: 'name' }"
      :renderIcon="createIcon"
      v-model:expandedKeys="defaultExpandedKeys"
      @select="handleSelect"
    />
  </div>
</template>
<script lang="ts" setup>
  import { onBeforeMount, ref, defineExpose } from 'vue';
  import { BasicTree } from '/@/components/Tree';

  import { sysMenuQueryTree } from '/@/api/sys/sysMenuApi';
  import { getAllParentKeys } from '/@/utils';

  const emit = defineEmits(['select']);
  const defaultExpandedKeys = ref(['0']);
  const treeData = ref([]);
  const treeRef = ref();
  onBeforeMount(() => {
    getTreeData();
  });

  // 查询树数据
  async function getTreeData() {
    // const res = await sysMenuQueryTree({});
    // treeData.value = res;
    const results = await sysMenuQueryTree({});
    treeData.value = [
      {
        id: '0',
        name: '根目录',
        children: results,
      },
    ];
  }

  // 选中树节点事件
  function handleSelect(keys: string, e) {
    console.log(keys, e);
    emit('select', keys[0]);
  }

  // 刷新树，并选中节点
  async function refresh(nodeId) {
    await getTreeData();
    // 选中nodeId
    const keys = !nodeId ? [] : [nodeId];
    treeRef.value.setSelectedKeys(keys);
    const parentIds = getAllParentKeys(treeData.value, nodeId);
    treeRef.value.setExpandedKeys(!nodeId ? [] : [...parentIds, nodeId]);
  }

  // 格式化图标
  function createIcon() {
    return 'ant-design:apartment-outlined';
  }

  // 暴露内部方法
  defineExpose({ refresh });
</script>
