'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

var _class, _temp, _initialiseProps; /**
                                      * Created by baoyinghai on 2/25/17.
                                      */


var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _reactRedux = require('react-redux');

var _qs = require('qs');

var _qs2 = _interopRequireDefault(_qs);

var _reactRouter = require('react-router');

var _routes = require('../../framework/entrance/routes');

var _EmptyUtils = require('../../framework/utils/EmptyUtils');

var _MenuHelper = require('../../framework/utils/MenuHelper');

var _MapUtils = require('../../framework/utils/MapUtils');

var _config = require('../../config');

var _config2 = _interopRequireDefault(_config);

var _ProcessHelper = require('../../framework/utils/ProcessHelper');

var _IconHelper = require('../../framework/utils/IconHelper');

var _SessionStorage = require('../../framework/service/SessionStorage');

var _windowUtils = require('../../framework/utils/windowUtils');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var Navigator = (_temp = _class = function (_React$Component) {
  _inherits(Navigator, _React$Component);

  function Navigator(props) {
    _classCallCheck(this, Navigator);

    var _this = _possibleConstructorReturn(this, (Navigator.__proto__ || Object.getPrototypeOf(Navigator)).call(this, props));

    _initialiseProps.call(_this);

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

  _createClass(Navigator, [{
    key: 'componentWillReceiveProps',
    value: function componentWillReceiveProps(nextProps) {
      var _this2 = this;

      if (this.props.status !== nextProps.status) {
        this.setState({ isRender: false });
        setTimeout(function () {
          return _this2.setState({ isRender: true });
        }, 300);
      }
      this.setState({
        menu: this._sortedByArray((0, _MenuHelper.searchAllMenusByFunc)(this.props.menu, function (m) {
          return nextProps.quickMenu.indexOf(m.menuCode) !== -1;
        }), nextProps.quickMenu)
      });
    }
  }, {
    key: 'componentDidMount',
    value: function componentDidMount() {
      var backBoard = document.querySelector('.body-wrapper.wrapper.remove-block-space');
      if (backBoard) {
        backBoard.style.backgroundColor = '#282d32';
      }
    }

    // mutile


    // mutile


    // TODO refactor


    // TODO refactor

  }, {
    key: 'render',


    /* eslint-disable */
    value: function render() {
      return _react2.default.createElement(
        'div',
        { className: this.props.status ? "page-menu-bar" : "page-menu-bar-up" },
        this.state.isRender && this._renderTitle(),
        this._renderMenuCtrl()
      );
    }
  }]);

  return Navigator;
}(_react2.default.Component), _class.LOGO_HEIGHT = 54, _class.ITEM_HEIGHT = 42, _initialiseProps = function _initialiseProps() {
  var _this3 = this;

  this._getActionLink = function (item) {
    return item.domainLink || item.actionLink;
  };

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

  this._sortedByArray = function () {
    var menu = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
    var codeAry = arguments[1];

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

  this._getMenuBindParams = function (menuItem) {
    var ret = {};
    menuItem.bindParameters && menuItem.bindParameters.forEach(function (item) {
      ret[item.name] = item.value;
    });
    if ((0, _ProcessHelper.isApply)(_this3._getActionLink(menuItem))) {
      ret.menu = 'BPMApply.QueryToDo';
    } else if ((0, _ProcessHelper.isReview)(_this3._getActionLink(menuItem))) {
      ret.menu = 'BPMReview.QueryToDo';
    }
    return ret;
  };

  this._updateEnterMenuId = function (menuCode, processId) {
    _this3.props.updateEnterMenuId([menuCode, processId]);
  };

  this._renderTitle = function () {
    if (_this3.props.status) {
      return _react2.default.createElement(
        'div',
        { className: 'menu-logo' },
        _react2.default.createElement('div', { className: 'img' }),
        _react2.default.createElement(
          'span',
          null,
          '\u878D\u8D44\u79DF\u8D41'
        ),
        (0, _IconHelper.iconWrapper)('icon-shuangjiantou', null, null, { onClick: _this3.props.switchMenu })
      );
    }
    return _react2.default.createElement(
      'div',
      { className: 'menu-logo' },
      (0, _IconHelper.iconWrapper)('icon-menu', null, null, { onClick: _this3.props.switchMenu })
    );
  };

  this._sortedMenu = function (index, menuCode) {
    var restMenu = _this3.props.quickMenu.filter(function (item) {
      return item !== menuCode;
    });
    if (_this3.props.quickMenu.length <= index) {
      _this3.props.updateQuickMenu([].concat(_toConsumableArray(restMenu), [menuCode]));
    } else if (index === 1) {
      _this3.props.updateQuickMenu([menuCode].concat(_toConsumableArray(restMenu)));
    } else {
      _this3.props.updateQuickMenu([].concat(_toConsumableArray(restMenu.slice(0, index - 1)), [menuCode], _toConsumableArray(restMenu.slice(index - 1, restMenu.length))));
    }
  };

  this._getElementLayout = function (ele) {
    var eleStyle = window.getComputedStyle(ele);
    return { width: eleStyle.width, height: eleStyle.height };
  };

  this._moveMenuItem = function (e) {
    var icon = e.currentTarget;
    var menuCode = icon.parentNode.getAttribute('data-menu-code');

    var _getElementLayout = _this3._getElementLayout(icon.parentNode),
        width = _getElementLayout.width,
        height = _getElementLayout.height;

    var 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';
    var _menuMoveHandler = function _menuMoveHandler(moveEvent) {
      elClone.style.top = moveEvent.clientY + 'px';
    };

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

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

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

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

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

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

    return ret;
  };

  this._getTipsWrapper = function () {
    var tipWrapper = document.querySelector('tips-wrapper');
    if (tipWrapper) {
      return { tipWrapper: tipWrapper, detail: tipWrapper.childNodes[1] };
    }
    tipWrapper = document.createElement('div');
    var arrow = document.createElement('span');
    var 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: tipWrapper, detail: detail };
  };

  this._showTips = function (event, menuValue) {
    if (!_this3.tipEle || !_this3.detail) {
      var _getTipsWrapper = _this3._getTipsWrapper(),
          tipWrapper = _getTipsWrapper.tipWrapper,
          detail = _getTipsWrapper.detail;

      _this3.tipEle = tipWrapper;
      _this3.detail = detail;
    }
    _this3.detail.innerHTML = menuValue;
    var tag = event.currentTarget;
    /* eslint-disable */
    _this3.tipEle.style.top = tag.offsetTop - tag.parentNode.parentNode.parentNode.parentNode.scrollTop + 35 + 'px';
    _this3.tipEle.style.width = '300px';
    _this3.tipEle.style.height = 'auto';
  };

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

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

  this._renderMenuCtrl = function () {
    if (_this3.state.isRender) {
      return _react2.default.createElement(
        'div',
        { className: _this3.props.status ? 'sub-menu' : 'page-menu-up' },
        _react2.default.createElement(
          'div',
          { className: 'page-menu' },
          _this3._renderMenuItem()
        )
      );
    }
    return null;
  };
}, _temp);

// eslint-disable-next-line arrow-body-style

var mapStateToProps = function mapStateToProps(state) {
  return {
    menu: state.menu || [],
    routing: state.routing,
    quickMenu: state.global && state.global.quickMenu || []
  };
};

exports.default = (0, _reactRedux.connect)(mapStateToProps)(Navigator);