/**
 * Created by baoyinghai on 4/12/17.
 */
import React from 'react';
import Qs from 'qs';
import { iconWrapper } from '../../framework/utils/IconHelper';
import { getAllLeafs } from '../../framework/utils/MenuHelper';
import { CONTAINER_PRE } from '../../framework/entrance/routes';
import { isApply, isReview } from '../../framework/utils/ProcessHelper';
import menuaim from './menuaim';
import { clickSpaceWrapper } from '../clickSpaceCallback';
import { saveProcessMenuCode, saveEnterMenuId } from '../../framework/service/SessionStorage';
import { jumpToNewTab } from '../../framework/utils/windowUtils';

export class HNav extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      activeSubIndex: -1,
      activeSubSubIndex: -1,
      activeSubSubSubIndex: -1,
    };
    this.handleMouseLeaveMenu = menuaim.handleMouseLeaveMenu.bind(this);
    this.handleMouseEnterRow = menuaim.handleMouseEnterRow.bind(this);
    this.didMount = menuaim.componentDidMount.bind(this);
    this.unMount = menuaim.componentWillUnmount.bind(this);
    this.__getMouseMoveDocumentHandler = menuaim.__getMouseMoveDocumentHandler.bind(this);
  }

  _switchHandler = e => {
    const tag = document.querySelector('.total-menu');
    if (tag && tag.compareDocumentPosition(e.target) !== 20) {
      this._switchTotalMenu();
    }
  };

  _switchTotalMenu = () => {
    this.props.switchHandler && this.props.switchHandler();
  };

  handleSwitchactiveSubIndex = index => {
    this.setState({
      activeSubIndex: index,
      activeSubSubIndex: -1,
      activeSubSubSubIndex: -1,
    });
  };

  handleSwitchactiveSubSubIndex = index => {
    this.setState({
      activeSubSubIndex: index,
      activeSubSubSubIndex: -1,
    });
  };

  handleSwitchactiveSubSubSubIndex = index => {
    this.setState({
      activeSubSubSubIndex: index
    });
  };

  _getActionLink = item => {
    return item.domainLink || item.actionLink;
  };

  // mutile
  _updateEnterMenuId = (menuCode, processId) => {
    this.props.updateEnterMenuId([menuCode, processId]);
  };

  // mutile
  _getMenuBindParams = menuItem => {
    const ret = {};
    menuItem.bindParameters && menuItem.bindParameters.forEach(item => {
      ret[item.name] = item.value;
    });
    if (isApply(this._getActionLink(menuItem))) {
      ret.menu = 'BPMApply.QueryToDo';
    } else if (isReview(this._getActionLink(menuItem))) {
      ret.menu = 'BPMReview.QueryToDo';
    }
    return ret;
  };

  _menuItemClick = item => {
    const link = this._getActionLink(item);
    if (link) {
      const bindParameters = this._getMenuBindParams(item);
      saveProcessMenuCode(bindParameters.menu);
      saveEnterMenuId(item.menuCode);
      // 如果menuItemClick 是Info模板的话 就跳新页面
      // if (item.templateType === 'Info') {
      //   jumpToNewTab(
      //     '/' + CONTAINER_PRE + this._getActionLink(item) + '?p=' + btoa(Qs.stringify({ ...bindParameters, enterMenuId: item.menuCode, domainType: item.templateType, s: '1' })),
      //     { buttonCode: item.menuCode }
      //   );
      // } else {
      //   this.props.push({ pathname: '/' + CONTAINER_PRE + this._getActionLink(item), state: { ...bindParameters } });
      // }
      this.props.push({ pathname: '/' + CONTAINER_PRE + this._getActionLink(item), state: { ...bindParameters } });
      this._switchTotalMenu();
    }
  };

  _cancelQuickMenu = (event, menuCode) => {
    event.stopPropagation();
    const quickMenu = this.props.quickMenu || [];
    this.props.updateQuickMenu(quickMenu.filter(item => item !== menuCode));
  };

  _addQuickMenu = (event, menuCode) => {
    event.stopPropagation();
    const quickMenu = this.props.quickMenu || [];
    quickMenu.push(menuCode);
    this.props.updateQuickMenu(quickMenu);
  };

  _isQuickMenu = code => {
    const quickMenu = this.props.quickMenu || [];
    return quickMenu.indexOf(code) !== -1;
  };

  _renderIcon = item => {
    if (!item.subMenus || item.subMenus.length === 0) {
      if (this._isQuickMenu(item.menuCode)) {
        return iconWrapper('icon-shoucangshixin', null, null, { onClick: event => this._cancelQuickMenu(event, item.menuCode) });
      }
      if (this._getActionLink(item)) {
        return iconWrapper('icon-shoucang', null, null, { onClick: event => this._addQuickMenu(event, item.menuCode) });
      }
      return null; //  no sub menu and  can't click
    }
    return iconWrapper('icon-arrow');
  };

  _renderAllMenuItems = (cname, activeIndex) => {
    const leafs = getAllLeafs(this.props.menu);
    return leafs.map((menu, index) => {
      let className = 'leafs menu-item';
      if (index === this.state[activeIndex]) {
        className += ' active';
      }
      return (
        <li
          className={className}
          key={index}
          onMouseEnter={() => this['handleSwitch' + activeIndex](index)}
          onClick={() => this._menuItemClick(menu)}
        >
          <span>{menu.menuValue}</span>
          {this._renderIcon(menu)}
        </li>
      );
    });
  };

  _renderItems = (menus, cname, activeIndex) => {
    return menus.map((menu, index) => {
      let className = 'menu-item';
      if (index === this.state[activeIndex]) {
        className += ' active';
      }
      return (
        <li
          className={className}
          key={index}
          onMouseEnter={() => {
            this.handleMouseEnterRow.call(this, index, this['handleSwitch' + activeIndex], {
              submenuDirection: 'right',
              menuSelector: '.' + cname,
              delay: 300,
              tolerance: 75
            });
          }}
          onClick={() => this._menuItemClick(menu)}
        >
          <span>{menu.menuValue}</span>
          {this._renderIcon(menu)}
        </li>
      );
    });
  };

  _renderUl = (menus, cname, activeIndex = '') => {
    return (
      <ul className={cname + (menus && menus.isAll ? ' leaf-wrapper' : '')} onMouseLeave={this.handleMouseLeaveMenu}>
        {
          (() => {
            if (menus) {
              if (menus.isAll) {
                return this._renderAllMenuItems(cname, activeIndex);
              }
              return this._renderItems(menus, cname, activeIndex);
            }
            return null;
          })()
        }
      </ul>
    );
  };

  _getAppendDataMenu = () => {
    return [{ menuValue: '全部', subMenus: { isAll: true } }, ...this.props.menu];
  };

  _renderAllMenu = () => {
    const menu = this._getAppendDataMenu();
    return (
      <div className="total-menu-detail">
        {menu && this._renderUl(menu, 'menu', 'activeSubIndex')}
        {menu &&
        menu[this.state.activeSubIndex] &&
        this._renderUl(menu[this.state.activeSubIndex].subMenus, 'sub-menu', 'activeSubSubIndex')}
        {menu
        && menu[this.state.activeSubIndex]
        && menu[this.state.activeSubIndex].subMenus
        && menu[this.state.activeSubIndex].subMenus[this.state.activeSubSubIndex]
        && this._renderUl(menu[this.state.activeSubIndex].subMenus[this.state.activeSubSubIndex].subMenus, 'sub-sub-menu', 'activeSubSubSubIndex')}
      </div>
    );
  };

  componentDidMount() {
    this.didMount();
  }

  componentWillUnmount() {
    this.unMount();
  }

  componentWillReceiveProps() {

  }

  render() {
    return (
      <div className={'total-menu ' + (this.props.show ? 'active' : '') + ' ' + (this.props.refStr || ' ')}>
        {this.props.desc ? (<span style={{ paddingRight: '5px' }}>/</span>) : null}
        <span onClick={this._switchTotalMenu}>{this.props.desc || '产品与服务'}</span>
        {this.props.desc ? null : iconWrapper('icon-jiantou')}
        <div className="total-menu-detail-wrapper">
          {this._renderAllMenu()}
        </div>
      </div>
    );
  }
}


export default clickSpaceWrapper(HNav, { querySelector: 'total-menu-ref' });
