import "core-js/modules/es.array.iterator.js";
import "core-js/modules/web.dom-collections.iterator.js";
import "core-js/modules/es.promise.js";
import "core-js/modules/es.array.reduce.js";
import React, { useRef, useCallback, useEffect, useContext, useImperativeHandle } from 'react';
import toArray from 'rc-util/es/Children/toArray';
import useMergedState from 'rc-util/es/hooks/useMergedState';
import classNames from 'classnames';
import Form from '../form';
import Steps from '../steps';
import ConfigProvider from '../config-provider';
import Button from '../button';
import Space from '../space';
import { useIntl } from '../wau-provider';
import { useMountMergeState } from '../utils';
import StepsFormProvide from './step-form-context';
import StepForm from './step-form';
import './style';
import { jsx as _jsx } from "react/jsx-runtime";
import { Fragment as _Fragment } from "react/jsx-runtime";
import { jsxs as _jsxs } from "react/jsx-runtime";
function StepsForm(props) {
  var _formArrayRef$current;
  const {
    getPrefixCls
  } = useContext(ConfigProvider.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 = useRef(new Map());
  const formMapRef = useRef(new Map());
  const formArrayRef = useRef([]);
  const [formArray, setFormArray] = useMountMergeState([]);
  const [loading, setLoading] = useMountMergeState(false);
  const intl = useIntl();

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

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

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

  /** Children 计算完成之后，重新生成一下当前的步骤列表 */
  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;
  useImperativeHandle(propsFormMapRef, () => formArrayRef.current);
  useImperativeHandle(formRef, () => currentFormRef);

  /** ProForm处理了一下 from 的数据，在其中做了一些操作 如果使用 Provider 自带的，自带的数据处理就无法生效了 */
  const onFormFinish = 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__*/_jsx("div", {
    className: `${prefixCls}-steps-container`,
    style: {
      maxWidth: Math.min(formArray.length * 320, 1160)
    },
    children: /*#__PURE__*/_jsx(Steps, {
      ...stepsProps,
      current: step,
      onChange: undefined,
      children: formArray.map(item => {
        const itemProps = formMapRef.current.get(item);
        return /*#__PURE__*/_jsx(Steps.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__*/_jsx(Button, {
    type: "primary",
    loading: loading,
    ...(submitter === null || submitter === void 0 ? void 0 : submitter.submitButtonProps),
    onClick: () => {
      var _submitter$onSubmit;
      submitter === null || submitter === void 0 ? 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__*/_jsx(Button, {
    ...(submitter === null || submitter === void 0 ? void 0 : submitter.resetButtonProps),
    onClick: () => {
      var _submitter$onReset;
      // 没有判断是因为 step<1 这个按钮不显示
      setStep(step - 1);
      submitter === null || submitter === void 0 ? 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__*/_jsx(Button, {
    type: "primary",
    loading: loading,
    ...(submitter === null || submitter === void 0 ? void 0 : submitter.submitButtonProps),
    onClick: () => {
      var _submitter$onSubmit2;
      submitter === null || submitter === void 0 ? 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 = toArray(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__*/_jsx("div", {
      className: classNames(`${prefixCls}-step`, {
        [`${prefixCls}-step-active`]: isShow
      }),
      children: /*#__PURE__*/React.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__*/_jsx("div", {
    className: prefixCls,
    children: /*#__PURE__*/_jsx(Form.Provider, {
      ...rest,
      children: /*#__PURE__*/_jsx(StepsFormProvide.Provider, {
        value: {
          loading,
          setLoading,
          keyArray: formArray,
          next: () => {
            if (step > formArray.length - 2) {
              return;
            }
            setStep(step + 1);
          },
          formArrayRef,
          formMapRef,
          unRegForm,
          onFormFinish
        },
        children: stepsFormRender ? stepsFormRender( /*#__PURE__*/_jsxs(_Fragment, {
          children: [finalStepsDom, /*#__PURE__*/_jsx("div", {
            className: `${prefixCls}-container`,
            style: containerStyle,
            children: formDom
          })]
        }), submitterDom) : /*#__PURE__*/_jsxs(_Fragment, {
          children: [finalStepsDom, /*#__PURE__*/_jsxs("div", {
            className: `${prefixCls}-container`,
            style: containerStyle,
            children: [formDom, /*#__PURE__*/_jsx(Space, {
              children: renderSubmitter()
            })]
          })]
        })
      })
    })
  });
}
StepsForm.StepForm = StepForm;
StepsForm.useForm = Form.useForm;
export default StepsForm;