"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
require("core-js/modules/es.array.iterator.js");
require("core-js/modules/web.dom-collections.iterator.js");
require("core-js/modules/es.promise.js");
require("core-js/modules/es.array.reduce.js");
var _react = _interopRequireWildcard(require("react"));
var _toArray = _interopRequireDefault(require("rc-util/es/Children/toArray"));
var _useMergedState = _interopRequireDefault(require("rc-util/es/hooks/useMergedState"));
var _classnames = _interopRequireDefault(require("classnames"));
var _form = _interopRequireDefault(require("../form"));
var _steps = _interopRequireDefault(require("../steps"));
var _configProvider = _interopRequireDefault(require("../config-provider"));
var _button = _interopRequireDefault(require("../button"));
var _space = _interopRequireDefault(require("../space"));
var _wauProvider = require("../wau-provider");
var _utils = require("../utils");
var _stepFormContext = _interopRequireDefault(require("./step-form-context"));
var _stepForm = _interopRequireDefault(require("./step-form"));
require("./style");
var _jsxRuntime = require("react/jsx-runtime");
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (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 StepsForm(props) {
  var _formArrayRef$current;
  const {
    getPrefixCls
  } = (0, _react.useContext)(_configProvider.default.ConfigContext);
  const prefixCls = getPrefixCls('pro-steps-form');
  const {
    // eslint-disable-next-line
    current,
    // eslint-disable-next-line
    onCurrentChange,
    submitter,
    stepsFormRender,
    // eslint-disable-next-line
    stepsRender,
    stepFormRender,
    stepsProps,
    // eslint-disable-next-line
    onFinish,
    formProps,
    containerStyle,
    formRef,
    formMapRef: propsFormMapRef,
    ...rest
  } = props;
  const formDataRef = (0, _react.useRef)(new Map());
  const formMapRef = (0, _react.useRef)(new Map());
  const formArrayRef = (0, _react.useRef)([]);
  const [formArray, setFormArray] = (0, _utils.useMountMergeState)([]);
  const [loading, setLoading] = (0, _utils.useMountMergeState)(false);
  const intl = (0, _wauProvider.useIntl)();

  /** 受控的方式来操作表单 */
  const [step, setStep] = (0, _useMergedState.default)(0, {
    value: props.current,
    onChange: props.onCurrentChange
  });

  /** 注册一个form进入，方便进行 props 的修改 */
  const regForm = (0, _react.useCallback)((name, childrenFormProps) => {
    formMapRef.current.set(name, childrenFormProps);
  }, []);

  /** 接触挂载掉这个 form，同时步数 -1 */
  const unRegForm = (0, _react.useCallback)(name => {
    formMapRef.current.delete(name);
    formDataRef.current.delete(name);
  }, []);

  /** Children 计算完成之后，重新生成一下当前的步骤列表 */
  (0, _react.useEffect)(() => {
    setFormArray(Array.from(formMapRef.current.keys()));
  }, [Array.from(formMapRef.current.keys()).join(',')]);
  const currentFormRef = (_formArrayRef$current = formArrayRef.current[step || 0]) === null || _formArrayRef$current === void 0 ? void 0 : _formArrayRef$current.current;
  (0, _react.useImperativeHandle)(propsFormMapRef, () => formArrayRef.current);
  (0, _react.useImperativeHandle)(formRef, () => currentFormRef);

  /** ProForm处理了一下 from 的数据，在其中做了一些操作 如果使用 Provider 自带的，自带的数据处理就无法生效了 */
  const onFormFinish = (0, _react.useCallback)(async (name, formData) => {
    formDataRef.current.set(name, formData);
    // 如果是最后一步
    if (step === formMapRef.current.size - 1 || formMapRef.current.size === 0) {
      if (!props.onFinish) {
        return;
      }
      setLoading(true);
      const values = Array.from(formDataRef.current.values()).reduce((pre, cur) => {
        return {
          ...pre,
          ...cur
        };
      }, {});
      try {
        const success = await props.onFinish(values);
        if (success) {
          setStep(0);
          formArrayRef.current.forEach(form => {
            var _form$current;
            return (_form$current = form.current) === null || _form$current === void 0 ? void 0 : _form$current.resetFields();
          });
        }
      } catch (error) {
        // eslint-disable-next-line no-console
        console.log(error);
      } finally {
        setLoading(false);
      }
    }
  }, [step]);
  const stepsDom = /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
    className: `${prefixCls}-steps-container`,
    style: {
      maxWidth: Math.min(formArray.length * 320, 1160)
    },
    children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_steps.default, {
      ...stepsProps,
      current: step,
      onChange: undefined,
      children: formArray.map(item => {
        const itemProps = formMapRef.current.get(item);
        return /*#__PURE__*/(0, _jsxRuntime.jsx)(_steps.default.Step, {
          title: itemProps === null || itemProps === void 0 ? void 0 : itemProps.title
        }, item);
      })
    })
  });
  const onSubmit = () => {
    var _from$current;
    const from = formArrayRef.current[step];
    (_from$current = from.current) === null || _from$current === void 0 ? void 0 : _from$current.submit();
  };
  const next = submitter !== false && /*#__PURE__*/(0, _jsxRuntime.jsx)(_button.default, {
    type: "primary",
    loading: loading,
    ...(submitter === null || submitter === void 0 ? void 0 : submitter.submitButtonProps),
    onClick: () => {
      var _submitter$onSubmit;
      submitter === null || submitter === void 0 || (_submitter$onSubmit = submitter.onSubmit) === null || _submitter$onSubmit === void 0 ? void 0 : _submitter$onSubmit.call(submitter);
      onSubmit();
    },
    children: intl.getMessage('stepsForm.next', '下一步')
  }, "next");
  const pre = submitter !== false && /*#__PURE__*/(0, _jsxRuntime.jsx)(_button.default, {
    ...(submitter === null || submitter === void 0 ? void 0 : submitter.resetButtonProps),
    onClick: () => {
      var _submitter$onReset;
      // 没有判断是因为 step<1 这个按钮不显示
      setStep(step - 1);
      submitter === null || submitter === void 0 || (_submitter$onReset = submitter.onReset) === null || _submitter$onReset === void 0 ? void 0 : _submitter$onReset.call(submitter);
    },
    children: intl.getMessage('stepsForm.prev', '上一步')
  }, "pre");
  const submit = submitter !== false && /*#__PURE__*/(0, _jsxRuntime.jsx)(_button.default, {
    type: "primary",
    loading: loading,
    ...(submitter === null || submitter === void 0 ? void 0 : submitter.submitButtonProps),
    onClick: () => {
      var _submitter$onSubmit2;
      submitter === null || submitter === void 0 || (_submitter$onSubmit2 = submitter.onSubmit) === null || _submitter$onSubmit2 === void 0 ? void 0 : _submitter$onSubmit2.call(submitter);
      onSubmit();
    },
    children: intl.getMessage('stepsForm.submit', '提交')
  }, "submit");
  const getActionButton = () => {
    const index = step || 0;
    if (index < 1) {
      return [next];
    }
    if (index + 1 === formArray.length) {
      return [pre, submit];
    }
    return [pre, next];
  };
  const renderSubmitter = () => {
    const submitterDom = getActionButton();
    if (submitter && submitter.render) {
      var _formArrayRef$current2;
      const submitterProps = {
        form: (_formArrayRef$current2 = formArrayRef.current[step]) === null || _formArrayRef$current2 === void 0 ? void 0 : _formArrayRef$current2.current,
        onSubmit,
        step,
        onPre: () => {
          if (step < 1) {
            return;
          }
          setStep(step - 1);
        }
      };
      return submitter.render(submitterProps, submitterDom);
    }
    if (submitter && (submitter === null || submitter === void 0 ? void 0 : submitter.render) === false) {
      return null;
    }
    return submitterDom;
  };
  const formDom = (0, _toArray.default)(props.children).map((item, index) => {
    const itemProps = item.props;
    const name = itemProps.name || `${index}`;
    regForm(name, itemProps);
    /** 是否是当前的表单 */
    const isShow = step === index;
    const config = isShow ? {
      contentRender: stepFormRender,
      submitter: false
    } : {};
    return /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
      className: (0, _classnames.default)(`${prefixCls}-step`, {
        [`${prefixCls}-step-active`]: isShow
      }),
      children: /*#__PURE__*/_react.default.cloneElement(item, {
        ...config,
        ...formProps,
        ...itemProps,
        name,
        step: index,
        key: name
      })
    }, name);
  });
  const finalStepsDom = props.stepsRender ? props.stepsRender(formArray.map(item => {
    var _formMapRef$current$g;
    return {
      key: item,
      title: (_formMapRef$current$g = formMapRef.current.get(item)) === null || _formMapRef$current$g === void 0 ? void 0 : _formMapRef$current$g.title
    };
  }), stepsDom) : stepsDom;
  const submitterDom = renderSubmitter();
  return /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
    className: prefixCls,
    children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_form.default.Provider, {
      ...rest,
      children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_stepFormContext.default.Provider, {
        value: {
          loading,
          setLoading,
          keyArray: formArray,
          next: () => {
            if (step > formArray.length - 2) {
              return;
            }
            setStep(step + 1);
          },
          formArrayRef,
          formMapRef,
          unRegForm,
          onFormFinish
        },
        children: stepsFormRender ? stepsFormRender( /*#__PURE__*/(0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
          children: [finalStepsDom, /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
            className: `${prefixCls}-container`,
            style: containerStyle,
            children: formDom
          })]
        }), submitterDom) : /*#__PURE__*/(0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
          children: [finalStepsDom, /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
            className: `${prefixCls}-container`,
            style: containerStyle,
            children: [formDom, /*#__PURE__*/(0, _jsxRuntime.jsx)(_space.default, {
              children: renderSubmitter()
            })]
          })]
        })
      })
    })
  });
}
StepsForm.StepForm = _stepForm.default;
StepsForm.useForm = _form.default.useForm;
var _default = StepsForm;
exports.default = _default;