const require_runtime = require("../../../_virtual/_rolldown/runtime.js");
const require_objectSpread2 = require("../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js");
const require_JsonWrapperContext = require("../dataSourceForm/provider/jsonWrapper/JsonWrapperContext.js");
const require_DataSourceProvider = require("../provider/dataSource/DataSourceProvider.js");
const require_FormSettingProvider = require("../dataSourceForm/provider/formSetting/FormSettingProvider.js");
let react = require("react");
react = require_runtime.__toESM(react);
let antd = require("antd");
let classnames = require("classnames");
classnames = require_runtime.__toESM(classnames);
let ahooks = require("ahooks");
//#region src/components/dataSourceComponents/dataSourceSubForm/index.tsx
/**
* @title 提取多语言文本
* @description 兼容字符串、数字、多语言对象格式，返回可显示文本
*/
const 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 "";
};
/**
* @title 解析并规范化 xRecordSchema
* @description 兼容字符串、数组、properties 和 fields 结构，统一成字段数组供渲染使用
*/
const 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];
	/**
	* @title 规范化单个字段
	* @description 将各种格式的字段配置统一转换为标准格式
	*/
	const normalizeSingleField = (field, fallbackName) => {
		var _uiSchema$xDataSour;
		const uiSchema = (field === null || field === void 0 ? void 0 : field.uiSchema) || {};
		const name = (field === null || field === void 0 ? void 0 : field.name) || fallbackName;
		if (!name) return null;
		const component = (uiSchema === null || uiSchema === void 0 ? void 0 : uiSchema["x-component"]) || (field === null || field === void 0 ? void 0 : field.interface) || (field === null || field === void 0 ? void 0 : field.componentName) || (field === null || field === void 0 ? void 0 : field.component) || "Input";
		const props = require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, (uiSchema === null || uiSchema === void 0 ? void 0 : uiSchema["x-component-props"]) || {}), (field === null || field === void 0 ? void 0 : field.props) || {});
		const uiSchemaDataSourceOptions = (uiSchema === null || uiSchema === void 0 || (_uiSchema$xDataSour = uiSchema["x-data-source"]) === null || _uiSchema$xDataSour === void 0 ? void 0 : _uiSchema$xDataSour.options) || [];
		const options = (uiSchemaDataSourceOptions.length ? uiSchemaDataSourceOptions : (uiSchema === null || uiSchema === void 0 ? void 0 : uiSchema.enum) || (field === null || field === void 0 ? void 0 : field.options) || (props === null || props === void 0 ? void 0 : props.options) || []).map((option) => {
			if (typeof option === "string" || typeof option === "number") return {
				label: option,
				value: option
			};
			return require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, option), {}, { label: getI18nText(option === null || option === void 0 ? void 0 : option.label) || (option === null || option === void 0 ? void 0 : option.value) });
		});
		if (component === "Select" && (field === null || field === void 0 ? void 0 : field.type) === "array" && !(props === null || props === void 0 ? void 0 : props.mode)) props.mode = "multiple";
		return require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, field), {}, {
			name,
			label: getI18nText(field === null || field === void 0 ? void 0 : field.label) || getI18nText(uiSchema === null || uiSchema === void 0 ? 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 || rawSchema === void 0 ? void 0 : rawSchema.fields)) return rawSchema.fields.map((item) => normalizeSingleField(item)).filter(Boolean);
	if (Array.isArray(rawSchema === null || rawSchema === void 0 ? void 0 : rawSchema.children)) return rawSchema.children.map((item) => normalizeSingleField(item)).filter(Boolean);
	if ((rawSchema === null || rawSchema === void 0 ? void 0 : rawSchema.properties) && typeof rawSchema.properties === "object") return Object.keys(rawSchema.properties).map((name) => normalizeSingleField(rawSchema.properties[name], name)).filter(Boolean);
	return [];
};
/**
* @title DataSourceSubForm 子表单组件
* @description
* 独立的子表单组件，专注于渲染一组表单字段。支持两种使用方式：
* 1. 传入 children：使用低代码引擎渲染的子组件（优先）
* 2. 传入 xRecordSchema：通过配置自动生成表单字段（fallback）
*
* 值结构: { field1: v1, field2: v2 }
*/
const DataSourceSubForm = (0, react.forwardRef)((props, ref) => {
	const { activeKey, value = {}, onChange, children, xRecordSchema, renderMode = "edit", __designMode, className, style } = props;
	const [innerForm] = antd.Form.useForm();
	const activeKeyRef = (0, react.useRef)(activeKey);
	/** 确保 value 是对象 */
	const safeValue = (0, react.useMemo)(() => {
		if (value && typeof value === "object" && !Array.isArray(value)) return value;
		return {};
	}, [value]);
	(0, react.useImperativeHandle)(ref, () => {
		return { getFieldsValue: () => {
			return innerForm.getFieldsValue();
		} };
	});
	/** 当外部 value 变化时，同步到内部 Form */
	(0, react.useEffect)(() => {
		if (activeKeyRef.current !== activeKey) {
			activeKeyRef.current = activeKey;
			innerForm.resetFields();
		}
		innerForm.setFieldsValue(safeValue);
	}, [
		safeValue,
		innerForm,
		activeKey
	]);
	/** 内部 Form 值变化 -> 通知外部 */
	const handleValuesChange = (0, ahooks.useMemoizedFn)((_, allValues) => {
		onChange === null || onChange === void 0 || onChange(require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, safeValue), allValues));
	});
	/** 解析 xRecordSchema 为字段数组 */
	const fields = (0, react.useMemo)(() => normalizeRecordSchema(xRecordSchema), [xRecordSchema]);
	/**
	* @title 判断是否有有效的低代码子组件
	* @description 排除引擎注入的空容器占位符
	*/
	const hasRealChildren = (0, react.useMemo)(() => {
		const childArray = react.default.Children.toArray(children);
		if (childArray.length === 0) return false;
		return childArray.some((child) => react.default.isValidElement(child));
	}, [children]);
	/**
	* @title 创建模拟数据源
	* @description 供 DataSourceProvider 消费，使子组件（如 Select）可访问字段元信息
	*/
	const mockDataSource = (0, 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]);
	/**
	* @title 渲染表单核心内容
	* @description
	* - 有 children：渲染低代码引擎注入的子组件
	* - 无 children 但有 fields：用 renderFormItem 逐字段渲染 Antd 控件
	* - 两者均无：显示空状态提示
	*/
	const renderFormContent = () => {
		if (!hasRealChildren && fields.length === 0) return /* @__PURE__ */ react.default.createElement("div", { className: "pisell-data-source-sub-form__empty" }, "No fields configured. Please configure xRecordSchema or add children components.");
		const formContent = /* @__PURE__ */ react.default.createElement(require_JsonWrapperContext.default.Provider, { value: {
			path: [],
			level: 0
		} }, /* @__PURE__ */ react.default.createElement(antd.Form, {
			form: innerForm,
			onValuesChange: handleValuesChange,
			component: false,
			layout: "vertical"
		}, children));
		if (mockDataSource) return /* @__PURE__ */ react.default.createElement(require_FormSettingProvider.default, {
			renderMode,
			groupInfoPosition: "top",
			size: "large"
		}, /* @__PURE__ */ react.default.createElement(require_DataSourceProvider.default, {
			dataSource: mockDataSource,
			__designMode
		}, formContent));
		return /* @__PURE__ */ react.default.createElement(require_FormSettingProvider.default, {
			renderMode,
			groupInfoPosition: "top",
			size: "large"
		}, formContent);
	};
	return /* @__PURE__ */ react.default.createElement("div", {
		className: (0, classnames.default)("pisell-data-source-sub-form", className),
		style
	}, renderFormContent());
});
//#endregion
exports.default = DataSourceSubForm;
