import React from 'react'
import { Popover, Tree } from 'antd'
import { arrayToTree } from '../../../utils/baseUtils'
import './popover.less'
const { TreeNode } = Tree;

class PopTree extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            expandedKeys: [props.pGroup.code]
        }
    }

    generateTreeNode(treeData) {
        let list = treeData.sort((a, b) => (a.index - b.index)).map(t => {
            return <TreeNode
                title={t.label}
                key={t.code}
            >
                {(t.children && t.children.length > 0) && this.generateTreeNode(t.children)}
            </TreeNode>
        });

        return list;
    }

    /**
     * 查找节点的所有子节点
     */
    findTree = (tree, group) => {
        let fGroup;
        for(let i = 0; tree && i < tree.length; i++) {
            if(tree[i].code === group.code) {
                fGroup = tree[i];
            }else {
                fGroup = this.findTree(tree[i].children, group);
            }
            if(!fGroup) {
                break;
            }
        }
        return fGroup;
    }


    render() {
        const { visible, handleVisibleChange, pGroup, groupList, selectGroup, children } = this.props;
        const { expandedKeys } = this.state;
        let treeData = arrayToTree(groupList, pGroup.code, 'code', 'pcode', 'children');
        
        return (
            <Popover
                overlayClassName='groupselector'
                placement="bottomLeft"
                trigger='click'
                visible={visible}
                onVisibleChange={handleVisibleChange}
                content={
                    <Tree
                        expandedKeys={expandedKeys}
                        onExpand={(expandedKeys) => {
                            this.setState({
                                expandedKeys
                            });
                        }}
                        onSelect={(selectedKeys) => {
                            let group = groupList.find(g => g.code === selectedKeys[0]);
                            selectGroup(group);
                        }}
                    >
                        {
                            <TreeNode title={pGroup.label} key={pGroup.code}>{this.generateTreeNode(treeData)}</TreeNode>
                        }
                    </Tree>
                }
            >
                { children }
            </Popover>
        );
    }
}

export default PopTree;