import destroy from "./../destroy";
import showMask from "./showMask";
import updateAttribute from "./updateAttribute";

// 弹出对话框
export default function confirm(_ref) {
  var portal = _ref.portal,
    maskClosable = _ref.maskClosable,
    onVisibleChange = _ref.onVisibleChange,
    maskProps = _ref.maskProps,
    title = _ref.title,
    titleProps = _ref.titleProps,
    content = _ref.content,
    contentProps = _ref.contentProps,
    footerProps = _ref.footerProps,
    ok = _ref.ok,
    onOk = _ref.onOk,
    okProps = _ref.okProps,
    cancel = _ref.cancel,
    onCancel = _ref.onCancel,
    cancelProps = _ref.cancelProps;
  var mask = null;

  // 点击遮罩
  function handleMaskClick(e) {
    e.stopPropagation();

    // 点击确定或取消按钮
    if (e.target.classList.contains('modal-cancel') || e.target.classList.contains('modal-ok')) {
      handleButtonClick(e);
      return;
    }

    // 点击遮罩
    if (e.target.classList.contains('mask')) {
      var _mask, _mask2;
      // 读取更新后的属性
      var _maskClosable = (_mask = mask) === null || _mask === void 0 ? void 0 : _mask.maskClosable;
      var _onVisibleChange = (_mask2 = mask) === null || _mask2 === void 0 ? void 0 : _mask2.onVisibleChange;
      if (_maskClosable) {
        if (_onVisibleChange) _onVisibleChange(false);
        destroy(e.currentTarget);
      }
    }
  }

  // 点击确定或者取消按钮
  function handleButtonClick(e) {
    var _mask3, _mask4, _mask5;
    var isOk = e.target.classList.contains('modal-ok');

    // 读取更新后的属性
    var onClick = isOk ? (_mask3 = mask) === null || _mask3 === void 0 ? void 0 : _mask3.onOk : (_mask4 = mask) === null || _mask4 === void 0 ? void 0 : _mask4.onCancel;
    var onVisibleChange = (_mask5 = mask) === null || _mask5 === void 0 ? void 0 : _mask5.onVisibleChange;
    if (typeof onClick === 'function') {
      var _onClick;
      var close = (_onClick = onClick()) !== null && _onClick !== void 0 ? _onClick : true;
      if (close) {
        if (onVisibleChange) onVisibleChange(false);
        destroy(e.currentTarget.closest('.modal-mask'));
      }
    } else {
      if (onVisibleChange) onVisibleChange(false);
      destroy(e.currentTarget.closest('.modal-mask'));
    }
    e.stopPropagation();
  }

  // 渲染与绑定事件
  mask = showMask({
    portal: portal,
    onMaskClick: handleMaskClick
  });

  // 更新属性
  updateAttribute(mask, {
    portal: portal,
    maskClosable: maskClosable,
    onVisibleChange: onVisibleChange,
    // 遮罩
    maskProps: maskProps,
    // 标题
    title: title,
    titleProps: titleProps,
    // 内容
    content: content,
    contentProps: contentProps,
    // 底部
    footerProps: footerProps,
    // 确定, 默认显示确定按钮
    ok: ok,
    onOk: onOk,
    okProps: okProps,
    // 取消, confirm默认显示取消按钮
    cancel: cancel,
    onCancel: onCancel,
    cancelProps: cancelProps
  });
  return mask;
}