import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import MenuItem from './MenuItem';

/**
 * 菜单 列表
 *
 * @class MenuList
 * @extends {PureComponent}
 */
class MenuList extends PureComponent {

  constructor(props) {
    super(props);
    this.state = {
      /** 当前选中一级菜单 key */
      activeKey: '',
      /** 当前选中的二级菜单 key */
      activeSubKey: ''
    };
  }

  onSubMenuClick = (key, subKey) => {
    this.setState({
      activeKey: key,
      activeSubKey: subKey
    });
    this.props.onMenuClosed();
  }

  setMenuActive = (key) => {
    const { activeKey } = this.state;
    if (activeKey !== key){
      this.setState({
        activeKey: key
      });
    }
  }

  setSubMenuActive = (key) => {
    const { activeSubKey } = this.state;
    if (activeSubKey !== key){
      this.setState({
        activeSubKey: key
      });
    }
  }

  render() {
    const { activeKey, activeSubKey } = this.state;
    const { height, navs, onMenuOpen, onMenuClosed, toggleSubMenu, renderSubmenu, menuWidth, iconPrefix } = this.props;
    const cls = height > 0 ? 'nav-menu-box menu-expanded' : 'nav-menu-box';
    return (
      <div className="nav-menu-wrapper">
        <div className={cls}>
          <div
            className="nav-menu-bg"
            style={{ height }}
            onMouseOver={this.onMouseOver}
            onMouseOut={this.onMouseOut}
          />
          <ul className="nav-menu-list" onMouseOver={onMenuOpen} onMouseOut={onMenuClosed}>
            {
              (navs || []).map(n => {
                const { sequenceNbr, ...rest } = n;
                return (
                  <MenuItem
                    key={sequenceNbr}
                    {...rest}
                    iconPrefix={iconPrefix}
                    menuKey={sequenceNbr}
                    height={height}
                    activeKey={activeKey}
                    activeSubKey={activeSubKey}
                    setMenuActive={this.setMenuActive}
                    setSubMenuActive={this.setSubMenuActive}
                    onSubMenuClick={this.onSubMenuClick}
                    onMenuClosed={onMenuClosed}
                    toggleSubMenu={toggleSubMenu}
                    renderSubmenu={renderSubmenu}
                    menuWidth={menuWidth}
                  />);
              })
            }
          </ul>
        </div>
      </div>
    );
  }
}

MenuList.propTypes = {
  height: PropTypes.number,
  navs: PropTypes.arrayOf(PropTypes.shape({
    sequenceNbr: PropTypes.string.isRequired,
    permissionName: PropTypes.string.isRequired,
    icon: PropTypes.string,
    path: PropTypes.string,
    children: PropTypes.array
  })),
  toggleSubMenu: PropTypes.func,
  onMenuOpen: PropTypes.func,
  onMenuClosed: PropTypes.func,
  renderSubmenu: PropTypes.func,
  menuWidth: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.number
  ])
};

export default MenuList;
