import "core-js/modules/es.promise.js";
import React, { useContext, useRef, useEffect, useImperativeHandle } from 'react';
import { noteOnce } from 'rc-util/es/warning';
import BaseForm from '../wau-base-form';
import StepsFormProvide from './step-form-context';
import { jsx as _jsx } from "react/jsx-runtime";
function StepForm({
  onFinish,
  step,
  formRef: propFormRef,
  ...restProps
}) {
  const formRef = useRef();
  const context = useContext(StepsFormProvide);
  noteOnce(
  // eslint-disable-next-line
  // @ts-expect-error
  !restProps.submitter, 'StepForm 不包含提交按钮，请在 StepsForm 上');
  /** 重置 formRef */
  useImperativeHandle(propFormRef, () => formRef.current);

  /** Dom 不存在的时候解除挂载 */
  useEffect(() => {
    return () => {
      if (restProps.name) {
        context === null || context === void 0 ? void 0 : context.unRegForm(restProps.name);
      }
    };
  }, []);
  if (context && context !== null && context !== void 0 && context.formArrayRef) {
    context.formArrayRef.current[step || 0] = formRef;
  }
  return /*#__PURE__*/_jsx(BaseForm, {
    formRef: formRef,
    onFinish: async values => {
      if (restProps.name) {
        context === null || context === void 0 ? void 0 : context.onFormFinish(restProps.name, values);
      }
      if (onFinish) {
        context === null || context === void 0 ? void 0 : context.setLoading(true);
        // 如果报错，直接抛出
        const success = await (onFinish === null || onFinish === void 0 ? void 0 : onFinish(values));
        if (success) {
          context === null || context === void 0 ? void 0 : context.next();
        }
        context === null || context === void 0 ? void 0 : context.setLoading(false);
        return;
      }
      context === null || context === void 0 ? void 0 : context.next();
    },
    layout: "vertical",
    ...restProps
  });
}
export default StepForm;