"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }

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

var _react = _interopRequireWildcard(require("react"));

var _classnames = _interopRequireDefault(require("classnames"));

var _reactRouterDom = require("react-router-dom");

var _components = require("@alicloudfe/components");

var _popConfirm = _interopRequireDefault(require("@teamix/pop-confirm"));

var _utils = require("@teamix/utils");

var _form = _interopRequireWildcard(require("../form"));

var _message = require("../utils/message");

var _base = require("./base");

var _request = require("./request");

var _utils2 = require("./utils");

var _excluded = ["trigger", "url", "customRequest", "method", "params", "data", "extendParams", "successMsg", "errorMsg", "formatParams", "formatResult", "onSuccess", "onError", "onOk", "onCancel", "hideFooter"],
    _excluded2 = ["title", "content", "component", "schema", "onFinish", "dialogType", "dialogQuickShowType", "messageType", "popType", "beforeRequest", "onTrigger", "link", "beforeContent", "afterContent", "message", "footerDescription", "footerAlign", "footer", "className"];

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

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); 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 = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

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 asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

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 _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

function addContextForReactNode(content, context) {
  if (typeof content === 'function' && context) {
    return content(context);
  }

  return content;
}

var FooterForm = function FooterForm(props) {
  var schema = props.schema,
      context = props.context,
      formRef = props.formRef;
  var form = (0, _react.useMemo)(function () {
    return (0, _form.createForm)();
  }, []);
  (0, _react.useEffect)(function () {
    formRef.current = form;
  }, []);
  return /*#__PURE__*/_react.default.createElement(_form.default, {
    layout: "inline",
    feedbackLayout: "none",
    form: form,
    context: context,
    schema: schema
  });
};

function getFooterAlignClass(isDrawer, align) {
  var footerAlign = align ? align : isDrawer ? 'left' : 'right';
  return "footer-align-".concat(footerAlign);
} // 弹窗 -> 请求（点击确认，发送数据请求）


function useDialogAction(action, actionContext, hasForm) {
  var _useState = (0, _react.useState)(false),
      _useState2 = _slicedToArray(_useState, 2),
      loading = _useState2[0],
      setLoading = _useState2[1];

  var footerDescriptionRef = (0, _react.useRef)();
  var history = (0, _reactRouterDom.useHistory)();

  var onActionStart = function onActionStart(context, e) {
    var _objectSpread2;

    var trigger = action.trigger,
        url = action.url,
        customRequest = action.customRequest,
        method = action.method,
        params = action.params,
        data = action.data,
        extendParams = action.extendParams,
        successMsg = action.successMsg,
        errorMsg = action.errorMsg,
        formatParams = action.formatParams,
        formatResult = action.formatResult,
        onSuccess = action.onSuccess,
        onError = action.onError,
        propsOnOk = action.onOk,
        propsOnCancel = action.onCancel,
        hideFooter = action.hideFooter,
        others = _objectWithoutProperties(action, _excluded);

    var _getTargetValue = (0, _utils.getTargetValue)(others, context),
        title = _getTargetValue.title,
        content = _getTargetValue.content,
        Component = _getTargetValue.component,
        schema = _getTargetValue.schema,
        onFinish = _getTargetValue.onFinish,
        dialogType = _getTargetValue.dialogType,
        dialogQuickShowType = _getTargetValue.dialogQuickShowType,
        _getTargetValue$messa = _getTargetValue.messageType,
        messageType = _getTargetValue$messa === void 0 ? 'notice' : _getTargetValue$messa,
        popType = _getTargetValue.popType,
        beforeRequest = _getTargetValue.beforeRequest,
        onTrigger = _getTargetValue.onTrigger,
        link = _getTargetValue.link,
        beforeContent = _getTargetValue.beforeContent,
        afterContent = _getTargetValue.afterContent,
        message = _getTargetValue.message,
        footerDescription = _getTargetValue.footerDescription,
        footerAlign = _getTargetValue.footerAlign,
        footer = _getTargetValue.footer,
        className = _getTargetValue.className,
        containerOtherProps = _objectWithoutProperties(_getTargetValue, _excluded2);

    var isDrawer = dialogType === 'drawer';
    var isPop = dialogType === 'pop';
    var container = isDrawer ? _components.Drawer : isPop ? _popConfirm.default : _components.Dialog;
    var containerProps = isDrawer ? {
      okText: (0, _utils.getMessage)('ok'),
      cancelText: (0, _utils.getMessage)('cancel'),
      closeable: !loading
    } : isPop ? {
      type: popType,
      trigger: e.currentTarget
    } : {
      type: dialogQuickShowType,
      messageProps: {
        type: messageType
      },
      closeable: !loading
    };

    var renderDialogFooterDescription = function renderDialogFooterDescription(footer) {
      if (footer instanceof Array || footer.component) {
        var _schema = footer instanceof Array ? footer : [footer];

        return /*#__PURE__*/_react.default.createElement(FooterForm, {
          formRef: footerDescriptionRef,
          context: context,
          schema: [{
            component: 'FormFlex',
            children: _schema
          }]
        });
      }

      return footer;
    };

    var onOk = function onOk() {
      return new Promise( /*#__PURE__*/function () {
        var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(resolve) {
          var _footerDescriptionRef;

          var footerDescriptionValues, requestContext;
          return regeneratorRuntime.wrap(function _callee$(_context) {
            while (1) {
              switch (_context.prev = _context.next) {
                case 0:
                  setLoading(true);
                  footerDescriptionValues = Object.assign({}, footerDescriptionRef === null || footerDescriptionRef === void 0 ? void 0 : (_footerDescriptionRef = footerDescriptionRef.current) === null || _footerDescriptionRef === void 0 ? void 0 : _footerDescriptionRef.values);
                  _context.prev = 2;
                  requestContext = Object.assign({
                    footer: footerDescriptionValues
                  }, context);
                  _context.next = 6;
                  return (0, _request.doRequest)(action, requestContext, history, footerDescriptionValues);

                case 6:
                  onFinish && onFinish();
                  propsOnOk && propsOnOk(context);
                  resolve(true);
                  _context.next = 19;
                  break;

                case 11:
                  _context.prev = 11;
                  _context.t0 = _context["catch"](2);
                  setLoading(false); // 如果 beforeRequest 中返回了 false 并且不是 dialog-form，则直接关闭弹窗

                  if (!(beforeRequest && !hasForm)) {
                    _context.next = 17;
                    break;
                  }

                  resolve(true);
                  return _context.abrupt("return");

                case 17:
                  resolve(false);
                  return _context.abrupt("return");

                case 19:
                case "end":
                  return _context.stop();
              }
            }
          }, _callee, null, [[2, 11]]);
        }));

        return function (_x) {
          return _ref.apply(this, arguments);
        };
      }());
    };

    var store = {
      hide: function hide() {}
    };

    var hide = function hide() {
      store.hide && store.hide();
    };

    var componentProps = schema ? schema : {};
    var dialogContext = Object.assign({}, context, {
      hide: hide
    });
    var dialogContent = Component ? /*#__PURE__*/_react.default.createElement(Component, _objectSpread({}, (0, _utils2.addContext)(componentProps, dialogContext))) : addContextForReactNode(content, dialogContext);

    var quickShowProps = _objectSpread(_objectSpread((_objectSpread2 = {}, _defineProperty(_objectSpread2, "".concat(isPop ? 'onConfirm' : 'onOk'), hideFooter && !isPop && isDrawer ? false : onOk), _defineProperty(_objectSpread2, "onCancel", hideFooter && !isPop && isDrawer ? false : function () {
      propsOnCancel && propsOnCancel(context);
    }), _defineProperty(_objectSpread2, "title", addContextForReactNode(title, dialogContext)), _defineProperty(_objectSpread2, "content", /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, beforeContent && /*#__PURE__*/_react.default.createElement("div", {
      className: "teamix-pro-dialog-before-content"
    }, addContextForReactNode(beforeContent, dialogContext)), message && /*#__PURE__*/_react.default.createElement("div", {
      className: "teamix-pro-dialog-message"
    }, (0, _message.renderProMessage)(message, {
      type: 'notice'
    })), dialogContent, afterContent && /*#__PURE__*/_react.default.createElement("div", {
      className: "teamix-pro-dialog-after-content"
    }, addContextForReactNode(afterContent, dialogContext)), !isPop && footerDescription && /*#__PURE__*/_react.default.createElement("div", {
      className: (0, _classnames.default)('teamix-pro-dialog-footer-description', getFooterAlignClass(isDrawer, footerAlign))
    }, renderDialogFooterDescription(footerDescription)))), _defineProperty(_objectSpread2, "footerAlign", footerAlign), _defineProperty(_objectSpread2, "className", (0, _classnames.default)('teamix-pro-action-dialog', {
      'has-footer-description': !!footerDescription
    })), _defineProperty(_objectSpread2, "footer", addContextForReactNode(footer, dialogContext)), _objectSpread2), containerProps), containerOtherProps); // TODO Drawer 基础组件未支持此配置，日后支持，并修改onOk、onCancel写法


    if ((!dialogType || dialogType === 'dialog') && hideFooter) {
      quickShowProps['footer'] = !hideFooter;
    }

    var ret = container.show(quickShowProps);
    store.hide = ret ? ret.hide || ret.close : function () {};
  };

  return _objectSpread({}, (0, _base.eventHandler)(action, actionContext, onActionStart));
}

var _default = useDialogAction;
exports.default = _default;