function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

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

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _extends() { _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; }; return _extends.apply(this, arguments); }

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import cx from 'classnames';
import ConfigProvider from '../config-provider';
import Message from '../message';
import Button from '../button';
import zhCN from '../locale/zh-cn';
import dialog from './dialog';
var Dialog = ConfigProvider.config(dialog);

var noop = function noop() {};

export var ModalInner = function ModalInner(_ref) {
  var type = _ref.type,
      _ref$messageProps = _ref.messageProps,
      messageProps = _ref$messageProps === void 0 ? {} : _ref$messageProps,
      title = _ref.title,
      rtl = _ref.rtl,
      _ref$prefix = _ref.prefix,
      prefix = _ref$prefix === void 0 ? 'next-' : _ref$prefix,
      content = _ref.content;
  return React.createElement(Message, _extends({}, messageProps, {
    closeable: false,
    shape: "addon",
    size: "large",
    type: type,
    title: title,
    rtl: rtl,
    className: cx("".concat(prefix, "dialog-message"), messageProps.className)
  }), content);
};

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

  function Modal() {
    var _getPrototypeOf2;

    var _this;

    _classCallCheck(this, Modal);

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

    _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(Modal)).call.apply(_getPrototypeOf2, [this].concat(args)));

    _defineProperty(_assertThisInitialized(_this), "state", {
      visible: true,
      loading: false
    });

    _defineProperty(_assertThisInitialized(_this), "close", function () {
      _this.setState({
        visible: false
      });
    });

    _defineProperty(_assertThisInitialized(_this), "loading", function (loading) {
      _this.setState({
        loading: loading
      });
    });

    return _this;
  }

  _createClass(Modal, [{
    key: "wrapper",
    value: function wrapper(fn, callback) {
      var _this2 = this;

      return function () {
        var res = fn();

        if (res && res.then) {
          _this2.loading(true);

          res.then(function (result) {
            _this2.loading(false);

            if (result !== false) {
              return callback();
            }
          })["catch"](function (e) {
            _this2.loading(false);

            throw e;
          });
        } else if (res !== false) {
          return callback();
        }
      };
    }
  }, {
    key: "render",
    value: function render() {
      var _this$props = this.props,
          prefix = _this$props.prefix,
          type = _this$props.type,
          title = _this$props.title,
          content = _this$props.content,
          messageProps = _this$props.messageProps,
          footerActions = _this$props.footerActions,
          onOk = _this$props.onOk,
          onCancel = _this$props.onCancel,
          onClose = _this$props.onClose,
          okProps = _this$props.okProps,
          rtl = _this$props.rtl,
          className = _this$props.className,
          others = _objectWithoutProperties(_this$props, ["prefix", "type", "title", "content", "messageProps", "footerActions", "onOk", "onCancel", "onClose", "okProps", "rtl", "className"]);

      var newFooterActions = footerActions || ['cancel', 'ok'];
      var newOnOk = this.wrapper(onOk, this.close);
      var newOnCancel = this.wrapper(onCancel, this.close);
      var newOnClose = this.wrapper(onClose, this.close);
      var newTitle = React.createElement("div", {
        className: "".concat(prefix, "dialog-quick-header")
      }, React.createElement("span", {
        className: "".concat(prefix, "dialog-quick-title")
      }, title), React.createElement(Button.Icon, {
        type: "primary",
        name: "remove",
        onClick: newOnClose,
        color: "gray"
      }));
      var newContent = type ? React.createElement(ModalInner, {
        messageProps: messageProps,
        type: type,
        title: newTitle,
        rtl: rtl,
        prefix: prefix,
        content: content,
        closeable: false
      }) : content;
      var _this$state = this.state,
          visible = _this$state.visible,
          loading = _this$state.loading;
      okProps.loading = loading;
      var classNames = cx("".concat(prefix, "dialog-quick"), className);
      return React.createElement(Dialog, _extends({
        role: "alertdialog"
      }, others, {
        visible: visible,
        rtl: rtl,
        footerActions: newFooterActions,
        onOk: this.state.loading ? noop : newOnOk,
        onCancel: newOnCancel,
        onClose: newOnClose,
        okProps: okProps,
        className: classNames
      }), newContent);
    }
  }]);

  return Modal;
}(Component);

_defineProperty(Modal, "propTypes", {
  prefix: PropTypes.string,
  pure: PropTypes.bool,
  rtl: PropTypes.bool,
  type: PropTypes.string,
  title: PropTypes.node,
  content: PropTypes.node,
  messageProps: PropTypes.object,
  footerActions: PropTypes.array,

  /**
   * Callback function triggered when Ok button is clicked
   * @param {Object} event click event object
   * @returns {Promise} Optionally handles a Promise return object
   */
  onOk: PropTypes.func,

  /**
   * Callback function triggered when Cancel button is clicked
   * @param {Object} event click event object
   * @returns {Promise} Optionally handles a Promise return object
   */
  onCancel: PropTypes.func,

  /**
   * Callback function triggered when Close button is clicked
   * @param {Object} event click event object
   * @returns {Promise} Optionally handles a Promise return object
   */
  onClose: PropTypes.func,
  okProps: PropTypes.object,
  locale: PropTypes.object,
  className: PropTypes.string
});

_defineProperty(Modal, "defaultProps", {
  prefix: 'next-',
  type: 'notice',
  pure: false,
  messageProps: {},
  onOk: noop,
  onCancel: noop,
  onClose: noop,
  okProps: {},
  locale: zhCN.Dialog
});

var ConfigModal = ConfigProvider.config(Modal, {
  componentName: 'Dialog'
});
/**
 * 创建对话框
 * @exportName show
 * @param {Object} config 配置项
 * @returns {Object} 包含有 hide 方法，可用来关闭对话框
 */

export var show = function show() {
  var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var container = document.createElement('div');

  var currentConfig = _objectSpread({}, config);

  var unmount = function unmount() {
    if (currentConfig.afterClose) {
      currentConfig.afterClose();
    }

    ReactDOM.unmountComponentAtNode(container);
    container.parentNode.removeChild(container);
  };

  document.body.appendChild(container);
  var newContext = ConfigProvider.getContext();
  var instance;

  var render = function render() {
    var modalConfig = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    setTimeout(function () {
      ReactDOM.render(React.createElement(ConfigProvider, newContext, React.createElement(ConfigModal, _extends({}, modalConfig, {
        afterClose: unmount,
        ref: function ref(_ref2) {
          instance = _ref2;
        }
      }))), container);
    });
  };

  render(currentConfig);
  return {
    hide: function hide() {
      var inc = instance && instance.getInstance();
      inc && inc.close();
    },
    update: function update() {
      var newConfig = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      currentConfig = _objectSpread({}, currentConfig, {}, newConfig);
      render(currentConfig);
    }
  };
};

var methodFactory = function methodFactory(type) {
  return function () {
    var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    config.type = type;
    return show(config);
  };
};
/**
 * 创建提示对话框
 * @exportName notice
 * @param {Object} config 配置项
 * @returns {Object} 包含有 hide 方法，可用来关闭对话框
 */


export var notice = methodFactory('notice');
/**
 * 创建警告对话框
 * @exportName warning
 * @param {Object} config 配置项
 * @returns {Object} 包含有 hide 方法，可用来关闭对话框
 */

export var warning = methodFactory('warning');
/**
 * 创建错误对话框
 * @exportName error
 * @param {Object} config 配置项
 * @returns {Object} 包含有 hide 方法，可用来关闭对话框
 */

export var error = methodFactory('error');
/**
 * 创建成功对话框
 * @exportName success
 * @param {Object} config 配置项
 * @returns {Object} 包含有 hide 方法，可用来关闭对话框
 */

export var success = methodFactory('success');