/**
 * imui.MenuItem
 * @author moxhe(何璇)
 * @date 2018-05-29
 */

import React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import { menuContext } from './context';
import Menu from './Menu';

class MenuItem extends React.Component {
  static propTypes = {
    /**
     * 唯一标志
     */
    name: PropTypes.string.isRequired,
    /**
     * 是否可点击
     */
    disabled: PropTypes.bool,
    /**
     * 子扩展相关属性
     */
    spread: PropTypes.any,
    /**
     * 扩展内容可见性
     */
    spreadVisible: PropTypes.bool,
  };

  static defaultProps = {
    disabled: false,
    spreadVisible: false,
  };

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

  componentWillReceiveProps(nextProps) {
    const { spreadVisible } = nextProps;

    if (spreadVisible !== this.props.spreadVisible) {
      this.toggleSpreadVisible(spreadVisible);
    }
  }

  toggleSpreadVisible(v = !this.props.spreadVisible) {
    this.setState({ spreadVisible: v });
  }

  render() {
    const { Consumer } = menuContext;
    const { name, disabled, className } = this.props;
    let { spread } = this.props;
    const { spreadVisible } = this.state;
    const { collapsed } = this.state;
    const wrapperCls = classnames('im-menu-item-wrapper',  {
      [className]: !!className,
      'im-menu-item-wrapper--spread': !!spread,
    });
    const cls = classnames('im-menu-item', {
      'im-menu-item--disabled': disabled,
    });

    if (spread && spread.type === Menu) {
      spread = React.cloneElement(spread, {
        className: `im-menu--sub ${spread.props.className || ''}`
      });
    }

    return (
      <Consumer>
        {(({ interactType, onClick }) => {
          let itemPorps = {};
          if (interactType === 'hover') {
            itemPorps = {
              onMouseEnter: () => {
                this.toggleSpreadVisible(true);
              },
              onMouseLeave: () => {
                this.toggleSpreadVisible(false);
              },
            };
          }

          const ttProps = {
            onClick: (e) => {
              if (interactType === 'click') {
                this.toggleSpreadVisible();
              }
              onClick(e, name);
            }
          };

          return (
            <li className={wrapperCls} {...itemPorps}>
              <div className={cls} {...ttProps}>
                {this.props.children}
              </div>
              {spread && spreadVisible ? spread : null}
            </li>
          );
        })}
      </Consumer>
    );
  }
}

export default MenuItem;
