import React from 'react'
import { Popover, Row, Col, Icon, Divider } from 'antd'
import { connect } from 'dva'
import './groupSelector.less'

class GroupSelector extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            visible: false
        }
    }

    hide = () => {
        this.setState({
            visible: false,
        });
    }

    handleVisibleChange = (visible) => {
        this.setState({ visible });
    }

    render() {
        const { model, modelName, children, dispatch } = this.props;
        const { visible } = this.state;
        const grouplist = model.groupList;
        const pgroups = grouplist.filter(g => g.pcode === '-1');

        const currentGroup = model.currentGroup;

        return (
            <Popover
                overlayClassName='groupselector'
                placement="bottomLeft"
                trigger='click'
                visible={visible}
                onVisibleChange={this.handleVisibleChange}
                content={
                    [{code: 'all', label: '全部分组'}, { code: '-1', label: '未分组' }].concat(pgroups).map(p => {
                        let cgroups = grouplist.filter(g => g.pcode === p.code && p.code !== '-1');
                        return <Row type='flex' justify='left' key={`gr-${p.code}`}>
                            <Col key={`rc-${p.code}`} onClick={() => {
                                this.hide();
                                dispatch({ type: modelName + '/setCurrentGroup', group1: p });
                            }}>
                                {<span className={`group${currentGroup[0].code === p.code ? ' selected' : ''}`}>{p.label}</span>}{cgroups.length>0 && <Icon type="right" />}
                            </Col>
                            {
                                cgroups.map((c, i) => <Col key={c.code} onClick={() => {
                                    this.hide();
                                    dispatch({ type: modelName + '/setCurrentGroup', group1: p, group2: c });
                                }}>
                                    {<span className={`group${currentGroup[1] ? (currentGroup[1].code === c.code ? ' selected' : '') : ''}`}>{c.label}</span>}
                                    {i === cgroups.length-1 ? '' : <Divider className='group-divider' type="vertical" />}
                                </Col>)
                            }
                        </Row>
                    })
                }
            >
                { children }
            </Popover>
        );
    }
}

export default connect()(GroupSelector);