'use strict';

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

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 _desc, _value, _class, _class2, _temp; /**
                                            * Created by baoyinghai on 11/27/16.
                                            */


var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _coreDecorators = require('core-decorators');

var _qs = require('qs');

var _qs2 = _interopRequireDefault(_qs);

var _sideMenu = require('./sideMenu');

var _sideMenu2 = _interopRequireDefault(_sideMenu);

var _Compose = require('../../utils/Compose');

var _Compose2 = _interopRequireDefault(_Compose);

var _AsyncDecorator = require('../../pageContainer/AsyncDecorator');

var _AsyncDecorator2 = _interopRequireDefault(_AsyncDecorator);

var _InitDecorator = require('../../pageContainer/InitDecorator');

var _InitDecorator2 = _interopRequireDefault(_InitDecorator);

var _exclusive = require('../../pageContainer/exclusive');

var _exclusive2 = _interopRequireDefault(_exclusive);

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

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

var _ModalWrapper = require('../../pageContainer/ModalWrapper');

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

var _dictActions = require('../../constant/dictActions');

var _dictCodes = require('../../constant/dictCodes');

var _components = require('../../../components');

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

var _StringUtils = require('../../utils/StringUtils');

var _ScrollHelper = require('../../utils/ScrollHelper');

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

var _config2 = _interopRequireDefault(_config);

var _anchor = require('../../../components/anchor');

var _anchor2 = _interopRequireDefault(_anchor);

var _titleBar = require('./titleBar');

var _titleBar2 = _interopRequireDefault(_titleBar);

var _InfoException = require('../exception/InfoException');

var _InfoException2 = _interopRequireDefault(_InfoException);

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

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

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

function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) {
  var desc = {};
  Object['ke' + 'ys'](descriptor).forEach(function (key) {
    desc[key] = descriptor[key];
  });
  desc.enumerable = !!desc.enumerable;
  desc.configurable = !!desc.configurable;

  if ('value' in desc || desc.initializer) {
    desc.writable = true;
  }

  desc = decorators.slice().reverse().reduce(function (desc, decorator) {
    return decorator(target, property, desc) || desc;
  }, desc);

  if (context && desc.initializer !== void 0) {
    desc.value = desc.initializer ? desc.initializer.call(context) : void 0;
    desc.initializer = undefined;
  }

  if (desc.initializer === void 0) {
    Object['define' + 'Property'](target, property, desc);
    desc = null;
  }

  return desc;
}

// const IFrame = require('react-iframe');

// const ButtonGroup = Button.Group;


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

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

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

    _this._getIcon = function (item) {
      return item && (item.buttonIcon || item.menuIcon) || _config2.default.DefaultMenuIcon;
    };

    _this._onBodyScroll = function (e) {
      var sideMenu = document.querySelector('.info-sidebar-sticky-wrapper');
      var mainContent = document.querySelector('.main-sticky-wrapper');
      /* eslint-disable */
      if (window.scrollY >= 54) {
        sideMenu.classList.add('sticky');
        mainContent.classList.add('sticky-main-content');
        !_this.state.showProcessBtn && _this.setState({ showProcessBtn: true });
      } else {
        sideMenu.classList.remove('sticky');
        mainContent.classList.remove('sticky-main-content');
        _this.state.showProcessBtn && _this.setState({ showProcessBtn: false });
      }
    };

    _this.modifyWindowHeight = function () {
      _this.setState({ innerHeight: window.innerHeight });
    };

    _this._modifyStyle = function (item) {
      if (item) {
        var _this$getLinkAndType = _this.getLinkAndType(item),
            domainType = _this$getLinkAndType.domainType;

        if (domainType === _dictActions.PAGE_TYPE_LIST) {
          return '100%';
        }
      }
      return "";
    };

    _this._getTitleDesc = function () {
      var _this$props$dataSourc = _this.props.dataSource,
          dataSource = _this$props$dataSourc === undefined ? {} : _this$props$dataSourc;
      var _dataSource$pageMenu = dataSource.pageMenu,
          pageMenu = _dataSource$pageMenu === undefined ? {} : _dataSource$pageMenu;

      var name = pageMenu.name;
      var headerDesc = pageMenu.headerDesc;
      var headerId = pageMenu.headerId;
      if (!headerDesc || headerDesc === 'null') return name;
      if (!headerId || headerId === 'null') return name + '-' + (0, _StringUtils.convertTemplate)(headerDesc, _this.props.query);
      return (0, _StringUtils.convertTemplate)(headerDesc, _this.props.query) + ' ' + (0, _StringUtils.convertTemplate)(headerId, _this.props.query);
    };

    _this._sideMenuChange = function (status) {
      _this.setState({ sideMenuStatus: status });
    };

    if (_this.props.dataSource && _this.props.dataSource.pageMenu && _this.props.dataSource.pageMenu.menus) {
      _this.tag = (0, _MenuHelper.getMenuItemByFunc)(function (m) {
        return m.isSelected === true;
      }, _this.props.dataSource.pageMenu.menus) || (0, _MenuHelper.getAllLeafs)(_this.props.dataSource.pageMenu.menus)[0]; // 没有默认选中的叶子 就选第一个
    }
    var buttons = _this.props.dataSource && _this.props.dataSource.buttons || [];
    var _this$props = _this.props,
        prefixCls = _this$props.prefixCls,
        query = _this$props.query,
        inject = _this$props.inject;

    var buttonClass = prefixCls + '-button';
    var menuCode = _this.props.query.processMenuId;
    var readonly = _this.props.query.readonly === 'true' || _this.props.query.readonly === true || _this.props.dataSource.readOnly || _this.props.query.displayType === 'VIEW';
    var globalBtns = readonly || ((0, _ProcessHelper.isApply)(_this.props.domainLink) || (0, _ProcessHelper.isReview)(_this.props.domainLink)) && menuCode && menuCode !== 'BPMApply.QueryToDo' && menuCode !== 'BPMReview.QueryToDo' && menuCode !== 'BPMApply.QueryReturned' ? [] : buttons.map(function (item) {
      return _react2.default.createElement(_components.ExtendButton, _extends({
        type: 'link',
        inline: false,
        buttonProps: { type: 'ghost' }
      }, item, {
        disabled: false,
        key: item.buttonDescription,
        query: query,
        className: buttonClass,
        inject: inject,
        relatedRows: _dictCodes.BUTTON_RELATEDDATA.NONE,
        onRefresh: function onRefresh() {
          return console.log('!!!!!!!-----onRefresh');
        }
      }));
    });
    _this.state = {
      main: null,
      // current: this.tag,
      topButtons: [],
      globalBtns: globalBtns,
      header: '',
      summarys: [],
      showSummary: true,
      anchor: [],
      sideMenuStatus: true, // side menu status
      showProcessBtn: false,
      innerHeight: window.innerHeight,
      readonly: readonly
    };
    return _this;
  }

  _createClass(InfoLayout, [{
    key: 'getGlobalButtons',
    value: function getGlobalButtons() {
      return this.state.globalBtns;
    }
  }, {
    key: 'createTopButtons',
    value: function createTopButtons(data) {
      this.setState({ topButtons: data });
    }
  }, {
    key: 'clearState',
    value: function clearState(cb) {
      this.setState({ topButtons: [], summarys: [] }, cb);
    }
  }, {
    key: '_renderSummaryHandler',
    value: function _renderSummaryHandler(summarys) {
      this.setState({ summarys: summarys });
    }
  }, {
    key: 'createMain',
    value: function createMain(data, domainType, domainLink, displayType, params, updateMain) {
      var TempPage = (0, _Compose2.default)(_AsyncDecorator2.default, _InitDecorator2.default)();

      var _props = this.props,
          query = _props.query,
          rest = _objectWithoutProperties(_props, ['query']);

      return _react2.default.createElement(TempPage, _extends({}, rest, {
        query: _extends({}, params, { s: '' }) // remove other parameters
        , displayType: displayType,
        createTopButtons: domainType === _dictActions.PAGE_TYPE_DETAIL ? this.createTopButtons : null,
        dataSource: data,
        domainType: domainType,
        domainLink: domainLink,
        updateMain: updateMain,
        renderSummaryHandler: this._renderSummaryHandler,
        isInfo: true,
        readonly: this.state.readonly,
        formInfo: true,
        refreshCallback: this.refreshCallback
      }));
    }
  }, {
    key: 'refreshCallback',
    value: function refreshCallback() {
      var _getLinkAndType = this.getLinkAndType(this.tag),
          domainLink = _getLinkAndType.domainLink,
          domainType = _getLinkAndType.domainType;

      this.updateMain(domainLink, domainType, this.tag);
    }
  }, {
    key: 'getLinkAndType',
    value: function getLinkAndType(e) {
      return { domainLink: (0, _StringUtils.trimStart)(e.domainLink || e.actionLink, '/'), domainType: e.domainType || e.templateType };
    }
  }, {
    key: 'menuClick',
    value: function menuClick(m) {
      this.tag = m;

      var _getLinkAndType2 = this.getLinkAndType(m),
          domainLink = _getLinkAndType2.domainLink,
          domainType = _getLinkAndType2.domainType;

      this.updateMain(domainLink, domainType, m);
    }

    // extraParams select params

  }, {
    key: 'createReqParam',
    value: function createReqParam(menuItem) {
      var query = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
      var extraParams = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};

      // TODO: some all
      var params = {};
      if (this.props && this.props.params) {
        params = _extends({}, params, this.props.params, query);
      }
      params = _extends({}, params, (0, _MapUtils.getValueByKey)(this.props, {}, 'query'), extraParams);
      // TODO: 只传递bindParameters数据
      var ret = {};
      menuItem.bindParameters && menuItem.bindParameters.forEach(function (item) {
        ret[item.name] = (0, _EmptyUtils.filterEmptyValue)(item.value, params[item.name]);
      });
      return ret;
    }

    // TODO: refactor  不需要renderMain

  }, {
    key: 'updateMain',
    value: function updateMain(domainLink, dt, mi) {
      var _this2 = this;

      var extraParams = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};

      var domainType = dt;
      var menuItem = mi;
      if (!menuItem) {
        menuItem = this.state.current;
        domainType = this.state.current.domainType;
      }
      var menuCode = menuItem.menuCode;
      // 下部菜单
      // const patch = searchBeforeAndAfter(menuCode, this.props.dataSource.pageMenu.menus);
      // patch.current = menuItem;
      var params = this.createReqParam(menuItem, this.props && this.props.query, extraParams);
      this.props.exec(function () {
        return new Promise(function (resolve, reject) {
          var tagLink = (0, _StringUtils.trimStart)((0, _StringUtils.convertTemplate)(domainLink, params, menuItem.actionLinkMappings), '/');
          if (_exclusive2.default.some(function (f) {
            return f(tagLink);
          })) {
            resolve({});
          } else {
            _this2.props.fetch(tagLink, params).then(resolve);
          }
        }).then(function (data) {
          if (domainType === _dictActions.PAGE_TYPE_DETAIL || domainType === _dictActions.PAGE_TYPE_DETAIL) {
            (0, _ScrollHelper.scrollAble)();
          } else {
            (0, _ScrollHelper.scrollDisable)();
          }

          _this2.clearState(function () {
            return _this2.setState({
              header: menuItem.menuValue,
              main: _this2.createMain(data, extraParams.domainType || domainType, domainLink, extraParams.displayType || menuItem.displayType, params, _this2.updateMain)
            }, function () {
              return _this2.setState({ anchor: (0, _anchor.archorQuery)() });
            });
          });
        }).catch(function (err) {
          console.log('**  error  **', err);
          _this2.setState({
            main: _react2.default.createElement(_InfoException2.default, { err: err })
          });
          throw err;
        });
      });
    }
  }, {
    key: 'componentDidMount',


    /* eslint-disable */
    value: function componentDidMount() {
      document.addEventListener('scroll', this._onBodyScroll);
      window.addEventListener('resize', this.modifyWindowHeight);
    }
  }, {
    key: 'componentWillUnmount',
    value: function componentWillUnmount() {
      document.removeEventListener('scroll', this._onBodyScroll);
      window.removeEventListener('resize', this.modifyWindowHeight);
    }
  }, {
    key: 'componentWillMount',
    value: function componentWillMount() {
      if (this.tag) {
        var _getLinkAndType3 = this.getLinkAndType(this.tag),
            domainLink = _getLinkAndType3.domainLink,
            domainType = _getLinkAndType3.domainType;

        this.updateMain(domainLink, domainType, this.tag);
      }
    }

    /* eslint-disable */


    // TODO: refactor

  }, {
    key: 'render',
    value: function render() {
      var _this3 = this;

      var headerStyle = !this.state.showSummary ? { height: '0px', overflow: 'hidden' } : {};
      var lockedLayoutStyle = {};
      var mainGrid = {};
      if ((this.tag.domainType || this.tag.templateType) === _dictActions.PAGE_TYPE_LIST) {
        lockedLayoutStyle.display = 'none';
        mainGrid.height = 'calc(100% - 52px)';
      } else {
        lockedLayoutStyle.borderBottom = '2px solid #00aaef';
      }

      var _props$dataSource = this.props.dataSource,
          pageMenu = _props$dataSource.pageMenu,
          infoCompletenessBean = _props$dataSource.infoCompletenessBean;

      var isNewPage = this.props.query && this.props.query.s === '1';
      /* eslint-disable */
      return _react2.default.createElement(
        'div',
        { style: { height: this._modifyStyle(this.tag) }, className: 'info-wrapper' },
        isNewPage && _react2.default.createElement(
          _titleBar2.default,
          { getTitleDesc: this._getTitleDesc, infoCompleteness: infoCompletenessBean && infoCompletenessBean.totalValue },
          this.getGlobalButtons()
        ),
        _react2.default.createElement(
          'div',
          { className: 'info-container margin-center-container', style: { margin: isNewPage ? '0 60px' : 0 } },
          _react2.default.createElement(
            _sideMenu.SideMenuContainer,
            { changeHander: this._sideMenuChange },
            _react2.default.createElement(_sideMenu2.default, {
              infoCompleteness: infoCompletenessBean && infoCompletenessBean.dtoValues,
              menu: pageMenu.menus,
              menuClick: this.menuClick,
              selectedItem: this.tag
            })
          ),
          _react2.default.createElement(
            'div',
            { className: 'main-grid ' + (this.state.sideMenuStatus ? '' : ' side-menu-close'), style: { minHeight: this.state.innerHeight - 54 + 'px' } },
            _react2.default.createElement(
              'div',
              { className: 'locked-layout', style: lockedLayoutStyle },
              _react2.default.createElement(
                'div',
                { className: ' main-sticky-wrapper' },
                _react2.default.createElement(
                  'div',
                  { className: 'info-header' },
                  _react2.default.createElement(
                    'div',
                    { className: 'detail-top' },
                    _react2.default.createElement(
                      'div',
                      { className: 'header-spread' },
                      _react2.default.createElement(
                        'div',
                        { className: 'biz-info' },
                        _react2.default.createElement(
                          'div',
                          { className: 'header-primary' },
                          _react2.default.createElement(
                            'div',
                            { className: 'header-col' },
                            _react2.default.createElement(
                              'h1',
                              { className: 'header-title' },
                              _react2.default.createElement('i', { className: 'iconfont ' + this._getIcon(this.tag) + ' menu-icon-alibb header-ico' }),
                              _react2.default.createElement(
                                'span',
                                { className: 'header-desc' },
                                this.state.header
                              )
                            )
                          ),
                          _react2.default.createElement(
                            'div',
                            { className: 'header-col' },
                            _react2.default.createElement(
                              'a',
                              { className: 'business-info' },
                              _react2.default.createElement('i', null),
                              '\u5DE5\u5546\u4FE1\u606F'
                            )
                          ),
                          _react2.default.createElement(
                            'div',
                            { className: 'header-col' },
                            _react2.default.createElement(
                              'a',
                              { className: 'group-talk' },
                              _react2.default.createElement('i', null),
                              '\u8BA8\u8BBA\u4E00\u4E0B'
                            )
                          )
                        )
                      ),
                      _react2.default.createElement(
                        'div',
                        { className: 'header-menu' },
                        this.state.topButtons && this.state.topButtons.length > 0 ? _react2.default.createElement(
                          'div',
                          { className: 'button-bar' },
                          _react2.default.createElement(
                            'ul',
                            { className: 'button-bar-list' },
                            this.state.topButtons && this.state.topButtons.map(function (item, index) {
                              return _react2.default.createElement(
                                'li',
                                { key: index, style: !index && { borderTopLeftRadius: '4px', borderBottomLeftRadius: '4px' } },
                                item
                              );
                            })
                          )
                        ) : null
                      )
                    ),
                    this.state.summarys && this.state.summarys.length > 0 && _react2.default.createElement(
                      'div',
                      { className: 'header-detail', style: headerStyle },
                      _react2.default.createElement(
                        'ul',
                        { className: 'summary-field' },
                        this.state.summarys.map(function (summary) {
                          return _react2.default.createElement(
                            'li',
                            { className: 'summary-col', style: { width: 100 / _this3.state.summarys.length + '%' } },
                            _react2.default.createElement(
                              'div',
                              { className: 'summary-col-item' },
                              _react2.default.createElement(
                                'div',
                                { className: 'summary-col-label' },
                                _react2.default.createElement(
                                  'span',
                                  { className: 'ellipsis' },
                                  summary.label
                                )
                              ),
                              _react2.default.createElement(
                                'div',
                                { className: 'summary-col-value' },
                                _react2.default.createElement(
                                  'span',
                                  { className: 'ellipsis' },
                                  summary.value
                                )
                              )
                            )
                          );
                        })
                      )
                    )
                  )
                )
              )
            ),
            _react2.default.createElement(
              'div',
              { className: 'main_grid_middlle', style: mainGrid },
              _react2.default.createElement(
                'div',
                { className: 'info-wrapper-margin' },
                _react2.default.createElement(
                  'div',
                  { style: { height: '100%', overflowY: '' } },
                  this.state.main
                )
              )
            ),
            _react2.default.createElement(
              _anchor2.default,
              { links: this.state.anchor },
              this.state.showProcessBtn && this.getGlobalButtons()
            ),
            _react2.default.createElement(_components.BackTop, null)
          )
        )
      );
    }
  }]);

  return InfoLayout;
}(_react2.default.Component), _class2.propTypes = {
  dataSource: _react2.default.PropTypes.object
}, _temp), (_applyDecoratedDescriptor(_class.prototype, 'getGlobalButtons', [_coreDecorators.autobind], Object.getOwnPropertyDescriptor(_class.prototype, 'getGlobalButtons'), _class.prototype), _applyDecoratedDescriptor(_class.prototype, 'createTopButtons', [_coreDecorators.autobind], Object.getOwnPropertyDescriptor(_class.prototype, 'createTopButtons'), _class.prototype), _applyDecoratedDescriptor(_class.prototype, 'clearState', [_coreDecorators.autobind], Object.getOwnPropertyDescriptor(_class.prototype, 'clearState'), _class.prototype), _applyDecoratedDescriptor(_class.prototype, '_renderSummaryHandler', [_coreDecorators.autobind], Object.getOwnPropertyDescriptor(_class.prototype, '_renderSummaryHandler'), _class.prototype), _applyDecoratedDescriptor(_class.prototype, 'createMain', [_coreDecorators.autobind], Object.getOwnPropertyDescriptor(_class.prototype, 'createMain'), _class.prototype), _applyDecoratedDescriptor(_class.prototype, 'refreshCallback', [_coreDecorators.autobind], Object.getOwnPropertyDescriptor(_class.prototype, 'refreshCallback'), _class.prototype), _applyDecoratedDescriptor(_class.prototype, 'getLinkAndType', [_coreDecorators.autobind], Object.getOwnPropertyDescriptor(_class.prototype, 'getLinkAndType'), _class.prototype), _applyDecoratedDescriptor(_class.prototype, 'menuClick', [_coreDecorators.autobind], Object.getOwnPropertyDescriptor(_class.prototype, 'menuClick'), _class.prototype), _applyDecoratedDescriptor(_class.prototype, 'createReqParam', [_coreDecorators.autobind], Object.getOwnPropertyDescriptor(_class.prototype, 'createReqParam'), _class.prototype), _applyDecoratedDescriptor(_class.prototype, 'updateMain', [_coreDecorators.autobind], Object.getOwnPropertyDescriptor(_class.prototype, 'updateMain'), _class.prototype)), _class);
exports.default = InfoLayout;