const require_runtime = require("../../../../_virtual/_rolldown/runtime.js");
const require_objectSpread2 = require("../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js");
const require_asyncToGenerator = require("../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js");
const require_objectWithoutProperties = require("../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectWithoutProperties.js");
const require_typeValidation = require("../utils/typeValidation.js");
const require_validators = require("../utils/validators.js");
const require_serve = require("./DataSourceTreeSelect/serve.js");
const require_index = require("./OptionDataSource/index.js");
let react = require("react");
react = require_runtime.__toESM(react);
let antd = require("antd");
let _pisell_utils = require("@pisell/utils");
let _pisell_materials = require("@pisell/materials");
//#region src/components/systemSettings/registry/components/ItemModal.tsx
const _excluded = ["type", "options"];
const { Option } = antd.Select;
const { TextArea } = antd.Input;
const DefaultScopeOptions = [
	{
		value: "system",
		label: "registry.scope.systemDefault"
	},
	{
		value: "saas",
		label: "registry.scope.saasDefault"
	},
	{
		value: "organization",
		label: "registry.scope.organization"
	},
	{
		value: "business",
		label: "registry.scope.business"
	},
	{
		value: "channel",
		label: "registry.scope.channel"
	},
	{
		value: "board",
		label: "registry.scope.board"
	}
];
const DeviceScopeOptions = [
	{
		value: "system",
		label: "registry.scope.systemDefault"
	},
	{
		value: "profile",
		label: "registry.scope.profile"
	},
	{
		value: "instance",
		label: "registry.scope.instance"
	}
];
const fieldTypeOptions = [
	{
		value: "string",
		label: "String"
	},
	{
		value: "integer",
		label: "Integer"
	},
	{
		value: "float",
		label: "Float"
	},
	{
		value: "boolean",
		label: "Boolean"
	},
	{
		value: "array",
		label: "Array"
	}
];
const interfaceTypeOptions = {
	string: [
		{
			value: "Input",
			label: "单行文本输入框"
		},
		{
			value: "Input.TextArea",
			label: "多行文本输入框"
		},
		{
			value: "Select",
			label: "单选下拉框"
		}
	],
	integer: [{
		value: "InputNumber",
		label: "数字输入框（整数模式）"
	}],
	float: [{
		value: "InputNumber",
		label: "数字输入框（支持小数）"
	}],
	boolean: [{
		value: "Checkbox",
		label: "复选框"
	}, {
		value: "Switch",
		label: "开关组件"
	}],
	array: [
		{
			value: "Select",
			label: "多选下拉框"
		},
		{
			value: "Input.JSON",
			label: "JSON编辑器"
		},
		{
			value: "RecordListWrapper",
			label: "记录列表包装器"
		},
		{
			value: "Translation",
			label: "多语言输入框"
		}
	]
};
const ItemModal = ({ open, type, data, section, onOk, onCancel, scene }) => {
	const scopeOptions = scene === "device" ? DeviceScopeOptions : DefaultScopeOptions;
	const [form] = antd.Form.useForm();
	const [selectedFieldType, setSelectedFieldType] = (0, react.useState)("string");
	const [selectedScopes, setSelectedScopes] = (0, react.useState)([]);
	const [showSystemDefaultValue, setShowSystemDefaultValue] = (0, react.useState)(false);
	const _interfaceType = antd.Form.useWatch("interfaceType", form);
	const [treeDataSource, setTreeDataSource] = (0, react.useState)([]);
	(0, react.useEffect)(() => {
		require_serve.getAllDataSources().then((data) => setTreeDataSource(data));
	}, []);
	const renderDefaultValueInput = (fieldType) => {
		switch (fieldType) {
			case "string": return /* @__PURE__ */ react.default.createElement(antd.Input, {
				placeholder: "请输入默认值",
				allowClear: true
			});
			case "integer": return /* @__PURE__ */ react.default.createElement(antd.InputNumber, {
				placeholder: "请输入整数",
				style: { width: "100%" },
				precision: 0,
				allowClear: true
			});
			case "float": return /* @__PURE__ */ react.default.createElement(antd.InputNumber, {
				placeholder: "请输入数字",
				style: { width: "100%" },
				allowClear: true
			});
			case "boolean": return /* @__PURE__ */ react.default.createElement(antd.Select, {
				placeholder: "请选择布尔值",
				allowClear: true
			}, /* @__PURE__ */ react.default.createElement(Option, { value: "true" }, "true"), /* @__PURE__ */ react.default.createElement(Option, { value: "false" }, "false"));
			case "array": return /* @__PURE__ */ react.default.createElement(TextArea, {
				placeholder: "请输入JSON对象或数组，例如：{} 或 []",
				rows: 4,
				allowClear: true
			});
			default: return /* @__PURE__ */ react.default.createElement(antd.Input, {
				placeholder: "请输入默认值",
				allowClear: true
			});
		}
	};
	(0, react.useEffect)(() => {
		if (open) if (type === "edit" && data) {
			const getDescription = (descField) => {
				if (typeof descField === "string") return {
					en: "",
					"zh-CN": "",
					"zh-HK": "",
					"ja": "",
					"pt": "",
					original: descField
				};
				if (descField && typeof descField === "object") return {
					en: descField.en || "",
					"zh-CN": descField["zh-CN"] || "",
					"zh-HK": descField["zh-HK"] || "",
					"ja": descField["ja"] || "",
					"pt": descField["pt"] || "",
					original: descField.original || descField["zh-CN"] || descField.en || ""
				};
				return {
					en: "",
					"zh-CN": "",
					"zh-HK": "",
					"ja": "",
					"pt": "",
					original: ""
				};
			};
			const formData = {
				name: getDescription(data.title),
				key: data.key || data.code,
				fieldType: data.type || data.fieldType || "string",
				interfaceType: data.interface || data.interfaceType,
				scopes: data.scopes || [],
				description: getDescription(data.description),
				default: data.default
			};
			const schema = (data === null || data === void 0 ? void 0 : data.schema) || {};
			const xDataSource = schema["x-data-source"] || {};
			if (Object.keys(xDataSource).length > 0) {
				const extraParams = xDataSource === null || xDataSource === void 0 ? void 0 : xDataSource.extraParams;
				if (!extraParams) xDataSource.extraParams = "";
				else if (typeof extraParams === "string") xDataSource.extraParams = extraParams;
				else if (typeof extraParams === "object") xDataSource.extraParams = JSON.stringify(extraParams, null, 2);
				formData.xDataSource = xDataSource;
			} else formData.xDataSource = {
				type: "default",
				options: []
			};
			const xRecordSchema = schema["x-record-schema"];
			if (!xRecordSchema) formData.xRecordSchema = "";
			else if (typeof xRecordSchema === "string") formData.xRecordSchema = xRecordSchema;
			else if (typeof xRecordSchema === "object") formData.xRecordSchema = JSON.stringify(xRecordSchema, null, 2);
			const xCustomUiSchema = schema["x-custom-ui-schema"];
			if (!xCustomUiSchema) formData.xCustomUiSchema = "";
			else if (typeof xCustomUiSchema === "string") formData.uiSchema = xCustomUiSchema;
			else if (typeof xCustomUiSchema === "object") formData.uiSchema = JSON.stringify(xCustomUiSchema, null, 2);
			form.setFieldsValue(formData);
			setSelectedFieldType(formData.fieldType);
			setSelectedScopes(formData.scopes);
			setShowSystemDefaultValue(formData.scopes.includes("system"));
		} else {
			form.resetFields();
			const defaultValues = {
				name: {
					en: "",
					"zh-CN": "",
					"zh-HK": "",
					"ja": "",
					"pt": "",
					original: ""
				},
				description: {
					en: "",
					"zh-CN": "",
					"zh-HK": "",
					"ja": "",
					"pt": "",
					original: ""
				},
				fieldType: "string",
				scopes: ["string"],
				key: (section === null || section === void 0 ? void 0 : section.code) ? `${section.code}.` : "",
				xDataSource: {
					type: "default",
					options: []
				},
				xRecordSchema: ""
			};
			form.setFieldsValue(defaultValues);
			setSelectedFieldType("string");
			setSelectedScopes(["string"]);
		}
	}, [
		open,
		type,
		data,
		form
	]);
	const handleFieldTypeChange = (value) => {
		setSelectedFieldType(value);
		form.setFieldsValue({ interfaceType: void 0 });
		form.setFieldsValue({ default: void 0 });
		form.setFieldsValue({ xDataSource: {
			type: "default",
			options: []
		} });
		form.setFieldsValue({ xRecordSchema: "" });
		form.validateFields(["default"]).catch(() => {});
	};
	const handleInterfaceTypeChange = (value) => {
		form.setFieldsValue({
			xDataSource: {
				type: "default",
				options: []
			},
			xRecordSchema: ""
		});
	};
	const handleScopesChange = (values) => {
		const stringValues = values.map((v) => String(v));
		setSelectedScopes(stringValues);
		console.log("stringValues", stringValues);
		setShowSystemDefaultValue(stringValues.includes("system"));
	};
	const handleOk = function() {
		var _ref2 = require_asyncToGenerator._asyncToGenerator(function* () {
			try {
				const values = yield form.validateFields();
				if (values.default !== void 0 && values.default !== null && values.default !== "") if (values.fieldType === "integer" || values.fieldType === "float") {
					if (typeof values.default !== "number") {
						const validation = require_typeValidation.validateDefaultValue(values.fieldType, values.default);
						if (!validation.isValid) throw new Error(`默认值验证失败: ${validation.error}`);
						values.default = require_typeValidation.parseDefaultValue(values.fieldType, values.default);
					}
				} else {
					const validation = require_typeValidation.validateDefaultValue(values.fieldType, values.default);
					if (!validation.isValid) throw new Error(`默认值验证失败: ${validation.error}`);
					values.default = require_typeValidation.parseDefaultValue(values.fieldType, values.default);
				}
				else values.default = null;
				let schema = {};
				if (values === null || values === void 0 ? void 0 : values.xCustomUiSchema) try {
					schema["x-custom-ui-schema"] = JSON.parse(values.xCustomUiSchema);
				} catch (error) {
					throw new Error(`UI Schema格式错误: ${error instanceof Error ? error.message : "未知错误"}`);
				}
				if (["Select", "RecordListWrapper"].includes(values.interfaceType || "") && values.xDataSource) {
					const _ref = (values === null || values === void 0 ? void 0 : values.xDataSource) || {}, { type = "default", options = [] } = _ref, rest = require_objectWithoutProperties._objectWithoutProperties(_ref, _excluded);
					if (type === "default") schema["x-data-source"] = {
						type,
						options
					};
					else if (type === "api") {
						schema["x-data-source"] = require_objectSpread2._objectSpread2({ type }, rest || {});
						if (rest === null || rest === void 0 ? void 0 : rest.extraParams) try {
							schema["x-data-source"].extraParams = JSON.parse(rest.extraParams);
						} catch (error) {
							throw new Error(`Extra Params格式错误: ${error instanceof Error ? error.message : "未知错误"}`);
						}
					} else if (type === "custom") schema["x-data-source"] = { type };
				} else schema["x-data-source"] = void 0;
				if (values.interfaceType === "RecordListWrapper" && values.xRecordSchema) try {
					schema["x-record-schema"] = JSON.parse(values.xRecordSchema);
				} catch (error) {
					throw new Error(`Record List Wrapper Schema格式错误: ${error instanceof Error ? error.message : "未知错误"}`);
				}
				else schema["x-record-schema"] = void 0;
				values.schema = Object.keys(schema).length > 0 ? schema : void 0;
				delete values.xDataSource;
				delete values.xRecordSchema;
				delete values.xCustomUiSchema;
				yield onOk(values);
			} catch (error) {
				console.error("Validation failed:", error);
			}
		});
		return function handleOk() {
			return _ref2.apply(this, arguments);
		};
	}();
	const handleCancel = () => {
		form.resetFields();
		onCancel();
	};
	const title = _pisell_utils.locales.getText(type === "add" ? "registry.modal.add.item" : "registry.modal.edit.item");
	const jsonValidator = (value, message) => {
		if (!value || value.trim() === "") return Promise.resolve();
		try {
			JSON.parse(value);
			return Promise.resolve();
		} catch (error) {
			return Promise.reject(new Error(message));
		}
	};
	return /* @__PURE__ */ react.default.createElement(antd.Drawer, {
		title,
		open,
		onClose: handleCancel,
		width: 600,
		destroyOnClose: true,
		footer: /* @__PURE__ */ react.default.createElement("div", { style: { textAlign: "right" } }, /* @__PURE__ */ react.default.createElement(_pisell_materials.Button, {
			onClick: handleCancel,
			style: { marginRight: 8 }
		}, _pisell_utils.locales.getText("registry.button.cancel")), /* @__PURE__ */ react.default.createElement(_pisell_materials.Button, {
			type: "primary",
			onClick: handleOk
		}, _pisell_utils.locales.getText("registry.button.save")))
	}, /* @__PURE__ */ react.default.createElement(antd.Form, {
		form,
		layout: "vertical",
		requiredMark: true
	}, /* @__PURE__ */ react.default.createElement(antd.Form.Item, {
		name: "name",
		label: _pisell_utils.locales.getText("registry.form.name"),
		rules: [{
			required: true,
			validator: (_, value) => {
				if (!value || !value.original) return Promise.reject(new Error(_pisell_utils.locales.getText("registry.message.required")));
				if (value.original.length > 100) return Promise.reject(new Error(_pisell_utils.locales.getText("registry.message.name.maxLength")));
				return Promise.resolve();
			}
		}]
	}, /* @__PURE__ */ react.default.createElement(_pisell_materials.BaseTranslation, {
		placeholder: _pisell_utils.locales.getText("registry.form.name.placeholder"),
		type: "text",
		renderMode: "edit"
	})), /* @__PURE__ */ react.default.createElement(antd.Form.Item, {
		name: "key",
		label: _pisell_utils.locales.getText("registry.form.key"),
		rules: [
			{
				required: true,
				message: _pisell_utils.locales.getText("registry.message.required")
			},
			{
				max: 100,
				message: _pisell_utils.locales.getText("registry.message.key.maxLength")
			},
			{ validator: (section === null || section === void 0 ? void 0 : section.code) ? require_validators.createPrefixedAppIdentifierValidator(section.code) : (_, value) => {
				if (!value) return Promise.resolve();
				return Promise.reject(/* @__PURE__ */ new Error("未找到当前区块信息"));
			} }
		]
	}, /* @__PURE__ */ react.default.createElement(antd.Input, {
		placeholder: _pisell_utils.locales.getText("registry.form.key.placeholder"),
		maxLength: 100
	})), /* @__PURE__ */ react.default.createElement(antd.Row, { gutter: 16 }, /* @__PURE__ */ react.default.createElement(antd.Col, { span: 12 }, /* @__PURE__ */ react.default.createElement(antd.Form.Item, {
		name: "fieldType",
		label: _pisell_utils.locales.getText("registry.form.fieldType"),
		rules: [{
			required: true,
			message: _pisell_utils.locales.getText("registry.message.required")
		}]
	}, /* @__PURE__ */ react.default.createElement(antd.Select, {
		placeholder: _pisell_utils.locales.getText("registry.form.fieldType.placeholder"),
		onChange: handleFieldTypeChange
	}, fieldTypeOptions.map((option) => /* @__PURE__ */ react.default.createElement(Option, {
		key: option.value,
		value: option.value
	}, option.label))))), /* @__PURE__ */ react.default.createElement(antd.Col, { span: 12 }, /* @__PURE__ */ react.default.createElement(antd.Form.Item, {
		name: "interfaceType",
		label: _pisell_utils.locales.getText("registry.form.interfaceType"),
		rules: [{
			required: true,
			message: _pisell_utils.locales.getText("registry.message.required")
		}]
	}, /* @__PURE__ */ react.default.createElement(antd.Select, {
		placeholder: _pisell_utils.locales.getText("registry.form.interfaceType.placeholder"),
		allowClear: true,
		onChange: handleInterfaceTypeChange
	}, (interfaceTypeOptions[selectedFieldType] || []).map((option) => /* @__PURE__ */ react.default.createElement(Option, {
		key: option.value,
		value: option.value
	}, option.label)))))), ["Select", "RecordListWrapper"].includes(_interfaceType || "") && /* @__PURE__ */ react.default.createElement(require_index.default, {
		form,
		treeDataSource
	}), _interfaceType === "RecordListWrapper" && /* @__PURE__ */ react.default.createElement(antd.Form.Item, {
		name: "xRecordSchema",
		label: _pisell_utils.locales.getText("registry.form.recordListWrapper.label"),
		rules: [{ validator: (_, value) => jsonValidator(value, _pisell_utils.locales.getText("registry.message.recordListWrapper.invalid")) }]
	}, /* @__PURE__ */ react.default.createElement(TextArea, {
		placeholder: _pisell_utils.locales.getText("registry.form.recordListWrapper.placeholder"),
		rows: 6,
		style: { fontFamily: "monospace" }
	})), /* @__PURE__ */ react.default.createElement(antd.Form.Item, {
		name: "scopes",
		label: _pisell_utils.locales.getText("registry.form.scopes"),
		rules: [{
			required: true,
			message: _pisell_utils.locales.getText("registry.message.required")
		}]
	}, /* @__PURE__ */ react.default.createElement(antd.Checkbox.Group, {
		options: scopeOptions.map((option) => ({
			label: _pisell_utils.locales.getText(option.label),
			value: option.value
		})),
		onChange: handleScopesChange
	})), /* @__PURE__ */ react.default.createElement(antd.Form.Item, {
		name: "description",
		label: _pisell_utils.locales.getText("registry.form.description"),
		rules: [{ validator: (_, value) => {
			if (value && value.original && value.original.length > 500) return Promise.reject(new Error(_pisell_utils.locales.getText("registry.message.description.maxLength")));
			return Promise.resolve();
		} }]
	}, /* @__PURE__ */ react.default.createElement(_pisell_materials.BaseTranslation, {
		placeholder: _pisell_utils.locales.getText("registry.form.description.placeholder"),
		type: "textarea",
		renderMode: "edit"
	})), showSystemDefaultValue && /* @__PURE__ */ react.default.createElement(antd.Form.Item, {
		name: "default",
		label: _pisell_utils.locales.getText("registry.form.systemDefaultValue"),
		rules: [{ validator: (_, value) => {
			if (value === null || value === void 0 || value === "") return Promise.resolve();
			const currentFieldType = form.getFieldValue("fieldType");
			if (!currentFieldType) return Promise.reject(/* @__PURE__ */ new Error("请先选择字段类型"));
			const validation = require_typeValidation.validateDefaultValue(currentFieldType, value);
			if (!validation.isValid) return Promise.reject(new Error(validation.error));
			return Promise.resolve();
		} }]
	}, renderDefaultValueInput(selectedFieldType)), /* @__PURE__ */ react.default.createElement(antd.Form.Item, {
		name: "xCustomUiSchema",
		label: _pisell_utils.locales.getText("registry.form.uiSchema"),
		rules: [{ validator: (_, value) => jsonValidator(value, _pisell_utils.locales.getText("registry.message.uiSchema.invalid")) }]
	}, /* @__PURE__ */ react.default.createElement(TextArea, {
		placeholder: _pisell_utils.locales.getText("registry.form.uiSchema.placeholder"),
		rows: 6,
		style: { fontFamily: "monospace" }
	}))));
};
//#endregion
exports.default = ItemModal;
