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/dataSourceSubForm/index.tsx
var dataSourceSubForm_exports = {};
__export(dataSourceSubForm_exports, {
  default: () => dataSourceSubForm_default
});
module.exports = __toCommonJS(dataSourceSubForm_exports);
var import_react = __toESM(require("react"));
var import_antd = require("antd");
var import_ahooks = require("ahooks");
var import_classnames = __toESM(require("classnames"));
var import_JsonWrapperContext = __toESM(require("../dataSourceForm/provider/jsonWrapper/JsonWrapperContext"));
var import_DataSourceProvider = __toESM(require("../provider/dataSource/DataSourceProvider"));
var import_FormSettingProvider = __toESM(require("../dataSourceForm/provider/formSetting/FormSettingProvider"));
var getI18nText = (value) => {
  if (value === null || value === void 0) {
    return "";
  }
  if (typeof value === "string" || typeof value === "number") {
    return `${value}`;
  }
  if (typeof value === "object") {
    return value.original || value["zh-CN"] || value.en || value["zh-HK"] || value.ja || value.pt || "";
  }
  return "";
};
var normalizeRecordSchema = (xRecordSchema) => {
  if (!xRecordSchema) {
    return [];
  }
  let rawSchema = xRecordSchema;
  if (typeof xRecordSchema === "string") {
    try {
      rawSchema = JSON.parse(xRecordSchema);
    } catch (error) {
      console.error("Failed to parse xRecordSchema:", error);
      return [];
    }
  }
  if (rawSchema && typeof rawSchema === "object" && !Array.isArray(rawSchema) && rawSchema.name) {
    rawSchema = [rawSchema];
  }
  const normalizeSingleField = (field, fallbackName) => {
    var _a;
    const uiSchema = (field == null ? void 0 : field.uiSchema) || {};
    const name = (field == null ? void 0 : field.name) || fallbackName;
    if (!name) {
      return null;
    }
    const component = (uiSchema == null ? void 0 : uiSchema["x-component"]) || (field == null ? void 0 : field.interface) || (field == null ? void 0 : field.componentName) || (field == null ? void 0 : field.component) || "Input";
    const props = {
      ...(uiSchema == null ? void 0 : uiSchema["x-component-props"]) || {},
      ...(field == null ? void 0 : field.props) || {}
    };
    const uiSchemaDataSourceOptions = ((_a = uiSchema == null ? void 0 : uiSchema["x-data-source"]) == null ? void 0 : _a.options) || [];
    const rawOptions = uiSchemaDataSourceOptions.length ? uiSchemaDataSourceOptions : (uiSchema == null ? void 0 : uiSchema.enum) || (field == null ? void 0 : field.options) || (props == null ? void 0 : props.options) || [];
    const options = rawOptions.map((option) => {
      if (typeof option === "string" || typeof option === "number") {
        return { label: option, value: option };
      }
      return { ...option, label: getI18nText(option == null ? void 0 : option.label) || (option == null ? void 0 : option.value) };
    });
    if (component === "Select" && (field == null ? void 0 : field.type) === "array" && !(props == null ? void 0 : props.mode)) {
      props.mode = "multiple";
    }
    return {
      ...field,
      name,
      label: getI18nText(field == null ? void 0 : field.label) || getI18nText(uiSchema == null ? void 0 : uiSchema.title) || name,
      component,
      componentName: component,
      options,
      props,
      uiSchema
    };
  };
  if (Array.isArray(rawSchema)) {
    return rawSchema.map((item) => normalizeSingleField(item)).filter(Boolean);
  }
  if (Array.isArray(rawSchema == null ? void 0 : rawSchema.fields)) {
    return rawSchema.fields.map((item) => normalizeSingleField(item)).filter(Boolean);
  }
  if (Array.isArray(rawSchema == null ? void 0 : rawSchema.children)) {
    return rawSchema.children.map((item) => normalizeSingleField(item)).filter(Boolean);
  }
  if ((rawSchema == null ? void 0 : rawSchema.properties) && typeof rawSchema.properties === "object") {
    return Object.keys(rawSchema.properties).map((name) => normalizeSingleField(rawSchema.properties[name], name)).filter(Boolean);
  }
  return [];
};
var DataSourceSubForm = (0, import_react.forwardRef)((props, ref) => {
  const {
    activeKey,
    value = {},
    onChange,
    children,
    xRecordSchema,
    renderMode = "edit",
    __designMode,
    className,
    style
  } = props;
  const [innerForm] = import_antd.Form.useForm();
  const activeKeyRef = (0, import_react.useRef)(activeKey);
  const safeValue = (0, import_react.useMemo)(() => {
    if (value && typeof value === "object" && !Array.isArray(value)) {
      return value;
    }
    return {};
  }, [value]);
  (0, import_react.useImperativeHandle)(ref, () => {
    return {
      getFieldsValue: () => {
        return innerForm.getFieldsValue();
      }
    };
  });
  (0, import_react.useEffect)(() => {
    if (activeKeyRef.current !== activeKey) {
      activeKeyRef.current = activeKey;
      innerForm.resetFields();
    }
    innerForm.setFieldsValue(safeValue);
  }, [safeValue, innerForm, activeKey]);
  const handleValuesChange = (0, import_ahooks.useMemoizedFn)(
    (_, allValues) => {
      onChange == null ? void 0 : onChange({ ...safeValue, ...allValues });
    }
  );
  const fields = (0, import_react.useMemo)(
    () => normalizeRecordSchema(xRecordSchema),
    [xRecordSchema]
  );
  const hasRealChildren = (0, import_react.useMemo)(() => {
    const childArray = import_react.default.Children.toArray(children);
    if (childArray.length === 0) return false;
    return childArray.some((child) => import_react.default.isValidElement(child));
  }, [children]);
  const mockDataSource = (0, import_react.useMemo)(() => {
    if (!fields || fields.length === 0) return null;
    return {
      fields: fields.map((field) => ({
        name: field.name,
        uiSchema: field.uiSchema,
        interface: field.interface
      })),
      name: "dataSourceSubForm",
      tableName: "dataSourceSubForm"
    };
  }, [fields]);
  const renderFormContent = () => {
    if (!hasRealChildren && fields.length === 0) {
      return /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-data-source-sub-form__empty" }, "No fields configured. Please configure xRecordSchema or add children components.");
    }
    const formContent = /* @__PURE__ */ import_react.default.createElement(import_JsonWrapperContext.default.Provider, { value: { path: [], level: 0 } }, /* @__PURE__ */ import_react.default.createElement(
      import_antd.Form,
      {
        form: innerForm,
        onValuesChange: handleValuesChange,
        component: false,
        layout: "vertical"
      },
      children
    ));
    if (mockDataSource) {
      return /* @__PURE__ */ import_react.default.createElement(
        import_FormSettingProvider.default,
        {
          renderMode,
          groupInfoPosition: "top",
          size: "large"
        },
        /* @__PURE__ */ import_react.default.createElement(
          import_DataSourceProvider.default,
          {
            dataSource: mockDataSource,
            __designMode
          },
          formContent
        )
      );
    }
    return /* @__PURE__ */ import_react.default.createElement(
      import_FormSettingProvider.default,
      {
        renderMode,
        groupInfoPosition: "top",
        size: "large"
      },
      formContent
    );
  };
  return /* @__PURE__ */ import_react.default.createElement(
    "div",
    {
      className: (0, import_classnames.default)("pisell-data-source-sub-form", className),
      style
    },
    renderFormContent()
  );
});
var dataSourceSubForm_default = DataSourceSubForm;
