import { getDeptTree } from '@/services/system/user';
import { Tree, message } from 'antd';
import React, { useEffect, useState } from 'react';

const { DirectoryTree } = Tree;

/* *
 *
 * @author whiteshader@163.com
 * @datetime  2023/02/06
 *
 * */

export type TreeProps = {
  onSelect: (values: any) => Promise<void>;
};

const DeptTree: React.FC<TreeProps> = (props) => {
  const [treeData, setTreeData] = useState<any>([]);
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
  const { onSelect } = props;

  useEffect(() => {
    const fetchDeptList = async () => {
      const hide = message.loading('正在查询');
      try {
        const res = await getDeptTree({});
        const treeData = res.map((item: any) => ({ ...item, key: item.id }));
        setTreeData(treeData);
        if (treeData.length > 0) {
          onSelect(treeData[0]);
          setExpandedKeys([treeData[0].key]);
          setSelectedKeys([treeData[0].key]);
        }
        hide();
        return true;
      } catch (error) {
        hide();
        return false;
      }
    };

    fetchDeptList();
  }, []);

  const handleSelect = (keys: React.Key[], info: any) => {
    setSelectedKeys(keys);
    onSelect(info.node);
  };

  const onExpand = (keys: React.Key[]) => {
    setExpandedKeys(keys);
  };

  return (
    <DirectoryTree
      // multiple
      defaultExpandAll
      onExpand={onExpand}
      expandedKeys={expandedKeys}
      selectedKeys={selectedKeys}
      onSelect={handleSelect}
      treeData={treeData}
    />
  );
};

export default DeptTree;
