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";

// const treeData: TreeDataNode[] = [
//   {
//     title: "文件: Test.exe",
//     key: "0-0",
//     children: [
//       {
//         title: "Dos 头部",
//         key: "0-0-0",
//       },
//       {
//         title: "Nt 头部",
//         key: "0-0-1",
//         children: [
//           {
//             title: "文件头部",
//             key: "0-0-1-0",
//           },
//           {
//             title: "可选头部",
//             key: "0-0-2-0",
//             children: [
//               {
//                 title: "数据目录",
//                 key: "0-0-1-1",
//               },
//             ],
//           },
//         ],
//       },
//       {
//         title: "节 头部",
//         key: "0-0-2",
//       },
//       {
//         title: "导入目录",
//         key: "0-0-3",
//       },
//       {
//         title: "资源目录",
//         key: "0-0-4",
//       },
//       {
//         title: "地址转换",
//         key: "0-0-5",
//       },
//       {
//         title: "依赖性分析",
//         key: "0-0-6",
//       },
//     ],
//   },
// ];

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

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

  const onSelect: TreeProps["onSelect"] = (selectedKeys, info) => {
    console.log("selected", selectedKeys, info);
    setSelectedKey(selectedKeys[0] as any);
  };

  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]);
  console.log("selectedKey", selectedKey);

  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>
  );
}
