"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 _useUrlSearchParams = require("use-url-search-params");
var _set = _interopRequireDefault(require("rc-util/es/utils/set"));
var _SizeContext = _interopRequireDefault(require("antd/es/config-provider/SizeContext"));
var _form = _interopRequireDefault(require("../form"));
var _utils = require("../utils");
var _wauProvider = require("../wau-provider");
var _fieldContext = _interopRequireDefault(require("../wau-form/field-context"));
var _Submitter = _interopRequireDefault(require("../wau-form/components/Submitter"));
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; }
const genParams = (syncUrl, params, type) => {
  if (syncUrl === true) {
    return params;
  }
  return (0, _utils.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.default.useForm();
  /** 同步 url 上的参数 */
  const [urlSearch, setUrlSearch] = (0, _useUrlSearchParams.useUrlSearchParams)({}, {});
  const formRef = (0, _react.useRef)(userForm || form);

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

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

  /** 渲染提交按钮与重置按钮 */
  const submitterNode = submitter === false ? undefined : /*#__PURE__*/(0, _jsxRuntime.jsx)(_Submitter.default, {
    ...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));
  };
  (0, _react.useEffect)(() => {
    if (isUpdate) {
      const finalValues = transformKey(formRef.current.getFieldsValue(), omitNil);
      onInit === null || onInit === void 0 ? void 0 : onInit(finalValues);
    }
  }, [dateFormatter, isUpdate]);

  // 如果为 false，不需要触发设置进去
  const [urlParamsMergeInitialValues] = (0, _react.useState)(() => {
    if (!syncToUrl) {
      return {};
    }
    return genParams(syncToUrl, urlSearch, 'get');
  });
  return (
    /*#__PURE__*/
    // 增加国际化的能力，与 table 组件可以统一
    (0, _jsxRuntime.jsx)(_wauProvider.ConfigProviderWrap, {
      children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_fieldContext.default.Provider, {
        value: {
          fieldProps,
          formItemProps,
          groupProps,
          setFieldValueType: (name, {
            valueType = 'text',
            transform
          }) => {
            if (Array.isArray(name)) {
              transformKeyRef.current = (0, _set.default)(transformKeyRef.current, name, transform);
              fieldsValueType.current = (0, _set.default)(fieldsValueType.current, name, valueType);
            } else {
              fieldsValueType.current[String(name)] = valueType;
              transformKeyRef.current[String(name)] = transform;
            }
          }
        },
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_SizeContext.default.Provider, {
          value: rest.size,
          children: /*#__PURE__*/(0, _jsxRuntime.jsxs)(_form.default, {
            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__*/(0, _jsxRuntime.jsx)("input", {
              type: "text",
              style: {
                display: 'none'
              }
            }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_form.default.Item, {
              noStyle: true,
              shouldUpdate: true,
              children: formInstance => {
                // 支持 fromRef，这里 ref 里面可以随时拿到最新的值
                if (propsFormRef && !isUpdate) forgetUpdate();
                if (propsFormRef) propsFormRef.current = formInstance;
                formRef.current = formInstance;
                return null;
              }
            }), content]
          })
        })
      })
    })
  );
}
var _default = BaseForm;
exports.default = _default;