import React, {useEffect, useState} from 'react';
import { Tree } from 'antd';
import type { DataNode } from 'antd/es/tree';
import {getMenuTree, getRoleMenu} from "@/services/role";

const MenuTree: React.FC = (props) => {
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const [checkedKeys, setCheckedKeys] = useState<React.Key[]>([]);
  const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
  const [autoExpandParent, setAutoExpandParent] = useState<boolean>(true);
  const [treedata,setTreeData] = useState([])

  const [targetTree,setTargetTree] = useState([])



  const search = () => {
    //
    (async ()=> {
      // 获取树的数据
      const msg = await getMenuTree()
      setTreeData(msg.data)

      // 获取设置树的
      const info = await getRoleMenu({r_id:props.editInfo.id})
      setTargetTree(info?.m_ids || [])

      setCheckedKeys(info?.m_ids);
      setExpandedKeys(info?.m_ids);
      localStorage.setItem('checkedKeysValue',JSON.stringify(info?.m_ids || []))
    })()
  }

  useEffect(() => {
    search()
  }, []);


  const onExpand = (expandedKeysValue: React.Key[]) => {
    console.log('onExpand', expandedKeysValue);
    setExpandedKeys(expandedKeysValue);
    setAutoExpandParent(false);

  };

  const onCheck = (checkedKeysValue: React.Key[]) => {
    console.log('onCheck', checkedKeysValue);
    setCheckedKeys(checkedKeysValue);
    // 存储值
    localStorage.setItem('checkedKeysValue',JSON.stringify(checkedKeysValue))

  };

  const onSelect = (selectedKeysValue: React.Key[], info: any) => {
    console.log('onSelect', info);
    setSelectedKeys(selectedKeysValue);
  };

  return (
    <Tree
      checkable
      onExpand={onExpand}
      expandedKeys={expandedKeys}

      autoExpandParent={autoExpandParent}
      onCheck={onCheck}
      checkedKeys={checkedKeys}
      onSelect={onSelect}
      selectedKeys={selectedKeys}
      fieldNames={{
        title:'name',
        key:'id'
      }}
      treeData={treedata}
    />
  );
};

export default MenuTree;
