import React, {useState} from 'react';
import {Card} from "antd";
import {DownOutlined} from "@ant-design/icons";
import {useRequest} from "@@/plugin-request/request";
import {fetchSystemTreeDevice2} from "@/services/dict";
import createSystemTree from './utils/createSystemTree'
import DirectoryTree from '@/components/DirectoryTree'


import styles from "./index.less";

type ProjectTreeProps = {
  placeholder?: string;
  onSelect: (id: any) => void
}

const cardBodyStyle: API.Store = {
  padding: 0,
  display: 'flex',
  flexDirection: 'column',
  flex: 1,
  overflow: 'auto'
}

const ProjectTree: React.FC<ProjectTreeProps> = (props) => {
  const {onSelect} = props;

  const [expandedKeys, setExpandedKeys] = useState<any[]>([]);
  const [selectedKeys, setSelectedKeys] = useState<any[] | undefined>();

  // 数据处理
  const systemTree = useRequest(fetchSystemTreeDevice2)
  const systemTreeData = systemTree?.data && createSystemTree(systemTree?.data) || [];

  // expand
  const onExpand = (keys: any, expanded: any) => {
    if (expanded.node.children && expanded.node.children.length > 0) {
      setExpandedKeys(keys);
    }
  };

  const handleSelect = (selectedKey: any, {node}: any) => {
    setSelectedKeys(selectedKey);
    const nodeKey = node.key;
    if (typeof nodeKey === "number"){
      onSelect?.(node.key);
    }
  };

  return (
    <div className={styles.sidebar}>
      <Card className={styles.sidebarCard} size="small" bodyStyle={cardBodyStyle}>
        <div className={styles.border_title} style={{ marginTop: 20 }}>
          <span>设备列表</span>
        </div>
        <div className={styles.treeBox} style={{ marginTop: 15 }}>
          <DirectoryTree
            loading={systemTree.loading}
            checkStrictly
            showIcon
            switcherIcon={<DownOutlined />}
            defaultExpandAll
            autoExpandParent={false}
            onExpand={onExpand}
            expandedKeys={expandedKeys}
            selectedKeys={selectedKeys}
            onSelect={handleSelect}
            directoryData={systemTreeData}
          />
        </div>
      </Card>
    </div>
  );
};

export default ProjectTree;