import React from 'react';
import { Button, Card, Tree, message } from 'antd';
import useBool from '@/utils/hooks/useBool';
import { arr2Tree, uniq } from '@/utils/array';
import { getResourceList } from '@/services/role';

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

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

  const onCheck = (keys, info) => {
    const { checkedNodes } = info;
    checkedNodesRef.current = checkedNodes;
    // const keys = checkedNodes.map(node => getKeysWithParent(node, treeDictRef.current));
    // setCheckedKeys(uniq(keys));
    setCheckedKeys(keys);
  };

  const onSubmit = () => {
    if (!checkedNodesRef.current) {
      return;
    }

    if (checkedNodesRef.current.length !== checkedKeys.length) {
      message.warn('未知错误, 请刷新重试');
      return;
    }

    const keys = checkedNodesRef.current.map(node => getKeysWithParent(node, treeDictRef.current));

  }

  React.useEffect(() => {
    startLoading();
    getResourceList({ pageSize: 500, type: 'menu' }).then((res) => {
      cancelLoading();
      setList(res.records || []);
    }).catch(() => {
      cancelLoading();
    })
  }, []);

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

  return (
    <Card
      loading={loading}
      title={title}
      extra={<Button type='primary' ghost onClick={onSubmit}>保存</Button>}
    >
      <Tree
        checkable
        autoExpandParent
        checkStrictly={false}
        selectable={false}
        checkedKeys={checkedKeys}
        onCheck={onCheck}
        treeData={treeData}
      />
    </Card>
  )
}

function getKeysWithParent(node, dict) {
  if (node.parentId === -1) return [node.key];
  const parentKeys = getKeysWithParent(dict[node.parentId], dict);
  return parentKeys ? [node.key].concat(parentKeys) : [node.key];
}
