<template>
  <Tree
    :tree-data="processedTreeData"
    :expanded-keys="expandedKeys"
    :default-expand-all="true"
    :auto-expand-parent="true"
    :virtual="false"
    @select="selectHandler"
  />
</template>
<script setup lang="ts">
  import { ref, watch } from 'vue';
  import { Tree } from 'ant-design-vue';
  import { MonitorSiteTreeNode } from '@/api/sys/model/monitorModel';
  import { TreeNode } from '../types/siteTree';

  const props = defineProps<{ treeData?: MonitorSiteTreeNode }>();
  const emit = defineEmits(['select']);

  const processedTreeData = ref<TreeNode[]>([
    {
      title: '暂无数据',
      key: '0',
      children: [],
    },
  ]);
  const expandedKeys = ref<string[]>([]);

  // 递归处理树节点并格式化为需要的格式
  function walk(node: MonitorSiteTreeNode, parentNodeKeys: string[]): TreeNode {
    const res: TreeNode = {
      title: node.label,
      key: node.id,
      children: [],
      raw: node,
    };

    if (node.children) {
      // 额外的，记录它们的key以将它们全部展开
      parentNodeKeys.push(node.id);
      node.children.forEach((child) => {
        res.children.push(walk(child, parentNodeKeys));
      });
    }

    return res;
  }

  function selectHandler(_, { selectedNodes }) {
    emit('select', selectedNodes.raw);
  }

  // 更新逻辑在这里
  watch(
    () => props.treeData,
    (v) => {
      if (!v) return;
      expandedKeys.value = [];
      processedTreeData.value = [walk(v, expandedKeys.value)];
    },
    {
      immediate: true,
    },
  );

  defineExpose({
    processedTreeData,
    expandedKeys,
  });
</script>
