'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.showModal = exports.closeBar = 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 _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _reactDom = require('react-dom');

var _reactDom2 = _interopRequireDefault(_reactDom);

var _reactMaskLayer = require('react-mask-layer');

var _reactMaskLayer2 = _interopRequireDefault(_reactMaskLayer);

var _mxa = require('../../components/mxa');

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

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

var _exclusive2 = _interopRequireDefault(_exclusive);

var _fetch = require('../system/fetch');

var _longRunOpt = require('../system/longRunOpt');

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

var _index = require('./index');

var _EventUtils = require('../utils/EventUtils');

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

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

// TODO: delete later
var closeBar = exports.closeBar = function closeBar(cb, title) {
  return _react2.default.createElement(
    'div',
    { className: 'title-bar' },
    _react2.default.createElement(
      'span',
      null,
      title
    ),
    _react2.default.createElement(
      'a',
      { onClick: cb },
      _react2.default.createElement(_mxa.Icon, { type: 'close' })
    )
  );
};

var getUrlPath = function getUrlPath(url) {
  return url;
};

var showModal = function showModal() {
  var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var domainType = arguments[1];
  var domainLink = arguments[2];
  var callback = arguments[3];
  var extraData = arguments[4];

  var maskDiv = document.createElement('div');
  document.body.appendChild(maskDiv);

  var _close = function _close() {
    var unmountResult = _reactDom2.default.unmountComponentAtNode(maskDiv);
    if (unmountResult) {
      maskDiv.parentNode.removeChild(maskDiv);
    }
  };

  var _modalCallback = function _modalCallback(value, selectType, mainEntityKey) {
    _close();
    callback && callback(value, selectType, mainEntityKey);
  };

  var self = {};
  var ModalPage = (0, _index.composePage)();
  var windowHeight = window.innerHeight;
  // TODO: refactor
  var modalDecorator = function modalDecorator(Wrapper) {
    var MyMaskLayer = function (_React$Component) {
      _inherits(MyMaskLayer, _React$Component);

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

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

        _this._getTag = function (cssSelector) {
          if (!cssSelector) {
            return document.querySelector('.' + _this.refStr);
          }
          return document.querySelector('.' + _this.refStr + ' ' + cssSelector);
        };

        _this._createModal = function (dataSource) {
          var maskLayerBody = _react2.default.createElement(ModalPage, {
            target: function target() {
              return self.container;
            },
            query: params // query
            , dataSource: dataSource,
            isModal: true,
            modalCallback: _modalCallback,
            domainType: domainType,
            domainLink: domainLink,
            onRefresh: params.onRefresh,
            isModalInput: params.isModalInput,
            createModalButtons: domainType === _dictActions.PAGE_TYPE_DETAIL || domainType === _dictActions.PAGE_TYPE_SUMMARY ? _this._createBottomButtons : null,
            closeModal: _close,
            refStr: _this.refStr,
            resetPosition: _this._resetPosition,
            initWrapperHeight: _this._initWrapperHeight,
            bodyAutoScroll: _this._bodyAutoScroll,
            extraData: extraData
          });
          _this.setState({
            body: maskLayerBody
          });
        };

        _this._resetPosition = function () {
          var tag = _this._getTag();
          /* eslint-disable */
          var modalBody = window.getComputedStyle(tag.childNodes[0]);
          var modalHeight = modalBody.height.substring(0, modalBody.height.length - 2);
          tag.style.top = (window.innerHeight - parseInt(modalHeight)) / 2 + 'px';
        };

        _this._closeBar = function (cb, title) {
          var event = {
            onMouseDown: function onMouseDown(e) {
              _this.isMoving = true;
              var tag = window.getComputedStyle(_this._getTag());
              _this.tagX = tag.left.substring(0, tag.left.length - 2);
              _this.tagY = tag.top.substring(0, tag.top.length - 2);
              _this.clientX = e.clientX;
              _this.clientY = e.clientY;
            },
            onMouseMove: function onMouseMove(e) {
              if (_this.isMoving) {
                var tag = _this._getTag();
                tag.style.left = Number(_this.tagX) + e.clientX - _this.clientX + 'px';
                tag.style.top = Number(_this.tagY) + e.clientY - _this.clientY + 'px';
              }
            }
          };

          event.onMouseUp = event.onMouseOut = function (e) {
            _this.isMoving = false;
          };
          return _react2.default.createElement(
            'div',
            _extends({ className: 'title-bar' }, event),
            _react2.default.createElement(
              'span',
              null,
              title
            ),
            _react2.default.createElement(
              'a',
              { onClick: cb },
              _react2.default.createElement(_mxa.Icon, { type: 'close' })
            )
          );
        };

        _this._createBottomButtons = function (data) {
          _this.setState({
            bottomButtons: data
          });
        };

        _this._initWrapperHeight = function (height) {
          var tag = _this._getTag('.modal-content-detail');
          if (height > windowHeight * 0.7) {
            height = windowHeight * 0.7;
          }
          tag && (tag.style.minHeight = height + 'px');
        };

        _this._bodyAutoScroll = function () {
          var tag = _this._getTag(".modal-content-detail");
          tag && (tag.scrollTop = tag.scrollHeight - tag.clientHeight);
        };

        _this.refStr = 'modal-pop-' + new Date().getTime();
        _this.isMoving = false;
        _this.clientX = 0;
        _this.clientY = 0;
        // 这样 body 只会构建一次
        var Body = null;
        if (_this.props.body) {
          Body = _this.props.body;
          Body = _react2.default.createElement(Body, { callback: _modalCallback, createBottomButtons: _this._createBottomButtons });
        }
        _this.state = {
          bottomButtons: null,
          body: Body || _react2.default.createElement(
            'div',
            { className: 'loading' },
            _react2.default.createElement(_mxa.Icon, { type: 'loading' })
          )
        };
        return _this;
      }

      _createClass(MyMaskLayer, [{
        key: 'componentDidMount',
        value: function componentDidMount() {
          var _this2 = this;

          (0, _EventUtils.addEventToBlurForm)(document.querySelector('.modal-content-detail'));
          this._resetPosition();
          if (domainLink && !_exclusive2.default.some(function (f) {
            return f(domainLink);
          })) {
            (function () {
              var url = getUrlPath((0, _StringUtils.trimStart)(domainLink, '/'));
              (0, _longRunOpt.longRunExec)(function () {
                return (0, _fetch.PFetch)(url, params).then(function (data) {
                  _this2._createModal(data);
                });
              });
            })();
          }
        }
      }, {
        key: 'componentWillUnmount',
        value: function componentWillUnmount() {
          (0, _EventUtils.removeEventToBlurForm)(document.querySelector('.modal-content-detail'));
        }
      }, {
        key: 'componentDidUpdate',
        value: function componentDidUpdate() {
          var _this3 = this;

          setTimeout(function () {
            return _this3._resetPosition();
          });
        }

        //TODO: refactor

      }, {
        key: 'render',
        value: function render() {
          var modalMaxHeight = void 0;
          var modalContentClassName = 'modal-content-detail';
          if (domainType === _dictActions.PAGE_TYPE_SUMMARY_LIST || domainType === _dictActions.PAGE_TYPE_LIST) {
            modalMaxHeight = windowHeight * 0.7;
            modalContentClassName = 'modal-content-list';
          }
          return _react2.default.createElement(
            Wrapper,
            { maskTransitionName: '', className: this.refStr, prefixCls: 'mx-mask-self', visible: true, style: { left: '25%', height: modalMaxHeight }, onCancel: _close, zIndex: '999', maskClosable: false },
            _react2.default.createElement(
              'div',
              { style: { width: '100%', overflow: 'hidden', height: '100%', position: 'relative' } },
              this._closeBar(_close, params && params.modalTitle),
              _react2.default.createElement(
                'div',
                { style: { maxHeight: windowHeight * 0.7, height: '100%' }, className: modalContentClassName, ref: function ref(node) {
                    self.container = node;
                  } },
                _react2.default.createElement(
                  'div',
                  { className: 'modal-content-body' },
                  this.state.body
                ),
                this.state.bottomButtons && _react2.default.createElement(
                  'div',
                  { className: 'pop-bottom-btns', style: { position: 'absolute', bottom: 0, width: '100%' } },
                  _react2.default.createElement(
                    'div',
                    { className: 'pop_up_button' },
                    this.state.bottomButtons
                  )
                )
              )
            )
          );
        }
      }]);

      return MyMaskLayer;
    }(_react2.default.Component);

    return MyMaskLayer;
  };

  var MaskModal = modalDecorator(_reactMaskLayer2.default);
  _reactDom2.default.render(_react2.default.createElement(MaskModal, { body: params.body }), maskDiv);
};

// const showModal = (params, domainType, domainLink, callback) => {
//  if (domainLink && !exclusive.some(f => f(domainLink))) {
//    const url = getUrlPath(trimStart(domainLink, '/'));
//    longRunExec(() => PFetch(url, params)
//      .then(data => {
//        createModal(params, domainType, domainLink, callback, data);
//      }));
//  } else {
//    createModal(params, domainType, domainLink, callback);
//  }
// };

// eslint-disable-next-line import/prefer-default-export
exports.showModal = showModal;