import styles from "./SideTree.module.scss";
import { Flex } from "antd";
import { Tree } from "antd";
import { DownOutlined } from "@ant-design/icons";
import type { TreeProps } from "antd";
import { useEffect, useState } from "react";

export default function SiderTree({
  treeData,
  defaultSelectedKey,
  onSelect: onTreeSelect,
}) {
  // 展开的节点
  const [expandedKeys, setExpandedKeys] = useState<string[]>([]);

  // 受控 选择的节点
  const [selectedKey, setSelectedKey] = useState<string>(defaultSelectedKey);

  const onSelect: TreeProps["onSelect"] = (_, info) => {
    let key = info.node.key as string;
    console.log("onSelect", key);
    setSelectedKey(key);
    onTreeSelect(key);
  };

  const onExpand: TreeProps["onExpand"] = (_expandedKeys) => {
    setExpandedKeys(_expandedKeys as any);
  };

  // 每次 treeData 变化时，更新 expandedKeys
  useEffect(() => {
    // 递归获取所有的 key
    const getKeys = (nodes) => {
      const keys = nodes.map((node) => node.key);
      nodes.forEach((node) => {
        if (node.children) {
          keys.push(...getKeys(node.children));
        }
      });
      return keys;
    };
    setExpandedKeys(getKeys(treeData));
    // 设置默认选中的节点
    setSelectedKey(defaultSelectedKey);
  }, [treeData]);
  return (
    <Flex className={styles.root}>
      <Tree
        style={{
          width: "100%",
          height: "100%",
        }}
        showLine
        treeData={treeData}
        selectedKeys={[selectedKey]}
        switcherIcon={<DownOutlined />}
        onSelect={onSelect}
        onExpand={onExpand}
        expandedKeys={expandedKeys}
      />
    </Flex>
  );
}
