'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports['default'] = undefined;

var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = require('babel-runtime/helpers/createClass');

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = require('babel-runtime/helpers/inherits');

var _inherits3 = _interopRequireDefault(_inherits2);

var _debounce2 = require('lodash/debounce');

var _debounce3 = _interopRequireDefault(_debounce2);

var _max2 = require('lodash/max');

var _max3 = _interopRequireDefault(_max2);

var _map2 = require('lodash/map');

var _map3 = _interopRequireDefault(_map2);

var _filter2 = require('lodash/filter');

var _filter3 = _interopRequireDefault(_filter2);

var _dec, _class;

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _mobxReact = require('mobx-react');

var _reactRouterDom = require('react-router-dom');

var _classnames = require('classnames');

var _classnames2 = _interopRequireDefault(_classnames);

require('./style');

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

var TAB_PLACEHOLDER_NAME = '临时标签页';
var MAX_WIDTH = 140;
var HIDDEN_CLOSE_WIDTH = 80;
var MIN_WIDTH = 20;

var MenuBar = (_dec = (0, _mobxReact.inject)('MenuStore', 'AppState'), (0, _reactRouterDom.withRouter)(_class = _dec(_class = (0, _mobxReact.observer)(_class = function (_Component) {
  (0, _inherits3['default'])(MenuBar, _Component);

  function MenuBar() {
    var _ref;

    var _temp, _this, _ret;

    (0, _classCallCheck3['default'])(this, MenuBar);

    for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    return _ret = (_temp = (_this = (0, _possibleConstructorReturn3['default'])(this, (_ref = MenuBar.__proto__ || Object.getPrototypeOf(MenuBar)).call.apply(_ref, [this].concat(args))), _this), _this.handleWindowResize = (0, _debounce3['default'])(function () {
      _this.forceUpdate();
    }, 500), _temp), (0, _possibleConstructorReturn3['default'])(_this, _ret);
  }

  (0, _createClass3['default'])(MenuBar, [{
    key: 'componentWillMount',
    value: function componentWillMount() {
      this.setIsTabMode();
      this.loadTabbar(this.props);
    }
  }, {
    key: 'componentWillReceiveProps',
    value: function componentWillReceiveProps(nextProps) {
      this.loadTabbar(nextProps);
    }
  }, {
    key: 'componentDidMount',
    value: function componentDidMount() {
      window.addEventListener('resize', this.handleWindowResize);
    }
  }, {
    key: 'componentWillUnmount',
    value: function componentWillUnmount() {
      window.removeEventListener('resize', this.handleWindowResize);
    }
  }, {
    key: 'loadTabbar',
    value: function loadTabbar(props) {
      var _this2 = this;

      var location = props.location,
          MenuStore = props.MenuStore,
          AppState = props.AppState;
      var pathname = location.pathname,
          search = location.search,
          state = location.state;
      var menus = MenuStore.menus,
          activeMenu = MenuStore.activeMenu;
      // eslint-disable-next-line no-nested-ternary

      var type = pathname.startsWith('/iframe/') ? 'HTML' : pathname.startsWith('/hap-modeling/metadata/') ? 'PAGE' : 'REACT';
      var key = {
        HTML: pathname.slice(8),
        PAGE: pathname.slice(19),
        REACT: pathname.slice(1)
      }[type];

      MenuStore.loadMenus().then(function (me) {
        if (pathname === '/') return;
        MenuStore.getPathById(key, me, type, function (temppath, targetNode) {
          _this2.insertTabs(key, type, targetNode);
        }, function () {
          var construct = {
            children: null,
            expand: false,
            functionCode: key,
            icon: null,
            id: -1,
            ischecked: null,
            score: -1,
            shortcutId: null,
            text: state && state.title || {
              SYS_PREFERENCE: '用户信息',
              'hap-core/sys/preferences': '首选项'
            }[key] || _this2.getNextTabName(),
            url: {
              SYS_PREFERENCE: 'sys/um/sys_user_info.html',
              'hap-core/sys/preferences': 'hap-core/sys/preferences'
            }[key] || key,
            symbol: type
          };
          _this2.insertTabs(key, type, construct);
        });
      });
    }
  }, {
    key: 'setIsTabMode',
    value: function setIsTabMode() {
      var AppState = this.props.AppState;

      AppState.loadTabMode();
    }
  }, {
    key: 'getNextTabName',
    value: function getNextTabName() {
      var MenuStore = this.props.MenuStore;

      var tabs = MenuStore.getTabs;
      var tabsNameArr = (0, _filter3['default'])((0, _map3['default'])(tabs, 'text'), function (v) {
        return v.startsWith(TAB_PLACEHOLDER_NAME);
      });
      if (!tabsNameArr.length) return TAB_PLACEHOLDER_NAME + '1';

      var nums = tabsNameArr.map(function (v) {
        return v.slice(v.indexOf(TAB_PLACEHOLDER_NAME) + TAB_PLACEHOLDER_NAME.length);
      });
      var nextNum = (0, _max3['default'])(nums) * 1 + 1;
      return '' + TAB_PLACEHOLDER_NAME + nextNum;
    }
  }, {
    key: 'insertTabs',
    value: function insertTabs(key, type, tab) {
      var MenuStore = this.props.MenuStore;

      var tabs = MenuStore.getTabs;
      if (!tabs.find(function (v) {
        return v && v[type !== 'HTML' ? 'url' : 'functionCode'] === key;
      })) {
        tabs.push(tab);
        MenuStore.setTabs(tabs);
      }
    }
  }, {
    key: 'handleMenuClick',
    value: function handleMenuClick(tab) {
      this.handleLink(tab);
    }
  }, {
    key: 'handleLink',
    value: function handleLink(tab, isFromFresh) {
      var _props = this.props,
          MenuStore = _props.MenuStore,
          isTabMode = _props.AppState.isTabMode;
      var selectedKeys = MenuStore.selectedKeys;

      var LINK_MAP = {
        REACT: '/' + tab.url,
        HTML: '/iframe/' + tab.functionCode,
        PAGE: '/hap-modeling/metadata/' + tab.url
      };

      // if (selectedKeys.length && selectedKeys[0] === tab.functionCode && isTabMode && !isFromFresh) return;

      var link = LINK_MAP[tab.symbol] || '/';
      this.props.history.push({
        pathname: link
      });
      if (link === '/') {
        MenuStore.setActiveMenu({});
      }
    }
  }, {
    key: 'handleCloseTab',
    value: function handleCloseTab(tab, event) {
      var MenuStore = this.props.MenuStore;
      var selectedKeys = MenuStore.selectedKeys;

      if (event) event.stopPropagation();
      if (selectedKeys.length && selectedKeys[0] === tab.functionCode) {
        var desTab = MenuStore.getNextTab(tab);
        var desUrl = void 0;
        if (desTab.functionCode !== 'HOME_PAGE') {
          var LINK_MAP = {
            REACT: '/' + desTab.url,
            HTML: '/iframe/' + desTab.functionCode,
            PAGE: '/hap-modeling/metadata/' + desTab.url
          };
          desUrl = LINK_MAP[desTab.symbol];
        } else {
          desUrl = '/';
          MenuStore.setActiveMenu({});
        }
        this.props.history.push(desUrl);
      }
      MenuStore.closeTabAndClearCacheByCacheKey(tab);
    }
  }, {
    key: 'handleCloseCmpContainTab',
    value: function handleCloseCmpContainTab(tab, event) {
      var MenuStore = this.props.MenuStore;

      MenuStore.closeTabAndClearCacheByCacheKey(tab, true);
    }
  }, {
    key: 'handleClickTabMenu',
    value: function handleClickTabMenu(tab, _ref2) {
      var _this3 = this;

      var key = _ref2.key;
      var _props2 = this.props,
          MenuStore = _props2.MenuStore,
          history = _props2.history;
      var tabs = MenuStore.tabs;

      var urlKey = history.location.pathname;
      var index = tabs.findIndex(function (v) {
        return v.functionCode === tab.functionCode;
      });
      switch (key) {
        case 'close_self':
          this.handleCloseTab(tab);
          break;
        case 'close_other':
          this.handleLink(tab);
          tabs.filter(function (v) {
            return v.functionCode !== tab.functionCode && v.functionCode !== 'HOME_PAGE';
          }).forEach(function (t) {
            _this3.handleCloseTab(t);
          });
          break;
        case 'close_all':
          this.props.history.push('/');
          tabs.filter(function (v) {
            return v.functionCode !== 'HOME_PAGE';
          }).forEach(function (t) {
            MenuStore.closeTabAndClearCacheByCacheKey(t);
          });
          break;
        case 'close_left':
          this.handleLink(tab);
          if (index !== undefined) {
            tabs.filter(function (v, i) {
              return i < index && v.functionCode !== 'HOME_PAGE';
            }).forEach(function (t) {
              _this3.handleCloseTab(t);
            });
          }
          break;
        case 'close_right':
          this.handleLink(tab);
          if (index !== undefined) {
            tabs.filter(function (v, i) {
              return i > index && v.functionCode !== 'HOME_PAGE';
            }).forEach(function (t) {
              _this3.handleCloseTab(t);
            });
          }
          break;
        case 'refresh':
          if (tab && tab.symbol === 'REACT') {
            MenuStore.setContentKey(urlKey, Date.now());
            // this.handleCloseCmpContainTab(tab);
            // this.handleLink(tab, true);
            // this.handleCloseCmpContainTab(tab);
            // this.props.history.push({
            //   pathname: '/',
            // });
            // setTimeout(() => this.handleLink(tab, true), 0);
            // this.handleLink(tab, true);
          } else {
            this.handleCloseTab(tab);
            this.handleLink(tab, true);
          }
          // MenuStore.setContentKey(urlKey, Date.now());
          break;
        default:
          break;
      }
    }
  }, {
    key: 'render',
    value: function render() {
      var _props3 = this.props,
          pathname = _props3.location.pathname,
          MenuStore = _props3.MenuStore,
          isTabMode = _props3.AppState.isTabMode;
      var tabs = MenuStore.tabs,
          activeMenu = MenuStore.activeMenu,
          collapsed = MenuStore.collapsed;


      var isHome = pathname === '/';
      var SCREEN_WIDTH = document.body.clientWidth;
      var MAX_NUMBER = Math.floor((document.body.clientWidth - (collapsed ? 100 : 300)) / MAX_WIDTH);
      var num = tabs.length;
      var eachTabWidth = num ? (document.body.clientWidth - (collapsed ? 100 : 300)) / num : MAX_WIDTH;
      var width = void 0;
      if (num <= MAX_NUMBER) {
        width = MAX_WIDTH;
      } else if (eachTabWidth < MIN_WIDTH) {
        width = MIN_WIDTH;
      } else {
        width = eachTabWidth;
      }

      var placehoderUrl = {
        HTML: '/iframe/',
        REACT: '/',
        PAGE: '/hap-modeling/metadata/'
      };
      // const activeIndex = tabs.findIndex(tab => pathname === `/${tab.url}` || pathname === `/iframe/${tab.functionCode}`);
      var activeIndex = tabs.findIndex(function (tab) {
        return pathname === (tab.symbol === 'HTML' ? '' + placehoderUrl[tab.symbol] + tab.functionCode : '' + placehoderUrl[tab.symbol] + tab.url);
      });

      return null;
    }
  }]);
  return MenuBar;
}(_react.Component)) || _class) || _class) || _class);
exports['default'] = MenuBar;