/**
 * Created by baoyinghai on 2/25/17.
 */
import React from 'react';
import { connect } from 'react-redux';
import Qs from 'qs';
import { Link } from 'react-router';
import { CONTAINER_PRE } from '../../framework/entrance/routes';
import { filterEmptyValue } from '../../framework/utils/EmptyUtils';
import { getMenuItemAndPathByFunc, searchAllMenusByFunc, getMenuItemByFunc } from '../../framework/utils/MenuHelper';
import { getValueByKey } from '../../framework/utils/MapUtils';
import { isApply, isReview } from '../../framework/utils/ProcessHelper';
import { svgWrapper, iconWrapper } from '../../framework/utils/IconHelper';
import { saveProcessMenuCode, saveEnterMenuId } from '../../framework/service/SessionStorage';
import { jumpToNewTab } from '../../framework/utils/windowUtils';

class Navigator extends React.Component {

  static LOGO_HEIGHT = 54;
  static ITEM_HEIGHT = 42;

  constructor(props) {
    super(props);
    let menu = null;
    // 获得默认的菜单项
    if (this.props.quickMenu.length > 0) {
      menu = searchAllMenusByFunc(this.props.menu, m => this.props.quickMenu.indexOf(m.menuCode) !== -1);
    } else {
      menu = searchAllMenusByFunc(this.props.menu, m => m.default);
      // save menu code
      this.props.updateQuickMenu(menu.map(i => i.menuCode));
      // saveMenus(menu.map(m => m.menuCode));
    }
    this.state = { menu, isRender: true };
    // save active menu item;
    this.activeMenuItem = null;
  }

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

  _menuClick = e => {
    // console.log('click menu', e);
    this.setState({
      selectIndex: this.state.hoverIndex,
      hoverIndex: -1,
    });
  };

  _sortedByArray = (menu = [], codeAry) => {
    return codeAry.reduce((ret, item) => {
      const f = menu.filter(m => m.menuCode === item);
      if (f && f[0]) {
        ret.push(f[0]);
        return ret;
      }
      return ret;
    }, []);
  };

  componentWillReceiveProps(nextProps) {
    if (this.props.status !== nextProps.status) {
      this.setState({ isRender: false });
      setTimeout(() => this.setState({ isRender: true }), 300);
    }
    this.setState({
      menu: this._sortedByArray(searchAllMenusByFunc(this.props.menu, m => nextProps.quickMenu.indexOf(m.menuCode) !== -1), nextProps.quickMenu)
    });
  }

  componentDidMount() {
    const backBoard = document.querySelector('.body-wrapper.wrapper.remove-block-space');
    if (backBoard) {
      backBoard.style.backgroundColor = '#282d32';
    }
  }

  // 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;
  };

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

  _renderTitle = () => {
    if (this.props.status) {
      return (
        <div className="menu-logo">
          <div className="img" />
          <span>融资租赁</span>
          {iconWrapper('icon-shuangjiantou', null, null, { onClick: this.props.switchMenu })}
        </div>
      );
    }
    return (
      <div className="menu-logo">
        {iconWrapper('icon-menu', null, null, { onClick: this.props.switchMenu })}
      </div>
    );
  };

  _sortedMenu = (index, menuCode) => {
    const restMenu = this.props.quickMenu.filter(item => item !== menuCode);
    if (this.props.quickMenu.length <= index) {
      this.props.updateQuickMenu([...restMenu, menuCode]);
    } else if (index === 1) {
      this.props.updateQuickMenu([menuCode, ...restMenu]);
    } else {
      this.props.updateQuickMenu([...restMenu.slice(0, index - 1), menuCode, ...restMenu.slice(index - 1, restMenu.length)]);
    }
  };

  _getElementLayout = ele => {
    const eleStyle = window.getComputedStyle(ele);
    return { width: eleStyle.width, height: eleStyle.height };
  };

  _moveMenuItem = e => {
    const icon = e.currentTarget;
    const menuCode = icon.parentNode.getAttribute('data-menu-code');
    const { width, height } = this._getElementLayout(icon.parentNode);
    const elClone = icon.parentNode.cloneNode(true);
    elClone.style.width = width;
    elClone.style.height = height;
    elClone.className += ' move-item';
    icon.parentNode.parentNode.appendChild(elClone);
    elClone.style.top = e.clientY + 'px';
    elClone.style.left = e.clientX + 'px';
    const _menuMoveHandler = moveEvent => {
      elClone.style.top = moveEvent.clientY + 'px';
    };

    const _releaseMoveHandler = upEvent => {
      const menuHeight = upEvent.clientY - Navigator.LOGO_HEIGHT;
      const index = Math.ceil(menuHeight / Navigator.ITEM_HEIGHT);
      console.log('new index: ', index);
      icon.parentNode.parentNode.removeChild(elClone);
      this._sortedMenu(index, menuCode);
      window.removeEventListener('mousemove', _menuMoveHandler);
      window.removeEventListener('mouseup', _releaseMoveHandler);
    };

    window.addEventListener('mousemove', _menuMoveHandler);
    window.addEventListener('mouseup', _releaseMoveHandler);
  };

  _removeActive = ele => {
    if (ele) ele.className = 'menu-item';
  };

  _addActive = ele => {
    if (ele) ele.className = 'menu-item active';
  };

  _jumpTo = (event, item) => {
    const menuItem = event.currentTarget;
    if (this.activeMenuItem && this.activeMenuItem !== menuItem) {
      this._removeActive(this.activeMenuItem);
    }
    this._addActive(menuItem);
    // save active menu item
    this.activeMenuItem = menuItem;
    const bindParameters = this._getMenuBindParams(item);
    saveProcessMenuCode(bindParameters.menu);
    saveEnterMenuId(item.menuCode);
    this.props.push({ pathname: '/' + CONTAINER_PRE + this._getActionLink(item), state: { ...bindParameters } });
  };

  _getMenuItemClass = subMenu => {
    const menuCode = subMenu.menuCode;
    // console.log();
    const ret = 'menu-item';
    const code = getValueByKey(this.props.routing, null, 'locationBeforeTransitions', 'query', 'MX-MainMenuId');
    if (menuCode === code) {
      this.activeMenuItem = undefined;
      return ret + ' active';
    }
    if (this.activeMenuItem) {
      const activeMenuCode = this.activeMenuItem.getAttribute('data-menu-code');
      if (activeMenuCode === menuCode) {
        return ret + ' active';
      }
    }

    return ret;
  };

  // TODO refactor
  _getTipsWrapper = () => {
    let tipWrapper = document.querySelector('tips-wrapper');
    if (tipWrapper) {
      return { tipWrapper, detail: tipWrapper.childNodes[1] };
    }
    tipWrapper = document.createElement('div');
    const arrow = document.createElement('span');
    const detail = document.createElement('span');
    // this.tipEle
    tipWrapper.className = 'tips-wrapper';
    arrow.className = 'tips-arrow';
    detail.className = 'tips-detail';
    tipWrapper.appendChild(arrow);
    tipWrapper.appendChild(detail);
    document.getElementsByTagName('body')[0].append(tipWrapper);
    return { tipWrapper, detail };
  };

  // TODO refactor
  _showTips = (event, menuValue) => {
    if (!this.tipEle || !this.detail) {
      const { tipWrapper, detail } = this._getTipsWrapper();
      this.tipEle = tipWrapper;
      this.detail = detail;
    }
    this.detail.innerHTML = menuValue;
    const tag = event.currentTarget;
    /* eslint-disable */
    this.tipEle.style.top = (tag.offsetTop - tag.parentNode.parentNode.parentNode.parentNode.scrollTop + 35) + 'px';
    this.tipEle.style.width = '300px';
    this.tipEle.style.height = 'auto';
  };

  _hiddenTips = event => {
    if (this.tipEle) {
      this.tipEle.style.width = '0px';
      this.tipEle.style.height = '0px';
    }
  };

  _renderMenuItem = () => {
    return (
      <div className="menu-group">
        <div className="menu-group-detail">
          {this.state.menu && this.state.menu.map((subMenu, sIndex) => {
            return (
              <div
                key={subMenu.menuCode}
                className={this._getMenuItemClass(subMenu)}
                data-menu-code={subMenu.menuCode}
                onClick={e => this._jumpTo(e, subMenu)}
                onMouseOver={e => !this.props.status && this._showTips(e, subMenu.menuValue)}
                onMouseOut={e => !this.props.status && this._hiddenTips(e)}
              >
                {iconWrapper('icon-raxicongengduo63', null, null, { onMouseDown: this._moveMenuItem })}
                {svgWrapper(subMenu.menuIcon)}
                <span>{subMenu.menuValue}</span>
              </div>
            );
          })}
        </div>
      </div>
    );
  };

  _renderMenuCtrl = () => {
    if (this.state.isRender) {
      return (
        <div className={this.props.status ? 'sub-menu' : 'page-menu-up'}>
          <div className="page-menu">
            {this._renderMenuItem()}
          </div>
        </div>
      );
    }
    return null;
  };

  /* eslint-disable */
  render() {
    return (
      <div className={this.props.status ? "page-menu-bar" : "page-menu-bar-up"}>
        {this.state.isRender && this._renderTitle()}
        {this._renderMenuCtrl()}
      </div>
    );
  }
}

// eslint-disable-next-line arrow-body-style
const mapStateToProps = state => ({
  menu: state.menu || [],
  routing: state.routing,
  quickMenu: (state.global && state.global.quickMenu) || [],
});

export default connect(mapStateToProps)(Navigator);
