import React from 'react';
import { Button, Card, Tree, Modal } from 'antd';
import useBool from '@/utils/hooks/useBool';
import arr2Tree from '@/utils/arr2Tree';

export default (props) => {
  const { role } = props;
  
  const [loading, startLoading, cancelLoading] = useBool();
  const [list, setList] = React.useState([]);
  const [treeData, setTreeData] = React.useState([]);

  const title = role ? `${role.name} - 授权菜单` : '授权菜单';

  const onSelect = (selectedKeys, info) => {
    console.log('selected', selectedKeys, info);
  };
  const onCheck = (checkedKeys, info) => {
    console.log('onCheck', checkedKeys, info);
  };

  React.useEffect(() => {
    if (!role) {
      setList([]);
    }
  }, [role]);
  
  React.useEffect(() => {
    // 先转为需要的格式
    const arr = list.map(x => ({ title: x.name, key: x.id, parentId: x.parentId }));
    // 再转为 tree
    setTreeData(arr2Tree(arr));
  }, [list]);

  return (
    <Card
      loading={loading}
      title={title}
      extra={<Button type='primary' ghost>保存</Button>}
    >
      <Tree
        checkable
        onSelect={onSelect}
        onCheck={onCheck}
        treeData={treeData}
      />
    </Card>
  )
}
