import React, { Component } from 'react';
import hocImmutable, { imShallowEqual } from '../../utils/HOC/hocImmutable';
import { Menu } from 'antd';

const Comp = hocImmutable(class extends Component {
    constructor(props) {
        super(props);
    }
    state = {
        openKeys: this.props.openKeys || this.props.defaultOpenKeys || []
    }
    componentWillReceiveProps(nextProps) {
        if (this.state.openKeys != nextProps.openKey) {
            this.setState({ openKey: nextProps.openKey })
        }
    }
    onOpenChange = keys => {
        const { onOpenChange, pKeyMap } = this.props;
        if (this.state.openKeys.length < keys.length && keys.length > 1) {
            if (pKeyMap) {
                let deleIndex = 0;
                deleIndex = keys.length - 1;
                const pKey = pKeyMap[keys[deleIndex]];
                for (; deleIndex > 0;) {
                    if (pKey === keys[--deleIndex]) {
                        deleIndex++;
                        break;
                    }
                }
                keys.splice(deleIndex, keys.length - deleIndex - 1);
            }
        }
        this.setState({ openKeys: keys }, () => {
            onOpenChange && onOpenChange(keys);
        })
    }
    onClick = data => {
        if (this.props.mode !== 'inline') {
            this.setState({ openKeys: [] }, () => {
                const { onClick } = this.props;
                onClick && onClick(data);
            })
        } else {
            const { onClick } = this.props;
            onClick && onClick(data);
        }
    }
    render() {
        const { openKey, defaultOpenKeys, onOpenChange, onClick, ...props } = this.props;
        return <Menu {...props}
            openKeys={this.state.openKeys}
            onOpenChange={this.onOpenChange}
            onClick={this.onClick}
        />
    }
});
Comp.Divider = hocImmutable(Menu.Divider);
Comp.Item = hocImmutable(Menu.Item);
Comp.SubMenu = hocImmutable(Menu.SubMenu);
Comp.ItemGroup = hocImmutable(Menu.ItemGroup);
export default Comp;
export const MenuDivider = Comp.Divider;
export const MenuItem = Comp.Item;
export const SubMenu = Comp.SubMenu;
export const MenuItemGroup = Comp.ItemGroup;