<template>
  <div class="m-4 mr-0 overflow-hidden bg-white" style="overflow: auto">
    <BasicTree
      title="部门列表"
      ref="asyncExpandTreeRef"
      toolbar
      search
      treeWrapperClassName="h-[calc(100%-35px)] overflow-auto"
      :clickRowToExpand="false"
      :treeData="treeData"
      :fieldNames="{ key: 'id', title: 'name' }"
      @select="handleSelect"
      :load-data="onLoadData"
      :expandedKeys="expandedKeys"
      :loadedKeys="loadedKeys"
    />
  </div>
</template>
<script lang="ts" setup>
  import { onMounted, ref, nextTick, unref } from 'vue';

  import { BasicTree, TreeItem, TreeActionType } from '@/components/Tree';
  import { getChildrenTree } from '@/api/demo/system';

  defineOptions({ name: 'DeptTree' });

  const emit = defineEmits(['select']);

  const treeData = ref<TreeItem[]>([]);
  const asyncExpandTreeRef = ref<Nullable<TreeActionType>>(null);

  async function fetch() {
    treeData.value = (await getChildrenTree({ parentId: 0 })) as unknown as TreeItem[];
    // 展开全部
    nextTick(() => {
      unref(asyncExpandTreeRef)?.filterByLevel(1);
      // unref(asyncExpandTreeRef)?.expandAll(true);
    });
  }
  const expandedKeys = ref<any>([]);
  const loadedKeys = ref<any>([]);
  const firstExpandedKeys = ref<any>([]);

  const getParentIdList = (list, data) => {
    if (data === undefined || data === null) {
      return list;
    }
    list.unshift(data.key);
    return getParentIdList(list, data.parent);
  };
  function handleSelect(keys) {
    emit('select', keys[0]);
  }
  const expand = (expandIdList, data) => {
    if (data.expanded) {
      let parentIdList = getParentIdList([data.node.key], data.node.parent);
      expandedKeys.value = [...parentIdList];
      loadedKeys.value = [...parentIdList];
      console.log(firstExpandedKeys.value, parentIdList);
      let levelData: any = treeData.value[0];
      console.log(levelData);
      for (let i = 1; i < Math.min(firstExpandedKeys.value.length, parentIdList.length); i++) {
        if (firstExpandedKeys.value[i] === parentIdList[i]) {
          levelData = levelData.children.find((item) => item.id === parentIdList[i]);
          console.log(levelData);
        } else {
          let data = levelData.children.find((item) => item.id === firstExpandedKeys.value[i]);
          data.children = null;
          break;
        }
      }
      firstExpandedKeys.value = parentIdList;
    }
  };
  function onLoadData(treeNode) {
    return new Promise((resolve: (value?: unknown) => void) => {
      if (treeNode.children && treeNode.children.length > 0) {
        resolve();
        return;
      }
      getChildrenTree({ parentId: treeNode.id })
        .then((res) => {
          const asyncTreeAction: TreeActionType | null = unref(asyncExpandTreeRef);
          if (asyncTreeAction) {
            const nodeChildren = res;
            asyncTreeAction.updateNodeByKey(treeNode.eventKey, { children: nodeChildren });
            loadedKeys.value.push(treeNode.eventKey);
          }
          resolve();
          return;
        })
        .catch((err) => {
          console.log(err);
          resolve();
          return;
        });
    });
  }
  onMounted(() => {
    fetch();
  });
</script>
