import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
import _objectSpread from "@babel/runtime/helpers/objectSpread2";
import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import _extends from "@babel/runtime/helpers/extends";
import _classCallCheck from "@babel/runtime/helpers/classCallCheck";
import _createClass from "@babel/runtime/helpers/createClass";
import _assertThisInitialized from "@babel/runtime/helpers/assertThisInitialized";
import _get from "@babel/runtime/helpers/get";
import _getPrototypeOf from "@babel/runtime/helpers/getPrototypeOf";
import _inherits from "@babel/runtime/helpers/inherits";
import _createSuper from "@babel/runtime/helpers/createSuper";
import _regeneratorRuntime from "@babel/runtime/regenerator";
import { __decorate } from "tslib";
import React, { cloneElement, isValidElement } from 'react';
import isEqual from 'lodash/isEqual';
import defer from 'lodash/defer';
import noop from 'lodash/noop';
import isNil from 'lodash/isNil';
import isNumber from 'lodash/isNumber';
import classNames from 'classnames';
import classes from 'component-classes';
import { pxToPercent, pxToRem, toPx } from '../../../es/_util/UnitConvertor';
import { observable, runInAction } from 'mobx';
import KeyCode from '../../../es/_util/KeyCode';
import math from 'choerodon-ui/dataset/math';
import ViewComponent from '../core/ViewComponent';
import Icon from '../icon';
import autobind from '../_util/autobind';
import Button from '../button/Button';
import EventManager from '../_util/EventManager';
import { ButtonColor, FuncType } from '../button/enum';
import asyncComponent from '../_util/AsyncComponent';
import message from '../message';
import exception from '../_util/exception';
import { $l } from '../locale-context';
import DataSetRequestError from '../data-set/DataSetRequestError';
import { suffixCls, toUsefulDrawerTransitionName } from './utils';
import { getDocument, transformZoomData } from '../_util/DocumentUtils';

function getMath(value, min, max) {
  return Math.min(Math.max(value, min), max);
}

function fixUnit(n) {
  if (isNumber(n)) {
    return "".concat(n, "px");
  }

  return n;
}

function getTransformOrigin(position, style) {
  var _ref = typeof window === 'undefined' ? {} : getDocument(window).documentElement,
      _ref$offsetWidth = _ref.offsetWidth,
      offsetWidth = _ref$offsetWidth === void 0 ? 0 : _ref$offsetWidth,
      _ref$scrollTop = _ref.scrollTop,
      scrollTop = _ref$scrollTop === void 0 ? 0 : _ref$scrollTop,
      _ref$scrollLeft = _ref.scrollLeft,
      scrollLeft = _ref$scrollLeft === void 0 ? 0 : _ref$scrollLeft;

  var _style$width = style.width,
      width = _style$width === void 0 ? 520 : _style$width,
      left = style.left,
      _style$top = style.top,
      top = _style$top === void 0 ? 100 : _style$top;
  var x = position.x,
      y = position.y;
  var originX = "calc(".concat(x, "px - ").concat(isNil(left) ? "(".concat(offsetWidth, "px - ").concat(fixUnit(width), ") / 2") : "".concat(fixUnit(left)), " - ").concat(scrollLeft, "px)"); // const originX = isNil(left) ? `calc(${x}px - (${offsetWidth}px - ${width}px) / 2)` : `${x - (toPx(left) || 0)}px`;

  var originY = "calc(".concat(y, "px - ").concat(fixUnit(top), " - ").concat(scrollTop, "px)"); // const originY = `${y - (toPx(top) || 0) - scrollTop}px`;

  return "".concat(originX, " ").concat(originY);
}

var HANDLE_MIN_SIZE = 50;

var Modal = /*#__PURE__*/function (_ViewComponent) {
  _inherits(Modal, _ViewComponent);

  var _super = _createSuper(Modal);

  function Modal(props, context) {
    var _this;

    _classCallCheck(this, Modal);

    _this = _super.call(this, props, context);
    _this.moveEvent = new EventManager();
    _this.okCancelEvent = new EventManager();
    _this.resizeEvent = new EventManager();

    _this.getDefaultHeader = function (title, closeButton, _okBtn, _cancelBtn) {
      var _assertThisInitialize = _assertThisInitialized(_this),
          prefixCls = _assertThisInitialize.prefixCls,
          drawerHeaderFooterCombined = _assertThisInitialize.drawerHeaderFooterCombined,
          modalClosable = _assertThisInitialize.modalClosable;

      if (title || closeButton) {
        return drawerHeaderFooterCombined ? /*#__PURE__*/React.createElement("div", {
          className: "".concat(prefixCls, "-drawer-header-combined")
        }, modalClosable ? /*#__PURE__*/React.createElement("button", {
          type: "button",
          className: "".concat(prefixCls, "-header-button ").concat(prefixCls, "-header-button-navigate"),
          onClick: _this.handleCancel
        }, /*#__PURE__*/React.createElement(Icon, {
          type: "navigate_next"
        })) : null, /*#__PURE__*/React.createElement("div", {
          className: "".concat(prefixCls, "-title")
        }, title)) : /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", {
          className: "".concat(prefixCls, "-title")
        }, title), /*#__PURE__*/React.createElement("div", {
          className: "".concat(prefixCls, "-header-buttons")
        }, closeButton));
      }
    };

    _this.getDefaultFooter = function (okBtn, cancelBtn, _modalChildrenProps) {
      var _this$props = _this.props,
          okCancel = _this$props.okCancel,
          okButton = _this$props.okButton,
          _this$props$cancelBut = _this$props.cancelButton,
          cancelButton = _this$props$cancelBut === void 0 ? okCancel !== false : _this$props$cancelBut,
          _this$props$okFirst = _this$props.okFirst,
          okFirst = _this$props$okFirst === void 0 ? _this.getContextConfig('modalOkFirst') : _this$props$okFirst,
          drawer = _this$props.drawer;
      var buttons = [];

      if (okButton !== false) {
        buttons.push(okBtn);
      }

      if (cancelButton !== false) {
        var drawerOkFirst = _this.getContextConfig('drawerOkFirst');

        if (drawer && !isNil(drawerOkFirst)) {
          if (drawerOkFirst) {
            buttons.push(cancelBtn);
          } else {
            buttons.unshift(cancelBtn);
          }
        } else if (okFirst) {
          buttons.push(cancelBtn);
        } else {
          buttons.unshift(cancelBtn);
        }
      }

      return /*#__PURE__*/React.createElement("div", null, buttons);
    };

    _this.registerOk = function (ok) {
      _this.okCancelEvent.removeEventListener('ok');

      _this.okCancelEvent.addEventListener('ok', ok);
    };

    _this.registerCancel = function (cancel) {
      _this.okCancelEvent.removeEventListener('cancel');

      _this.okCancelEvent.addEventListener('cancel', cancel);
    };

    var _props$close = props.close,
        close = _props$close === void 0 ? noop : _props$close,
        _props$update = props.update,
        update = _props$update === void 0 ? noop : _props$update;
    _this.childrenProps = {
      close: close,
      update: update,
      props: props,
      handleOk: _this.registerOk,
      handleCancel: _this.registerCancel
    };

    _this.loadCustomized();

    return _this;
  }

  _createClass(Modal, [{
    key: "okBtn",
    get: function get() {
      var _this$props2 = this.props,
          okProps = _this$props2.okProps,
          _this$props2$okText = _this$props2.okText,
          okText = _this$props2$okText === void 0 ? $l('Modal', 'ok') : _this$props2$okText,
          drawer = _this$props2.drawer;
      var modalButtonProps = this.getContextConfig('modalButtonProps');
      var funcType = drawer ? FuncType.raised : this.getContextConfig('buttonFuncType');
      return /*#__PURE__*/React.createElement(Button, _extends({
        key: "ok",
        funcType: funcType,
        color: ButtonColor.primary,
        onClick: this.handleOk
      }, modalButtonProps, okProps), okText);
    }
  }, {
    key: "cancelBtn",
    get: function get() {
      var _this$props3 = this.props,
          cancelProps = _this$props3.cancelProps,
          _this$props3$cancelTe = _this$props3.cancelText,
          cancelText = _this$props3$cancelTe === void 0 ? $l('Modal', 'cancel') : _this$props3$cancelTe,
          drawer = _this$props3.drawer;
      var modalButtonProps = this.getContextConfig('modalButtonProps');
      var funcType = drawer ? FuncType.raised : this.getContextConfig('buttonFuncType');
      return /*#__PURE__*/React.createElement(Button, _extends({
        key: "cancel",
        ref: this.saveCancelRef,
        funcType: funcType,
        onClick: this.handleCancel
      }, modalButtonProps, cancelProps), cancelText);
    }
  }, {
    key: "drawerTransitionName",
    get: function get() {
      var _this$props$drawerTra = this.props.drawerTransitionName,
          drawerTransitionName = _this$props$drawerTra === void 0 ? this.getContextConfig('drawerTransitionName') : _this$props$drawerTra;
      return toUsefulDrawerTransitionName(drawerTransitionName);
    }
  }, {
    key: "drawerHeaderFooterCombined",
    get: function get() {
      var drawer = this.props.drawer;
      return this.getContextConfig('drawerHeaderFooterCombined') && !!drawer;
    }
  }, {
    key: "modalClosable",
    get: function get() {
      if ('closable' in this.props) {
        return this.props.closable;
      }

      return this.getContextConfig('modalClosable');
    }
  }, {
    key: "doc",
    get: function get() {
      return getDocument(window);
    }
  }, {
    key: "autoWidth",
    get: function get() {
      var contentStyle = this.props.contentStyle;

      if (contentStyle && contentStyle.width) {
        return true;
      }

      return false;
    }
  }, {
    key: "componentDidMount",
    value: function componentDidMount() {
      _get(_getPrototypeOf(Modal.prototype), "componentDidMount", this).call(this);

      this.initResizableRange(this.props);
    }
  }, {
    key: "componentWillReceiveProps",
    value: function componentWillReceiveProps(nextProps, nextContext) {
      _get(_getPrototypeOf(Modal.prototype), "componentWillReceiveProps", this).call(this, nextProps, nextContext);

      if (!isEqual(this.props, nextProps)) {
        var _nextProps$close = nextProps.close,
            close = _nextProps$close === void 0 ? noop : _nextProps$close,
            _nextProps$update = nextProps.update,
            update = _nextProps$update === void 0 ? noop : _nextProps$update,
            _nextProps$resizable = nextProps.resizable,
            nextResizable = _nextProps$resizable === void 0 ? false : _nextProps$resizable;

        _extends(this.childrenProps, {
          close: close,
          update: update,
          props: nextProps
        });

        if (nextResizable !== this.props.resizable) {
          this.initResizableRange(nextProps);
        }
      }
    }
  }, {
    key: "initResizableRange",
    value: function initResizableRange(props) {
      var _this2 = this;

      var resizable = props.resizable,
          contentStyle = props.contentStyle,
          style = props.style;

      if (resizable) {
        runInAction(function () {
          _this2.minWidth = style && toPx(style.minWidth) || contentStyle && toPx(contentStyle.minWidth) || _this2.element.getBoundingClientRect().width;
          _this2.minHeight = style && toPx(style.minHeight) || contentStyle && toPx(contentStyle.minHeight) || _this2.contentNode.offsetHeight;
        });
      }
    }
  }, {
    key: "saveCancelRef",
    value: function saveCancelRef(node) {
      this.cancelButton = node;
    }
  }, {
    key: "handleKeyDown",
    value: function handleKeyDown(e) {
      if (e.keyCode === KeyCode.ESC) {
        e.stopPropagation();
        var cancelButton = this.cancelButton;

        if (cancelButton && !cancelButton.disabled) {
          cancelButton.handleClickWait(e);
        } else {
          this.handleCancel();
        }
      }

      if (e.keyCode === KeyCode.TAB && !this.props.hidden) {
        this.changeActive(!e.shiftKey);
      }
    }
  }, {
    key: "getOmitPropsKeys",
    value: function getOmitPropsKeys() {
      return _get(_getPrototypeOf(Modal.prototype), "getOmitPropsKeys", this).call(this).concat(['__deprecate__', 'closable', 'movable', 'maskClosable', 'maskStyle', 'mask', 'maskClassName', 'keyboardClosable', 'fullScreen', 'title', 'header', 'footer', 'close', 'update', 'okText', 'cancelText', 'okButton', 'cancelButton', 'okCancel', 'onClose', 'onOk', 'onCancel', 'destroyOnClose', 'drawer', 'drawerOffset', 'drawerTransitionName', 'transitionAppear', 'afterClose', 'okProps', 'cancelProps', 'border', 'drawerBorder', 'okFirst', 'autoCenter', 'mousePosition', 'active', 'onTop', 'contentStyle', 'bodyStyle', 'closeOnLocationChange', 'eventKey', 'resizable', 'customizable', 'customizedCode']);
    }
  }, {
    key: "loadCustomized",
    value: function () {
      var _loadCustomized = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
        var _this3 = this;

        var getCustomizable, _this$props4, _this$props4$customiz, customizable, customizedCode, drawer, temp, contentNode, element, prefixCls;

        return _regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                getCustomizable = this.context.getCustomizable;
                _this$props4 = this.props, _this$props4$customiz = _this$props4.customizable, customizable = _this$props4$customiz === void 0 ? getCustomizable('Modal') : _this$props4$customiz, customizedCode = _this$props4.customizedCode, drawer = _this$props4.drawer;

                if (!(customizable && customizedCode)) {
                  _context.next = 7;
                  break;
                }

                _context.next = 5;
                return this.getContextConfig('customizedLoad')(customizedCode, 'Modal');

              case 5:
                temp = _context.sent;

                if (temp) {
                  contentNode = this.contentNode, element = this.element, prefixCls = this.prefixCls;
                  runInAction(function () {
                    if (drawer) {
                      switch (_this3.drawerTransitionName) {
                        case 'slide-right':
                        case 'slide-left':
                          delete temp.height;
                          break;

                        case 'slide-up':
                        case 'slide-down':
                          delete temp.width;
                          break;

                        default:
                          break;
                      }
                    }

                    _this3.tempCustomized = _this3.getTempCustomized(temp);
                  });

                  if (classes(element).has("".concat(prefixCls, "-auto-center"))) {
                    _extends(element.style, {
                      bottom: 0,
                      margin: 'auto'
                    });

                    if (contentNode) {
                      _extends(contentNode.style, {
                        height: 'inherit'
                      });
                    }
                  }

                  this.forceUpdate();
                }

              case 7:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, this);
      }));

      function loadCustomized() {
        return _loadCustomized.apply(this, arguments);
      }

      return loadCustomized;
    }()
  }, {
    key: "saveCustomized",
    value: function saveCustomized() {
      var getCustomizable = this.context.getCustomizable;
      var _this$props5 = this.props,
          _this$props5$customiz = _this$props5.customizable,
          customizable = _this$props5$customiz === void 0 ? getCustomizable('Modal') : _this$props5$customiz,
          customizedCode = _this$props5.customizedCode;

      if (customizable && customizedCode) {
        var customizedSave = this.getContextConfig('customizedSave');
        customizedSave(customizedCode, this.tempCustomized || {}, 'Modal');
      }
    }
  }, {
    key: "getTempCustomized",
    value: function getTempCustomized() {
      var tempCustomized = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.tempCustomized;
      var temp = {};

      if (tempCustomized) {
        var element = this.element;
        var isEmbedded = !!(element && element.offsetParent);
        Object.keys(tempCustomized).forEach(function (item) {
          temp[item] = isEmbedded ? tempCustomized[item] : math.floor(tempCustomized[item]);
        });
      }

      return temp;
    }
  }, {
    key: "getOtherProps",
    value: function getOtherProps() {
      var otherProps = _get(_getPrototypeOf(Modal.prototype), "getOtherProps", this).call(this);

      var _this$props6 = this.props,
          hidden = _this$props6.hidden,
          mousePosition = _this$props6.mousePosition,
          _this$props6$keyboard = _this$props6.keyboardClosable,
          keyboardClosable = _this$props6$keyboard === void 0 ? this.getContextConfig('modalKeyboard') : _this$props6$keyboard,
          _this$props6$style = _this$props6.style,
          style = _this$props6$style === void 0 ? {} : _this$props6$style,
          drawer = _this$props6.drawer,
          onTop = _this$props6.onTop;

      var currentStyle = _objectSpread(_objectSpread({}, style), this.getTempCustomized());

      if (keyboardClosable) {
        otherProps.autoFocus = true;
        otherProps.tabIndex = -1;
        otherProps.onKeyDown = this.handleKeyDown;
      }

      if (drawer) {
        otherProps.style = _objectSpread({}, currentStyle);
      } else {
        var position = this.mousePosition || mousePosition;

        if (position) {
          this.mousePosition = position;
          otherProps.style = _objectSpread(_objectSpread({}, currentStyle), {}, {
            transformOrigin: getTransformOrigin(position, currentStyle)
          });
        }

        if (hidden) {
          this.mousePosition = null;
        }
      }

      if (onTop) {
        otherProps.onMouseDown = this.handleMouseDown;
      }

      return otherProps;
    }
  }, {
    key: "contentReference",
    value: function contentReference(node) {
      this.contentNode = node;
    }
  }, {
    key: "sentinelStartReference",
    value: function sentinelStartReference(node) {
      this.sentinelStartRef = node;
    }
  }, {
    key: "sentinelEndReference",
    value: function sentinelEndReference(node) {
      this.sentinelEndRef = node;
    }
  }, {
    key: "getClassName",
    value: function getClassName() {
      var _get$call;

      var prefixCls = this.prefixCls,
          autoWidth = this.autoWidth,
          _this$props7 = this.props,
          _this$props7$style = _this$props7.style,
          style = _this$props7$style === void 0 ? this.tempCustomized || {} : _this$props7$style,
          fullScreen = _this$props7.fullScreen,
          drawer = _this$props7.drawer,
          size = _this$props7.size,
          active = _this$props7.active,
          _this$props7$border = _this$props7.border,
          border = _this$props7$border === void 0 ? this.getContextConfig('modalSectionBorder') : _this$props7$border,
          _this$props7$drawerBo = _this$props7.drawerBorder,
          drawerBorder = _this$props7$drawerBo === void 0 ? this.getContextConfig('drawerSectionBorder') : _this$props7$drawerBo,
          _this$props7$autoCent = _this$props7.autoCenter,
          autoCenter = _this$props7$autoCent === void 0 ? this.getContextConfig('modalAutoCenter') : _this$props7$autoCent;
      var center = !drawer && !this.offset;
      return _get(_getPrototypeOf(Modal.prototype), "getClassName", this).call(this, (_get$call = {}, _defineProperty(_get$call, "".concat(prefixCls, "-center"), center && !('left' in style || 'right' in style)), _defineProperty(_get$call, "".concat(prefixCls, "-fullscreen"), fullScreen), _defineProperty(_get$call, "".concat(prefixCls, "-drawer"), drawer), _defineProperty(_get$call, "".concat(prefixCls, "-border"), drawer ? drawerBorder : border), _defineProperty(_get$call, "".concat(prefixCls, "-drawer-").concat(toUsefulDrawerTransitionName(this.drawerTransitionName)), drawer), _defineProperty(_get$call, "".concat(prefixCls, "-auto-center"), autoCenter && center && !fullScreen), _defineProperty(_get$call, "".concat(prefixCls, "-").concat(size), size), _defineProperty(_get$call, "".concat(prefixCls, "-active"), active), _defineProperty(_get$call, "".concat(prefixCls, "-auto-width"), autoWidth), _get$call));
    }
  }, {
    key: "getDrawerOffset",
    value: function getDrawerOffset(drawerTransitionName) {
      var style = this.props.style;

      if (style) {
        switch (drawerTransitionName) {
          case 'slide-right':
            return toPx(style.marginRight) || 0;

          case 'slide-left':
            return toPx(style.marginLeft) || 0;

          case 'slide-up':
            return toPx(style.marginTop) || 0;

          case 'slide-down':
            return toPx(style.marginBottom) || 0;

          default:
            return toPx(style.marginRight) || 0;
        }
      }

      return 0;
    }
  }, {
    key: "handleResize",
    value: function handleResize(e) {
      var _this4 = this;

      e.persist();
      var _this$props8 = this.props,
          drawer = _this$props8.drawer,
          fullScreen = _this$props8.fullScreen;

      if (e.target && !fullScreen && this.contentNode) {
        var mousemove = !drawer ? this.handleModalMouseResize(e) : this.handleDrawerMouseResize(e);

        if (mousemove) {
          var maskDiv = document.createElement('div');
          maskDiv.className = "".concat(this.prefixCls, "-resizer-mask");
          this.element.appendChild(maskDiv);

          var handleMouseUp = function handleMouseUp() {
            var _this4$element$getBou = _this4.element.getBoundingClientRect(),
                width = _this4$element$getBou.width,
                height = _this4$element$getBou.height;

            var _ref2 = _this4.element.offsetParent || {},
                embeddedOffsetWidth = _ref2.offsetWidth,
                embeddedOffsetHeight = _ref2.offsetHeight;

            runInAction(function () {
              var temp = {
                width: pxToPercent(width, embeddedOffsetWidth),
                height: pxToPercent(height, embeddedOffsetHeight)
              };

              if (drawer) {
                switch (_this4.drawerTransitionName) {
                  case 'slide-left':
                  case 'slide-right':
                    delete temp.height;
                    break;

                  case 'slide-up':
                  case 'slide-down':
                    delete temp.width;
                    break;

                  default:
                    break;
                }
              }

              _this4.tempCustomized = temp;
            });

            _this4.saveCustomized();

            _this4.element.removeChild(maskDiv);

            _this4.resizeEvent.removeEventListener('mousemove', mousemove).removeEventListener('mouseup', handleMouseUp);
          };

          this.resizeEvent.setTarget(this.doc).addEventListener('mousemove', mousemove).addEventListener('mouseup', handleMouseUp);
        }
      }
    }
  }, {
    key: "handleModalMouseResize",
    value: function handleModalMouseResize(e) {
      var contentNode = this.contentNode,
          element = this.element,
          offsetParent = this.element.offsetParent,
          minHeight = this.minHeight,
          minWidth = this.minWidth,
          prefixCls = this.prefixCls,
          _this$props9 = this.props,
          drawer = _this$props9.drawer,
          _this$props9$autoCent = _this$props9.autoCenter,
          autoCenter = _this$props9$autoCent === void 0 ? this.getContextConfig('modalAutoCenter') : _this$props9$autoCent;

      var _ref3 = this.doc.documentElement || this.doc.body,
          docClientWidth = _ref3.clientWidth,
          docClientHeight = _ref3.clientHeight;

      var clientX = transformZoomData(e.clientX);
      var clientY = transformZoomData(e.clientY);
      var contentHeight = contentNode.offsetHeight,
          contentWidth = contentNode.offsetWidth,
          contentTop = contentNode.offsetTop;

      var _ref4 = offsetParent || {},
          embeddedOffsetWidth = _ref4.offsetWidth,
          embeddedOffsetHeight = _ref4.offsetHeight;

      var clzz = classes(element);
      var startX = clientX - contentWidth;
      var startY = clientY - contentHeight;

      var _element$getBoundingC = element.getBoundingClientRect(),
          elementLeft = _element$getBoundingC.left,
          elementTop = _element$getBoundingC.top; // modal模式需存在坐标


      if (!drawer && !this.offset && clzz.has("".concat(prefixCls, "-center"))) {
        if (offsetParent) {
          elementTop = element.offsetTop;
          elementLeft = element.offsetLeft;
        }

        this.offset = [pxToRem(elementLeft), pxToRem(autoCenter && contentTop ? contentTop : elementTop)];
        clzz.remove("".concat(prefixCls, "-center")).remove("".concat(prefixCls, "-auto-center"));

        _extends(element.style, {
          left: this.offset[0],
          top: this.offset[1],
          margin: 'initial'
        });
      }

      return function (me) {
        var width = transformZoomData(me.clientX) - startX;
        var height = transformZoomData(me.clientY) - startY;

        _extends(element.style, {
          width: pxToRem(getMath(width, minWidth, embeddedOffsetWidth || docClientWidth)),
          height: pxToRem(getMath(height, minHeight, embeddedOffsetHeight || docClientHeight))
        });
      };
    }
  }, {
    key: "handleDrawerMouseResize",
    value: function handleDrawerMouseResize(e) {
      var contentNode = this.contentNode,
          drawerTransitionName = this.drawerTransitionName,
          element = this.element,
          _this$element = this.element,
          offsetParent = _this$element.offsetParent,
          elementOffsetTop = _this$element.offsetLeft,
          elementOffsetLeft = _this$element.offsetTop,
          minWidth = this.minWidth,
          minHeight = this.minHeight;

      var _ref5 = this.doc.documentElement || this.doc.body,
          docClientWidth = _ref5.clientWidth,
          docClientHeight = _ref5.clientHeight;

      var _ref6 = offsetParent || {},
          embeddedOffsetWidth = _ref6.offsetWidth,
          embeddedOffsetHeight = _ref6.offsetHeight;

      var drawerOffset = this.getDrawerOffset(drawerTransitionName);
      var maxWidth = (embeddedOffsetWidth || docClientWidth) - drawerOffset;
      var maxHeight = (embeddedOffsetHeight || docClientHeight) - drawerOffset;
      var height = contentNode.offsetHeight,
          width = contentNode.offsetWidth;
      return function (me) {
        var clientX = transformZoomData(me.clientX);
        var clientY = transformZoomData(me.clientY);

        if (offsetParent) {
          clientX = elementOffsetTop + clientX - transformZoomData(e.clientX);
          clientY = elementOffsetLeft + clientY - transformZoomData(e.clientY);
        }

        switch (drawerTransitionName) {
          case 'slide-right':
            width = getMath(maxWidth - clientX, minWidth, maxWidth);
            break;

          case 'slide-left':
            width = getMath(clientX - drawerOffset, minWidth, maxWidth);
            break;

          case 'slide-up':
            height = getMath(clientY - drawerOffset, minHeight, maxHeight);
            break;

          case 'slide-down':
            height = getMath(maxHeight - clientY, minHeight, maxHeight);
            break;

          default:
            break;
        }

        _extends(element.style, {
          width: pxToRem(width),
          height: pxToRem(height)
        });
      };
    }
  }, {
    key: "render",
    value: function render() {
      var _classNames, _classNames2;

      var prefixCls = this.prefixCls,
          drawerHeaderFooterCombined = this.drawerHeaderFooterCombined,
          drawerTransitionName = this.drawerTransitionName,
          _this$props10 = this.props,
          contentStyle = _this$props10.contentStyle,
          drawer = _this$props10.drawer,
          _this$props10$resizab = _this$props10.resizable,
          resizable = _this$props10$resizab === void 0 ? this.getContextConfig('modalResizable') : _this$props10$resizab,
          fullScreen = _this$props10.fullScreen;
      var header = this.getHeader();
      var body = this.getBody();
      var footer = this.getFooter();
      var resizerPrefixCls = "".concat(prefixCls, "-resizer");
      var resizerCursorCls = "".concat(resizerPrefixCls, "-cursor");
      var sentinelStyle = {
        width: 0,
        height: 0,
        overflow: 'hidden',
        outline: 'none'
      };
      return /*#__PURE__*/React.createElement("div", _extends({}, this.getMergedProps()), /*#__PURE__*/React.createElement("div", {
        tabIndex: 0,
        ref: this.sentinelStartReference,
        style: sentinelStyle,
        "aria-hidden": "true"
      }), /*#__PURE__*/React.createElement("div", {
        ref: this.contentReference,
        className: classNames("".concat(prefixCls, "-content"), (_classNames = {}, _defineProperty(_classNames, "".concat(prefixCls, "-drawer-content"), drawer), _defineProperty(_classNames, "".concat(resizerPrefixCls, "-content"), resizable), _classNames)),
        style: contentStyle
      }, header, body, drawerHeaderFooterCombined ? null : footer, resizable && /*#__PURE__*/React.createElement("div", {
        className: classNames(resizerCursorCls, (_classNames2 = {}, _defineProperty(_classNames2, "".concat(resizerCursorCls, "-modal"), !drawer && !fullScreen), _defineProperty(_classNames2, "".concat(resizerCursorCls, "-drawer-right"), drawer && drawerTransitionName === 'slide-right'), _defineProperty(_classNames2, "".concat(resizerCursorCls, "-drawer-left"), drawer && drawerTransitionName === 'slide-left'), _defineProperty(_classNames2, "".concat(resizerCursorCls, "-drawer-up"), drawer && drawerTransitionName === 'slide-up'), _defineProperty(_classNames2, "".concat(resizerCursorCls, "-drawer-down"), drawer && drawerTransitionName === 'slide-down'), _classNames2)),
        onMouseDown: this.handleResize
      }, drawer ? /*#__PURE__*/React.createElement("div", {
        className: "".concat(resizerCursorCls, "-line")
      }) : /*#__PURE__*/React.createElement("span", {
        className: "".concat(resizerCursorCls, "-icon")
      }))), /*#__PURE__*/React.createElement("div", {
        tabIndex: 0,
        ref: this.sentinelEndReference,
        style: sentinelStyle,
        "aria-hidden": "true"
      }));
    }
  }, {
    key: "focus",
    value: function focus() {
      this.sentinelStartRef.focus();
    }
  }, {
    key: "changeActive",
    value: function changeActive(next) {
      var activeElement = this.doc.activeElement;

      if (next && activeElement === this.sentinelEndRef) {
        this.sentinelStartRef.focus();
      } else if (!next && activeElement === this.sentinelStartRef) {
        this.sentinelEndRef.focus();
      }
    }
  }, {
    key: "componentWillUpdate",
    value: function componentWillUpdate(_ref7) {
      var _this5 = this;

      var hidden = _ref7.hidden;

      if (hidden === false && hidden !== this.props.hidden) {
        defer(function () {
          return _this5.focus();
        });
      }
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      this.moveEvent.clear();
      this.okCancelEvent.clear();
      this.resizeEvent.clear();
    }
  }, {
    key: "handleMouseDown",
    value: function handleMouseDown(e) {
      var _this$props11 = this.props,
          _this$props11$onMouse = _this$props11.onMouseDown,
          onMouseDown = _this$props11$onMouse === void 0 ? noop : _this$props11$onMouse,
          _this$props11$onTop = _this$props11.onTop,
          onTop = _this$props11$onTop === void 0 ? noop : _this$props11$onTop,
          eventKey = _this$props11.eventKey;
      onMouseDown(e);

      if (!e.isDefaultPrevented()) {
        onTop(eventKey);
      }
    }
  }, {
    key: "handleHeaderMouseDown",
    value: function handleHeaderMouseDown(downEvent) {
      var _this6 = this;

      var element = this.element,
          contentNode = this.contentNode,
          _this$props$autoCente = this.props.autoCenter,
          autoCenter = _this$props$autoCente === void 0 ? this.getContextConfig('modalAutoCenter') : _this$props$autoCente;

      if (element && contentNode) {
        var prefixCls = this.prefixCls;

        var _ref8 = this.doc.documentElement || this.doc.body,
            docClientWidth = _ref8.clientWidth,
            docClientHeight = _ref8.clientHeight;

        var currentTarget = downEvent.currentTarget;
        var clientX = transformZoomData(downEvent.clientX);
        var clientY = transformZoomData(downEvent.clientY);
        var clzz = classes(element);
        var offsetParent = element.offsetParent;

        var _ref9 = offsetParent || {},
            _ref9$scrollTop = _ref9.scrollTop,
            scrollTop = _ref9$scrollTop === void 0 ? 0 : _ref9$scrollTop,
            _ref9$scrollLeft = _ref9.scrollLeft,
            scrollLeft = _ref9$scrollLeft === void 0 ? 0 : _ref9$scrollLeft,
            _ref9$clientWidth = _ref9.clientWidth,
            clientWidth = _ref9$clientWidth === void 0 ? 0 : _ref9$clientWidth,
            _ref9$clientHeight = _ref9.clientHeight,
            clientHeight = _ref9$clientHeight === void 0 ? 0 : _ref9$clientHeight;

        var headerWidth = currentTarget.offsetWidth,
            headerHeight = currentTarget.offsetHeight;

        if (clzz.has("".concat(prefixCls, "-auto-center"))) {
          clzz.remove("".concat(prefixCls, "-auto-center")).remove("".concat(prefixCls, "-center"));
          var offsetWidth = element.offsetWidth,
              offsetHeight = element.offsetHeight;
          var isEmbedded = !!(element && element.offsetParent);
          var top = pxToRem(isEmbedded ? (clientHeight - offsetHeight) / 2 + scrollTop : (docClientHeight - offsetHeight) / 2, true);
          var left = pxToRem(isEmbedded ? (clientWidth - offsetWidth) / 2 + scrollLeft : (docClientWidth - offsetWidth) / 2, true);
          this.offset = [left, top];

          _extends(element.style, {
            top: top,
            left: left
          });
        }

        var offsetLeft = element.offsetLeft;
        var offsetTop = autoCenter && clzz.has("".concat(prefixCls, "-auto-center")) ? scrollTop + contentNode.offsetTop : element.offsetTop;
        this.moveEvent.setTarget(this.doc).addEventListener('mousemove', function (moveEvent) {
          var moveX = transformZoomData(moveEvent.clientX);
          var moveY = transformZoomData(moveEvent.clientY);
          clzz.remove("".concat(prefixCls, "-center"));
          var left = pxToRem(Math.min(Math.max(offsetLeft + moveX - clientX, scrollLeft - headerWidth + HANDLE_MIN_SIZE), scrollLeft + docClientWidth - HANDLE_MIN_SIZE), true);
          var top = pxToRem(Math.min(Math.max(offsetTop + moveY - clientY, scrollTop - headerHeight + HANDLE_MIN_SIZE), scrollTop + docClientHeight - HANDLE_MIN_SIZE), true);
          _this6.offset = [left, top];

          _extends(element.style, {
            left: left,
            top: top
          });
        }).addEventListener('mouseup', function () {
          _this6.moveEvent.clear();
        });
      }
    }
  }, {
    key: "handleOk",
    value: function () {
      var _handleOk = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
        var _this$props$onOk, onOk, promise, _yield$promise, _yield$promise2, ret1, ret2;

        return _regeneratorRuntime.wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                _this$props$onOk = this.props.onOk, onOk = _this$props$onOk === void 0 ? noop : _this$props$onOk;
                promise = Promise.all([onOk(), this.okCancelEvent.fireEvent('ok')]);
                _context2.prev = 2;
                _context2.next = 5;
                return promise;

              case 5:
                _yield$promise = _context2.sent;
                _yield$promise2 = _slicedToArray(_yield$promise, 2);
                ret1 = _yield$promise2[0];
                ret2 = _yield$promise2[1];

                if (ret1 !== false && ret2) {
                  this.close();
                }

                _context2.next = 16;
                break;

              case 12:
                _context2.prev = 12;
                _context2.t0 = _context2["catch"](2);

                if (!(_context2.t0 instanceof DataSetRequestError)) {
                  message.error(exception(_context2.t0));
                }

                throw _context2.t0;

              case 16:
              case "end":
                return _context2.stop();
            }
          }
        }, _callee2, this, [[2, 12]]);
      }));

      function handleOk() {
        return _handleOk.apply(this, arguments);
      }

      return handleOk;
    }()
  }, {
    key: "handleCancel",
    value: function () {
      var _handleCancel = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3() {
        var _this$props$onCancel, onCancel, promise, _yield$promise3, _yield$promise4, ret1, ret2;

        return _regeneratorRuntime.wrap(function _callee3$(_context3) {
          while (1) {
            switch (_context3.prev = _context3.next) {
              case 0:
                _this$props$onCancel = this.props.onCancel, onCancel = _this$props$onCancel === void 0 ? noop : _this$props$onCancel;
                promise = Promise.all([onCancel(), this.okCancelEvent.fireEvent('cancel')]);
                _context3.prev = 2;
                _context3.next = 5;
                return promise;

              case 5:
                _yield$promise3 = _context3.sent;
                _yield$promise4 = _slicedToArray(_yield$promise3, 2);
                ret1 = _yield$promise4[0];
                ret2 = _yield$promise4[1];

                if (ret1 !== false && ret2) {
                  this.close();
                }

                _context3.next = 16;
                break;

              case 12:
                _context3.prev = 12;
                _context3.t0 = _context3["catch"](2);

                if (!(_context3.t0 instanceof DataSetRequestError)) {
                  message.error(exception(_context3.t0));
                }

                throw _context3.t0;

              case 16:
              case "end":
                return _context3.stop();
            }
          }
        }, _callee3, this, [[2, 12]]);
      }));

      function handleCancel() {
        return _handleCancel.apply(this, arguments);
      }

      return handleCancel;
    }()
  }, {
    key: "getHeader",
    value: function getHeader() {
      var _this$props12 = this.props,
          _this$props12$header = _this$props12.header,
          header = _this$props12$header === void 0 ? this.getDefaultHeader : _this$props12$header,
          title = _this$props12.title;

      if (typeof header === 'function') {
        var closeButton = this.getCloseButton();
        return this.getWrappedHeader(header(title, closeButton, this.okBtn, this.cancelBtn));
      }

      if (!isNil(header)) {
        return this.getWrappedHeader(header);
      }
    }
  }, {
    key: "getWrappedHeader",
    value: function getWrappedHeader(header) {
      var drawerHeaderFooterCombined = this.drawerHeaderFooterCombined,
          prefixCls = this.prefixCls,
          _this$props13 = this.props,
          title = _this$props13.title,
          _this$props13$movable = _this$props13.movable,
          movable = _this$props13$movable === void 0 ? this.getContextConfig('modalMovable') : _this$props13$movable,
          fullScreen = _this$props13.fullScreen,
          drawer = _this$props13.drawer,
          modalClosable = this.modalClosable;
      var footer = this.getFooter();

      if (title || modalClosable || movable || header) {
        var _classNames3;

        var headerProps = {
          className: classNames("".concat(prefixCls, "-header"), (_classNames3 = {}, _defineProperty(_classNames3, "".concat(prefixCls, "-movable"), movable && !fullScreen && !drawer), _defineProperty(_classNames3, "".concat(prefixCls, "-title-none"), !title), _defineProperty(_classNames3, "".concat(prefixCls, "-drawer-header"), drawer), _defineProperty(_classNames3, "".concat(prefixCls, "-drawer-header-combined"), drawerHeaderFooterCombined), _classNames3))
        };

        if (movable && !fullScreen && !drawer) {
          headerProps.onMouseDown = this.handleHeaderMouseDown;
        }

        return /*#__PURE__*/React.createElement("div", _extends({}, headerProps), header, drawerHeaderFooterCombined ? footer : null);
      }
    }
  }, {
    key: "getCloseButton",
    value: function getCloseButton() {
      var prefixCls = this.prefixCls,
          modalClosable = this.modalClosable;

      if (modalClosable) {
        return /*#__PURE__*/React.createElement("button", {
          type: "button",
          className: "".concat(prefixCls, "-header-button"),
          onClick: this.handleCancel
        }, /*#__PURE__*/React.createElement(Icon, {
          type: "close"
        }));
      }
    }
  }, {
    key: "getBody",
    value: function getBody() {
      var children = this.props.children;
      return this.renderChildren(typeof children === 'function' ? asyncComponent(children) : children);
    }
  }, {
    key: "getFooter",
    value: function getFooter() {
      var _this$props$footer = this.props.footer,
          footer = _this$props$footer === void 0 ? this.getDefaultFooter : _this$props$footer;

      if (typeof footer === 'function') {
        return this.getWrappedFooter(footer(this.okBtn, this.cancelBtn, this.childrenProps));
      }

      if (!isNil(footer)) {
        return this.getWrappedFooter(footer);
      }
    }
  }, {
    key: "getWrappedFooter",
    value: function getWrappedFooter(footer) {
      var _classNames4;

      var prefixCls = this.prefixCls,
          drawerHeaderFooterCombined = this.drawerHeaderFooterCombined;
      var drawer = this.props.drawer;
      var className = classNames((_classNames4 = {}, _defineProperty(_classNames4, "".concat(prefixCls, "-footer"), !drawerHeaderFooterCombined), _defineProperty(_classNames4, "".concat(prefixCls, "-footer-drawer"), drawer && !drawerHeaderFooterCombined), _defineProperty(_classNames4, "".concat(prefixCls, "-drawer-footer"), drawer && !drawerHeaderFooterCombined), _defineProperty(_classNames4, "".concat(prefixCls, "-drawer-header-buttons-footer"), drawerHeaderFooterCombined), _classNames4));
      return /*#__PURE__*/React.createElement("div", {
        className: className
      }, footer);
    }
  }, {
    key: "renderChildren",
    value: function renderChildren(children) {
      if (children) {
        var prefixCls = this.prefixCls,
            props = this.props;
        var bodyStyle = props.bodyStyle,
            drawer = props.drawer;
        return /*#__PURE__*/React.createElement("div", {
          className: classNames("".concat(prefixCls, "-body"), _defineProperty({}, "".concat(prefixCls, "-drawer-body"), drawer)),
          style: bodyStyle
        }, /*#__PURE__*/isValidElement(children) ? /*#__PURE__*/cloneElement(children, {
          modal: this.childrenProps
        }) : children);
      }
    }
  }, {
    key: "close",
    value: function close() {
      var _this$props$close = this.props.close,
          close = _this$props$close === void 0 ? noop : _this$props$close;
      close();
    }
  }]);

  return Modal;
}(ViewComponent);

export { Modal as default };
Modal.displayName = 'Modal';
Modal.defaultProps = {
  suffixCls: suffixCls,
  mask: true,
  okButton: true,
  okCancel: true,
  destroyOnClose: true,
  fullScreen: false,
  drawer: false,
  drawerOffset: 150,
  autoFocus: true,
  closeOnLocationChange: true
};

__decorate([observable], Modal.prototype, "tempCustomized", void 0);

__decorate([autobind], Modal.prototype, "saveCancelRef", null);

__decorate([autobind], Modal.prototype, "handleKeyDown", null);

__decorate([autobind], Modal.prototype, "contentReference", null);

__decorate([autobind], Modal.prototype, "sentinelStartReference", null);

__decorate([autobind], Modal.prototype, "sentinelEndReference", null);

__decorate([autobind], Modal.prototype, "handleResize", null);

__decorate([autobind], Modal.prototype, "handleMouseDown", null);

__decorate([autobind], Modal.prototype, "handleHeaderMouseDown", null);

__decorate([autobind], Modal.prototype, "handleOk", null);

__decorate([autobind], Modal.prototype, "handleCancel", null);

__decorate([autobind], Modal.prototype, "close", null);
//# sourceMappingURL=Modal.js.map
