/* eslint-disable no-plusplus */
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { utils } from 'amos-tool';
import classNames from 'classnames';
import connectMenu from './connectMenu';
import LevelMenu from './LevelMenu';

const calcHtmlSize = (value, ratio) => {
  if (!utils.isNil(value) && !utils.isNull(value)) {
    if (utils.isNumber(value)) {
      return parseFloat(value) * ratio;
    } else if (utils.isString(value)) {
      const numVal = parseFloat(value);
      const unit = value.replace(numVal, '');
      return `${numVal * ratio}${unit}`;
    }
  }

  return 0;
};

/**
 * 子菜单
 *
 * @class SubMenuItem
 * @extends {PureComponent}
 */
@connectMenu
class SubMenuItem extends PureComponent {
  genRecursiveStyle = level => {
    const { menuWidth } = this.props;
    return {
      width: menuWidth,
      left: calcHtmlSize(menuWidth, level)
    };
  };

  /** 每一个 subitem 均是其父节点的内容，所以只需要 left 其父节点的宽即可 */
  genRecursiveStyle2 = () => {
    const { menuWidth } = this.props;
    return {
      width: menuWidth,
      left: menuWidth
    };
  };

  recursiveRender = (subItems, level = 1) => {
    const { onSubMenuClick, rootMenuKey, iconPrefix } = this.props;
    const cls = `recursive-level-menu content-level${level}`;
    const style = this.genRecursiveStyle2();
    return (
      <ul className={cls} style={style}>
        {subItems.map(si => {
          const cls = classNames('menu-subitem', {
            // 'active': si.key === activeRecursiveKey
          });
          const nonChild = utils.isEmpty(si.children);
          let newLevel = level;
          if (!nonChild) {
            newLevel += 1;
          }
          return (
            <LevelMenu
              {...si}
              key={si.sequenceNbr}
              menuKey={si.sequenceNbr}
              className={cls}
              iconPrefix={iconPrefix}
              nonChild={nonChild}
              onClick={() => onSubMenuClick(rootMenuKey, si.sequenceNbr)}
            >
              {!nonChild && this.recursiveRender(si.children, newLevel)}
            </LevelMenu>
          );
        })}
      </ul>
    );
  };

  render() {
    const { className, children, onClick, subItems } = this.props;
    return (
      <li className={className} onClick={onClick}>
        {children}
        {subItems && subItems.length > 0 && this.recursiveRender(subItems)}
      </li>
    );
  }
}

SubMenuItem.propTypes = {
  className: PropTypes.string,
  iconPrefix: PropTypes.string,
  // 菜单 key，此处是 subMenuKey
  menuKey: PropTypes.string,
  // 根节点菜单 key
  rootMenuKey: PropTypes.string,
  onClick: PropTypes.func,
  onSubMenuClick: PropTypes.func,
  children: PropTypes.node,
  subItems: PropTypes.array,
  menuWidth: PropTypes.oneOfType([PropTypes.string, PropTypes.number])
};

export default SubMenuItem;
