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, useEffect, useImperativeHandle, useState } from 'react';
import { useUrlSearchParams } from 'use-url-search-params';
import namePathSet from 'rc-util/es/utils/set';
import SizeContext from 'antd/es/config-provider/SizeContext';
import Form from '../form';
import { conversionSubmitValue, transformKeySubmitValue, useMountMergeState, runFunction } from '../utils';
import { ConfigProviderWrap } from '../wau-provider';
import FieldContext from '../wau-form/field-context';
import Submitter from '../wau-form/components/Submitter';
import './style';
import { jsx as _jsx } from "react/jsx-runtime";
import { jsxs as _jsxs } from "react/jsx-runtime";
const genParams = (syncUrl, params, type) => {
  if (syncUrl === true) {
    return params;
  }
  return runFunction(syncUrl, params, type);
};
function BaseForm(props) {
  const {
    children,
    contentRender,
    submitter,
    fieldProps,
    formItemProps,
    groupProps,
    dateFormatter = 'string',
    form: userForm,
    formRef: propsFormRef,
    onInit,
    syncToUrl,
    onReset,
    omitNil = true,
    isKeyPressSubmit,
    ...rest
  } = props;
  const [form] = Form.useForm();
  /** 同步 url 上的参数 */
  const [urlSearch, setUrlSearch] = useUrlSearchParams({}, {});
  const formRef = useRef(userForm || form);

  // 初始化给一个默认的 form
  useImperativeHandle(propsFormRef, () => formRef.current, []);
  const fieldsValueType = useRef({});
  /** 保存 transformKeyRef，用于对表单key transform */
  const transformKeyRef = useRef({});
  const [loading, setLoading] = useMountMergeState(false);

  /** 因为 protable 里面的值无法保证刚开始就存在 所以多进行了一次触发，这样可以解决部分问题 */
  const [isUpdate, updateState] = useMountMergeState(false);
  const items = React.Children.toArray(children);
  const submitterProps = typeof submitter === 'boolean' || !submitter ? {} : submitter;
  const transformKey = (values, omit) => transformKeySubmitValue(conversionSubmitValue(values, dateFormatter, fieldsValueType.current, omit), transformKeyRef.current);

  /** 渲染提交按钮与重置按钮 */
  const submitterNode = submitter === false ? undefined : /*#__PURE__*/_jsx(Submitter, {
    ...submitterProps,
    onReset: () => {
      var _submitterProps$onRes;
      const finalValues = transformKey(formRef.current.getFieldsValue(), omitNil);
      submitterProps === null || submitterProps === void 0 ? void 0 : (_submitterProps$onRes = submitterProps.onReset) === null || _submitterProps$onRes === void 0 ? void 0 : _submitterProps$onRes.call(submitterProps, finalValues);
      onReset === null || onReset === void 0 ? void 0 : onReset(finalValues);
      // 如果 syncToUrl，清空一下数据
      if (syncToUrl) {
        setUrlSearch(transformKey(formRef.current.getFieldsValue(), false));
      }
    },
    form: userForm || form,
    submitButtonProps: {
      loading,
      ...submitterProps.submitButtonProps
    }
  }, "submitter");
  const content = contentRender ? contentRender(items, submitterNode, formRef.current) : items;
  const forgetUpdate = () => {
    setTimeout(() => updateState(true));
  };
  useEffect(() => {
    if (isUpdate) {
      const finalValues = transformKey(formRef.current.getFieldsValue(), omitNil);
      onInit === null || onInit === void 0 ? void 0 : onInit(finalValues);
    }
  }, [dateFormatter, isUpdate]);

  // 如果为 false，不需要触发设置进去
  const [urlParamsMergeInitialValues] = useState(() => {
    if (!syncToUrl) {
      return {};
    }
    return genParams(syncToUrl, urlSearch, 'get');
  });
  return (
    /*#__PURE__*/
    // 增加国际化的能力，与 table 组件可以统一
    _jsx(ConfigProviderWrap, {
      children: /*#__PURE__*/_jsx(FieldContext.Provider, {
        value: {
          fieldProps,
          formItemProps,
          groupProps,
          setFieldValueType: (name, {
            valueType = 'text',
            transform
          }) => {
            if (Array.isArray(name)) {
              transformKeyRef.current = namePathSet(transformKeyRef.current, name, transform);
              fieldsValueType.current = namePathSet(fieldsValueType.current, name, valueType);
            } else {
              fieldsValueType.current[String(name)] = valueType;
              transformKeyRef.current[String(name)] = transform;
            }
          }
        },
        children: /*#__PURE__*/_jsx(SizeContext.Provider, {
          value: rest.size,
          children: /*#__PURE__*/_jsxs(Form, {
            onKeyPress: event => {
              if (!isKeyPressSubmit) return;
              if (event.key === 'Enter') {
                var _formRef$current;
                (_formRef$current = formRef.current) === null || _formRef$current === void 0 ? void 0 : _formRef$current.submit();
              }
            },
            form: userForm || form,
            ...rest,
            // 组合 urlSearch 和 initialValues
            initialValues: {
              ...urlParamsMergeInitialValues,
              ...rest.initialValues
            },
            onFinish: async () => {
              if (!rest.onFinish) {
                return;
              }
              setLoading(true);
              try {
                const finalValues = transformKey(formRef.current.getFieldsValue(), omitNil);
                await rest.onFinish(finalValues);
                if (syncToUrl) {
                  // 把没有的值设置为未定义可以删掉 url 的参数
                  const params = Object.keys(transformKey(formRef.current.getFieldsValue(), false)).reduce((pre, next) => {
                    return {
                      ...pre,
                      [next]: finalValues[next] || undefined
                    };
                  }, {});
                  /** 在同步到 url 上时对参数进行转化 */
                  setUrlSearch(genParams(syncToUrl, params, 'set'));
                }
                setLoading(false);
              } catch (error) {
                // console.log(error);
                setLoading(false);
              }
            },
            children: [/*#__PURE__*/_jsx("input", {
              type: "text",
              style: {
                display: 'none'
              }
            }), /*#__PURE__*/_jsx(Form.Item, {
              noStyle: true,
              shouldUpdate: true,
              children: formInstance => {
                // 支持 fromRef，这里 ref 里面可以随时拿到最新的值
                if (propsFormRef && !isUpdate) forgetUpdate();
                if (propsFormRef) propsFormRef.current = formInstance;
                formRef.current = formInstance;
                return null;
              }
            }), content]
          })
        })
      })
    })
  );
}
export default BaseForm;