var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/components/dataSourceComponents/dataSourceForm/BaseForm.tsx
var BaseForm_exports = {};
__export(BaseForm_exports, {
  default: () => BaseForm_default
});
module.exports = __toCommonJS(BaseForm_exports);
var import_react = __toESM(require("react"));
var import_classnames = __toESM(require("classnames"));
var import_ahooks = require("ahooks");
var import_pisellModal = __toESM(require("../../pisellModal"));
var import_useCtxActions = __toESM(require("../hooks/useCtxActions"));
var import_useDataSource = __toESM(require("../hooks/useDataSource"));
var import_useEngineContext = __toESM(require("../../../hooks/useEngineContext"));
var import_form = __toESM(require("../../form"));
var import_FormSettingProvider = __toESM(require("./provider/formSetting/FormSettingProvider"));
var import_page_header = __toESM(require("../../page-header"));
var import_utils = require("./utils");
var import_serve = require("./serve");
var import_useFormSettingParams = __toESM(require("../hooks/useFormSettingParams"));
var import_index = require("./index.less");
var import_utils2 = require("@pisell/utils");
var BaseForm = (0, import_react.forwardRef)(
  (props, ref) => {
    var _a;
    const {
      title,
      description,
      dataSource,
      showTitle,
      showDescription,
      groupInfoPosition,
      variables,
      renderMode,
      children,
      currentValue,
      className,
      onDataSourceFinish,
      formatSubmitValues,
      formatInitialValues,
      customSubmit,
      beforeSubmit,
      leaveConfirmConfig,
      ...others
    } = props;
    const context = (0, import_useEngineContext.default)();
    const { setBeforeClose } = (0, import_useCtxActions.default)();
    const { getApp } = (_a = context.appHelper) == null ? void 0 : _a.utils;
    const { scope, target } = (0, import_useFormSettingParams.default)();
    const formRef = (0, import_react.useRef)(null);
    const { get } = (0, import_useDataSource.default)();
    (0, import_react.useEffect)(() => {
      var _a2;
      const isDesignMode = props.__designMode === "design";
      if (isDesignMode) {
        (_a2 = formRef.current) == null ? void 0 : _a2.resetFields();
      }
    }, [dataSource, props.__designMode]);
    (0, import_react.useEffect)(() => {
      document.body.id = "body";
    }, []);
    (0, import_react.useImperativeHandle)(ref, () => formRef.current);
    (0, import_react.useEffect)(() => {
      var _a2;
      if (["edit", "view"].includes(renderMode || "") && dataSource) {
        if (dataSource == null ? void 0 : dataSource.fromSettingMeta) {
          if (props.__designMode === "design") return;
          const sectionCodes = Array.from(new Set((_a2 = dataSource == null ? void 0 : dataSource.fields) == null ? void 0 : _a2.map((field) => field.name.split(".").shift())));
          (0, import_serve.getFormSettingMetaData)({ sectionCodes, scope, target }).then((res) => {
            var _a3, _b;
            const formattedValues = formatInitialValues ? formatInitialValues(res.data) : res.data || {};
            const fieldNames = new Set(((_a3 = dataSource == null ? void 0 : dataSource.fields) == null ? void 0 : _a3.map((field) => field.name)) || []);
            const filteredValues = Object.keys(formattedValues).reduce((acc, key) => {
              if (fieldNames.has(key)) {
                acc[key] = formattedValues[key];
              }
              return acc;
            }, {});
            (_b = formRef.current) == null ? void 0 : _b.setFields((0, import_utils.transformFormObjToArrayWithUntouched)({
              ...filteredValues
            }));
          }).catch((error) => {
            console.error("获取formSettingMeta数据失败:", error);
          });
          return;
        }
        get == null ? void 0 : get.runAsync().then((res) => {
          var _a3, _b;
          const formattedValues = formatInitialValues ? formatInitialValues(res) : res;
          let values = formattedValues;
          if ((0, import_utils2.isArr)(dataSource == null ? void 0 : dataSource.fields)) {
            const fieldNames = new Set(((_a3 = dataSource == null ? void 0 : dataSource.fields) == null ? void 0 : _a3.map((field) => field.name)) || []);
            values = Object.keys(formattedValues).reduce((acc, key) => {
              if (fieldNames.has(key)) {
                acc[key] = formattedValues[key];
              }
              return acc;
            }, {});
          }
          (_b = formRef.current) == null ? void 0 : _b.setFields((0, import_utils.transformFormObjToArrayWithUntouched)(values));
        });
      }
    }, [renderMode, dataSource]);
    const checkFormClose = (0, import_ahooks.useMemoizedFn)(async () => {
      var _a2;
      const isFormChanged = (_a2 = formRef.current) == null ? void 0 : _a2.isFieldsTouched();
      if (isFormChanged) {
        return new Promise((resolve) => {
          import_pisellModal.default.confirm({
            title: leaveConfirmConfig == null ? void 0 : leaveConfirmConfig.title,
            content: leaveConfirmConfig == null ? void 0 : leaveConfirmConfig.content,
            okText: leaveConfirmConfig == null ? void 0 : leaveConfirmConfig.okText,
            cancelText: leaveConfirmConfig == null ? void 0 : leaveConfirmConfig.cancelText,
            onOk: () => {
              var _a3;
              (_a3 = formRef.current) == null ? void 0 : _a3.resetFields();
              resolve(true);
            },
            onCancel: () => {
              resolve(false);
            }
          });
        });
      }
      return true;
    });
    (0, import_react.useEffect)(() => {
      if (leaveConfirmConfig == null ? void 0 : leaveConfirmConfig.enable) {
        setBeforeClose == null ? void 0 : setBeforeClose(checkFormClose);
      }
    }, [leaveConfirmConfig]);
    (0, import_react.useEffect)(() => {
      var _a2, _b;
      if (leaveConfirmConfig == null ? void 0 : leaveConfirmConfig.enable) {
        const history = (_b = (_a2 = getApp == null ? void 0 : getApp()) == null ? void 0 : _a2.history) == null ? void 0 : _b.instance;
        let unblock = history == null ? void 0 : history.block((location, action) => {
          var _a3;
          const isFormChanged = (_a3 = formRef.current) == null ? void 0 : _a3.isFieldsTouched();
          if (isFormChanged) {
            import_pisellModal.default.confirm({
              title: leaveConfirmConfig.title,
              content: leaveConfirmConfig.content,
              okText: leaveConfirmConfig.okText,
              cancelText: leaveConfirmConfig.cancelText,
              onOk: () => {
                unblock == null ? void 0 : unblock();
                if (action === "PUSH") {
                  history.push(location);
                } else if (action === "POP") {
                  history.go(-1);
                } else if (action === "REPLACE") {
                  history.replace(location);
                }
              },
              onCancel: () => {
              }
            });
            return false;
          }
          return true;
        });
        return () => {
          unblock == null ? void 0 : unblock();
        };
      }
    }, []);
    return /* @__PURE__ */ import_react.default.createElement(
      import_FormSettingProvider.default,
      {
        renderMode,
        groupInfoPosition,
        currentValue,
        size: others.size,
        onDataSourceFinish,
        formatSubmitValues,
        formatInitialValues,
        customSubmit,
        beforeSubmit
      },
      /* @__PURE__ */ import_react.default.createElement(
        import_form.default,
        {
          ...others,
          className: (0, import_classnames.default)("pisell-lowcode-data-source-form", className),
          ref: formRef,
          preserve: true
        },
        /* @__PURE__ */ import_react.default.createElement(
          import_page_header.default,
          {
            title,
            showTitle,
            subTitle: description,
            showSubTitle: showDescription
          }
        ),
        children
      )
    );
  }
);
var BaseForm_default = BaseForm;
