const require_runtime = require("../../../_virtual/_rolldown/runtime.js");
const require_index = require("../../../locales/index.js");
const require_objectSpread2 = require("../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js");
const require_objectWithoutProperties = require("../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectWithoutProperties.js");
const require_index$1 = require("../../form/index.js");
const require_useDataSource = require("../hooks/useDataSource.js");
const require_useFormSetting = require("./provider/hooks/useFormSetting.js");
const require_useJsonPrefixPath = require("./provider/hooks/useJsonPrefixPath.js");
const require_useVariables = require("../hooks/useVariables.js");
const require_DataSourceProvider = require("../provider/dataSource/DataSourceProvider.js");
const require_useTranslationOriginal = require("../../../hooks/useTranslationOriginal.js");
let react = require("react");
react = require_runtime.__toESM(react);
let _pisell_utils = require("@pisell/utils");
let classnames = require("classnames");
classnames = require_runtime.__toESM(classnames);
let libphonenumber_js = require("libphonenumber-js");
require("./style.less");
//#region src/components/dataSourceComponents/dataSourceForm/utils.tsx
const _excluded = [
	"renderMode",
	"value",
	"onChange"
], _excluded2 = [
	"name",
	"label",
	"mode",
	"renderMode",
	"tooltip",
	"noStyle",
	"extra",
	"required",
	"requiredobj",
	"minLengthobj",
	"maxLengthobj",
	"typeobj",
	"maxobj",
	"minobj",
	"normalize",
	"getValueProps",
	"validator",
	"style",
	"validateTrigger",
	"__designMode",
	"labelCol",
	"hideLabel",
	"innerStyle"
];
/**
* @title: 增加renderMode属性
* @description: 基于renderMode属性控制渲染模式
* @return: *
* @Author: shengjie.zuo
* @Date: 2024-11-23 17:13:18
*/
const withMode = (FieldComponent, ReadPrettyComponent, transformProps) => {
	return (_ref) => {
		let { renderMode = "edit", value, onChange } = _ref, props = require_objectWithoutProperties._objectWithoutProperties(_ref, _excluded);
		const transformedProps = (transformProps === null || transformProps === void 0 ? void 0 : transformProps(require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, props), {}, {
			value,
			onChange,
			renderMode
		}), renderMode)) || require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, props), {}, {
			value,
			onChange,
			renderMode
		});
		if (["view", "tableView"].includes(renderMode) && ReadPrettyComponent) return /* @__PURE__ */ react.default.createElement(ReadPrettyComponent, transformedProps);
		if (renderMode === "disabled") return /* @__PURE__ */ react.default.createElement(FieldComponent, require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, transformedProps), {}, { disabled: true }));
		return /* @__PURE__ */ react.default.createElement(FieldComponent, transformedProps);
	};
};
/**
* @title: 追加formItem层
* @description:
* @return: *
* @Author: shengjie.zuo
* @Date: 2024-11-23 17:14:25
*/
const withFormItem = (WrappedComponent, overlayProps) => {
	return (_ref2) => {
		var _field$uiSchema;
		let { name: propsName, label: propsLabel, mode: propsMode, renderMode: propsRenderMode, tooltip, noStyle, extra, required, requiredobj, minLengthobj, maxLengthobj, typeobj, maxobj, minobj, normalize, getValueProps, validator, style, validateTrigger, __designMode, labelCol: propsLabelCol, hideLabel, innerStyle } = _ref2, otherProps = require_objectWithoutProperties._objectWithoutProperties(_ref2, _excluded2);
		const { path: prefixPath = [] } = require_useJsonPrefixPath.default();
		const { dataSource } = require_useDataSource.default();
		const { fields } = dataSource || {};
		const { renderMode: globalRenderMode, size } = require_useFormSetting.default();
		const field = fields === null || fields === void 0 ? void 0 : fields.find((item) => item.name === propsName);
		const label = propsLabel || (field === null || field === void 0 || (_field$uiSchema = field.uiSchema) === null || _field$uiSchema === void 0 ? void 0 : _field$uiSchema.title) || propsName;
		const effectiveMode = propsRenderMode || globalRenderMode;
		const name = (0, _pisell_utils.isString)(propsName) && propsName.includes(".") ? [propsName] : propsName;
		const renderComponent = (0, react.useMemo)(() => {
			var _overlayProps$innerPr;
			return /* @__PURE__ */ react.default.createElement(WrappedComponent, require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, overlayProps === null || overlayProps === void 0 ? void 0 : overlayProps.innerProps), otherProps), {}, {
				mode: propsMode,
				renderMode: effectiveMode,
				style: require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, (overlayProps === null || overlayProps === void 0 || (_overlayProps$innerPr = overlayProps.innerProps) === null || _overlayProps$innerPr === void 0 ? void 0 : _overlayProps$innerPr.style) || {}), innerStyle || {}),
				fieldKey: name,
				isVerification: typeobj === null || typeobj === void 0 ? void 0 : typeobj.enabled,
				size
			}));
		}, [
			effectiveMode,
			otherProps,
			propsMode,
			overlayProps === null || overlayProps === void 0 ? void 0 : overlayProps.innerProps,
			typeobj === null || typeobj === void 0 ? void 0 : typeobj.enabled,
			size,
			innerStyle,
			name
		]);
		const isDesignMode = __designMode === "design";
		const isHidden = effectiveMode === "hidden";
		const concatName = name !== void 0 ? [...prefixPath, ...toArr(name)] : void 0;
		const rules = [];
		if (requiredobj && requiredobj.required) rules.push(require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, requiredobj), {}, { message: requiredobj.message || require_index.getText("pisell-data-source-form-required-message") }));
		if (typeobj && typeobj.enabled) switch (typeobj.type) {
			case "email":
				rules.push(require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, typeobj), {}, { message: typeobj.message || require_index.getText("pisell-data-source-form-email-message") }));
				break;
			case "pattern":
				rules.push(require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, typeobj), {}, {
					pattern: new RegExp(typeobj.pattern),
					message: typeobj.message || require_index.getText("pisell-data-source-form-pattern-message")
				}));
				break;
			case "phone":
				rules.push({ validator: (_, originValue) => {
					var _phone;
					let value = "";
					if ((0, _pisell_utils.isString)(originValue)) value = originValue;
					else if (originValue && "phone" in originValue) value = `${(originValue === null || originValue === void 0 ? void 0 : originValue.countryCallingCode) || ""}${originValue.phone || ""}`;
					if (!(value === null || value === void 0 ? void 0 : value.trim())) {
						if ((requiredobj === null || requiredobj === void 0 ? void 0 : requiredobj.required) === false) return Promise.resolve();
						else if (typeof originValue == "object") return Promise.reject(new Error(requiredobj.message || require_index.getText("pisell-data-source-form-required-message")));
					}
					if (typeof originValue !== "string" && (requiredobj === null || requiredobj === void 0 ? void 0 : requiredobj.required) === false && (originValue === null || originValue === void 0 || (_phone = originValue.phone) === null || _phone === void 0 ? void 0 : _phone.trim()) === "") return Promise.resolve();
					try {
						const parsedNumber = (0, libphonenumber_js.parsePhoneNumberFromString)(value.replace(/\s|\(|\)/g, ""));
						if (!(parsedNumber === null || parsedNumber === void 0 ? void 0 : parsedNumber.isValid())) return Promise.reject(new Error(typeobj.message || require_index.getText("pisell-data-source-form-phone-message")));
						return Promise.resolve();
					} catch (error) {
						return Promise.reject(new Error(typeobj.message || require_index.getText("pisell-data-source-form-phone-message")));
					}
				} });
				break;
			case "mobile":
				rules.push({ validator: (_, originValue) => {
					let value = "";
					if ((0, _pisell_utils.isString)(originValue)) value = originValue;
					else if (originValue && "phone" in originValue) value = `${(originValue === null || originValue === void 0 ? void 0 : originValue.countryCallingCode) || ""}${originValue.phone || ""}`;
					if (!(value === null || value === void 0 ? void 0 : value.trim())) return Promise.resolve();
					try {
						const cleanedNumber = value.replace(/\s|\(|\)/g, "");
						if (cleanedNumber.length > 15) return Promise.reject(new Error(typeobj.message || require_index.getText("pisell-data-source-form-mobile-message")));
						if (cleanedNumber.startsWith("+61")) {
							const numberWithoutPrefix = cleanedNumber.slice(3);
							if (!/^(?:04\d{8}|4\d{8})$/.test(numberWithoutPrefix)) return Promise.reject(new Error(typeobj.message || require_index.getText("pisell-data-source-form-mobile-message")));
						} else if (cleanedNumber.startsWith("+86")) {
							const numberWithoutPrefix = cleanedNumber.slice(3);
							if (!/^1[3-9]\d{9}$/.test(numberWithoutPrefix)) return Promise.reject(new Error(typeobj.message || require_index.getText("pisell-data-source-form-mobile-message")));
						}
						return Promise.resolve();
					} catch (error) {
						if (value.replace(/\s|\(|\)/g, "").length > 15) return Promise.reject(new Error(typeobj.message || require_index.getText("pisell-data-source-form-mobile-message")));
						return Promise.resolve();
					}
				} });
				break;
			case "url":
				rules.push(require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, typeobj), {}, { message: typeobj.message || require_index.getText("pisell-data-source-form-url-message") }));
				break;
			case "subdomain":
				rules.push({ validator: (_, value) => {
					if (!value) return Promise.resolve();
					const subdomain = value.split(".")[0];
					if (!/^[a-z0-9-]+$/.test(subdomain)) return Promise.reject(new Error(require_index.getText("subdomain-error-pattern")));
					if (/^\d+$/.test(subdomain)) return Promise.reject(new Error(require_index.getText("subdomain-error-numbers-only")));
					if (subdomain.startsWith("-") || subdomain.endsWith("-")) return Promise.reject(new Error(require_index.getText("subdomain-error-hyphen-ends")));
					if (subdomain.includes("--")) return Promise.reject(new Error(require_index.getText("subdomain-error-consecutive-hyphens")));
					return Promise.resolve();
				} });
				break;
			case "appIdentifier":
				rules.push({ validator: (_, value) => {
					if (!value) return Promise.resolve();
					if (!/^[a-z0-9\-\._]+$/.test(value)) return Promise.reject(new Error(require_index.getText("pisell-data-source-form-app-identifier-pattern")));
					if (!/^[a-z]/.test(value)) return Promise.reject(new Error(require_index.getText("pisell-data-source-form-app-identifier-start-with-letter")));
					if (/[\-\._]$/.test(value)) return Promise.reject(new Error(require_index.getText("pisell-data-source-form-app-identifier-special-ends")));
					if (/[\-]{2,}|[\.]{2,}|[\_]{2,}/.test(value)) return Promise.reject(new Error(require_index.getText("pisell-data-source-form-app-identifier-consecutive-special")));
					return Promise.resolve();
				} });
				break;
		}
		if (maxLengthobj && maxLengthobj.enabled) rules.push({ validator(_, value) {
			let length = 0;
			if ((0, _pisell_utils.isString)(value)) length = value.length;
			else if ((0, _pisell_utils.isArr)(value)) length = value.length;
			else if ((0, _pisell_utils.isNumber)(value)) length = `${value}`.length;
			if (length > maxLengthobj.max) return Promise.reject(new Error(maxLengthobj.message || require_index.getText("pisell-data-source-form-max-length-message")(maxLengthobj === null || maxLengthobj === void 0 ? void 0 : maxLengthobj.max)));
			return Promise.resolve();
		} });
		if (minLengthobj && minLengthobj.enabled) rules.push({ validator(_, value) {
			let length = 0;
			if ((0, _pisell_utils.isString)(value)) length = value.length;
			else if ((0, _pisell_utils.isArr)(value)) length = value.length;
			else if ((0, _pisell_utils.isNumber)(value)) length = `${value}`.length;
			if (length < minLengthobj.min) return Promise.reject(new Error(minLengthobj.message || require_index.getText("pisell-data-source-form-min-length-message")(minLengthobj === null || minLengthobj === void 0 ? void 0 : minLengthobj.min)));
			return Promise.resolve();
		} });
		if (maxobj && maxobj.enabled) rules.push(require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, maxobj), {}, {
			type: "number",
			message: maxobj.message || require_index.getText("pisell-data-source-form-max-value-message")(maxobj === null || maxobj === void 0 ? void 0 : maxobj.max)
		}));
		if (minobj && minobj.enabled) rules.push(require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, minobj), {}, {
			type: "number",
			message: minobj.message || require_index.getText("pisell-data-source-form-min-value-message")(minobj === null || minobj === void 0 ? void 0 : minobj.min)
		}));
		if (validator) rules.push({ validator: (_, value) => {
			return validator(value);
		} });
		const labelCol = (0, react.useMemo)(() => {
			if (hideLabel) return { span: 0 };
			return propsLabelCol;
		}, [hideLabel, propsLabelCol]);
		const otherFormItemProps = (0, react.useMemo)(() => {
			if ((0, _pisell_utils.isFunction)(overlayProps === null || overlayProps === void 0 ? void 0 : overlayProps.otherFormItemProps)) return overlayProps === null || overlayProps === void 0 ? void 0 : overlayProps.otherFormItemProps(otherProps, { rules });
			return require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, otherProps || {}), (overlayProps === null || overlayProps === void 0 ? void 0 : overlayProps.otherFormItemProps) || {}), {}, { onChange: void 0 });
		}, [overlayProps === null || overlayProps === void 0 ? void 0 : overlayProps.otherFormItemProps, otherProps]);
		return /* @__PURE__ */ react.default.createElement(require_index$1.default.Item, require_objectSpread2._objectSpread2({
			required,
			style: require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({ width: "100%" }, style), {}, { opacity: isDesignMode && isHidden ? "0.3" : 1 }),
			name: concatName,
			label,
			tooltip,
			noStyle,
			extra,
			hidden: isHidden && !isDesignMode,
			rules,
			normalize,
			getValueProps,
			validateTrigger: validateTrigger || ["onChange", "onBlur"],
			labelCol,
			initialValue: otherProps === null || otherProps === void 0 ? void 0 : otherProps.defaultValue,
			className: (0, classnames.default)("pisell-data-source-form-item", { "pisell-data-source-form-item-view": effectiveMode === "view" })
		}, otherFormItemProps), renderComponent);
	};
};
const withDataSource = (WrappedComponent) => {
	return (props) => {
		const { dataSource, extraParams } = props;
		return /* @__PURE__ */ react.default.createElement(require_DataSourceProvider.default, {
			dataSource,
			extraParams: { list: extraParams },
			requestOptions: { list: { cacheKey: `${dataSource === null || dataSource === void 0 ? void 0 : dataSource.headerDataSource}-${dataSource === null || dataSource === void 0 ? void 0 : dataSource.name}-${dataSource === null || dataSource === void 0 ? void 0 : dataSource.tableName}` } }
		}, /* @__PURE__ */ react.default.createElement(WrappedComponent, props));
	};
};
const withOptions = (WrappedComponent) => {
	return (props) => {
		var _list$data2;
		const translationOriginal = require_useTranslationOriginal.default();
		const { options: propsOptions, optionSourceType, labelField, valueField, extraParams } = props;
		const { parseVariable } = require_useVariables.default();
		const { list, getCurrentRecord } = require_useDataSource.default();
		const parseParams = (0, react.useMemo)(() => {
			const params = {};
			if (extraParams) Object.keys(extraParams).forEach((key) => {
				params[key] = parseVariable === null || parseVariable === void 0 ? void 0 : parseVariable(extraParams[key], { currentRecord: getCurrentRecord() });
			});
			return params;
		}, [extraParams]);
		(0, react.useEffect)(() => {
			if (optionSourceType === "api") list.run(require_objectSpread2._objectSpread2({
				page: 1,
				pageSize: 500
			}, parseParams));
		}, []);
		const options = (0, react.useMemo)(() => {
			var _list$data, _list$data$filter;
			if (optionSourceType !== "api") return propsOptions;
			return (((_list$data = list.data) === null || _list$data === void 0 || (_list$data = _list$data.data) === null || _list$data === void 0 || (_list$data$filter = _list$data.filter) === null || _list$data$filter === void 0 ? void 0 : _list$data$filter.call(_list$data, (item) => ![
				"draft",
				"inactive",
				"disabled"
			].includes(item === null || item === void 0 ? void 0 : item.status))) || []).map((item) => ({
				label: translationOriginal(item[labelField]),
				value: item[valueField]
			})) || [];
		}, [
			propsOptions,
			optionSourceType,
			list === null || list === void 0 || (_list$data2 = list.data) === null || _list$data2 === void 0 ? void 0 : _list$data2.data
		]);
		return /* @__PURE__ */ react.default.createElement(WrappedComponent, require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, props), {}, { options }));
	};
};
const getNestedValue = (obj, path) => {
	const keys = path.split(".");
	let value = obj;
	for (const k of keys) {
		if (!value) break;
		value = value[k];
	}
	return value;
};
const renderValueWithMap = (value, valueMap, renderMode) => {
	const textStyle = renderMode === "tableView" ? {
		fontSize: 14,
		fontWeight: 400
	} : {};
	if ((0, _pisell_utils.isArr)(value)) return /* @__PURE__ */ react.default.createElement("span", { className: "pisell-form-read-pretty-text" }, value.map((item, index) => /* @__PURE__ */ react.default.createElement(react.default.Fragment, null, /* @__PURE__ */ react.default.createElement("span", {
		key: item,
		className: "pisell-form-read-pretty-value",
		style: textStyle
	}, valueMap === null || valueMap === void 0 ? void 0 : valueMap[item]), index < value.length - 1 && ", ")));
	else if ((0, _pisell_utils.isString)(value) || (0, _pisell_utils.isNumber)(value)) return /* @__PURE__ */ react.default.createElement("span", { className: "pisell-form-read-pretty-text" }, /* @__PURE__ */ react.default.createElement("span", {
		className: "pisell-form-read-pretty-value",
		style: textStyle
	}, (valueMap === null || valueMap === void 0 ? void 0 : valueMap[value]) || value));
	return null;
};
function toArr(str) {
	return Array.isArray(str) ? str : [str];
}
const systemFields = [
	"createdAt",
	"updatedAt",
	"createdBy",
	"created_at",
	"updated_at",
	"deleted_at"
];
const filterSystemFields = (params) => {
	return Object.keys(params).reduce((acc, key) => {
		if (!systemFields.includes(key)) acc[key] = params[key];
		return acc;
	}, {});
};
const transformFormObjToArrayWithUntouched = (obj) => {
	return Object.keys(obj).reduce((acc, key) => {
		acc.push({
			name: key,
			value: obj[key],
			touched: false
		});
		return acc;
	}, []);
};
const setFormFieldsUntouched = (form) => {
	const fields = form.getFieldsError().map((item) => {
		return {
			name: item.name,
			value: form.getFieldValue(item.name),
			touched: false
		};
	});
	form.setFields(fields);
};
//#endregion
exports.filterSystemFields = filterSystemFields;
exports.getNestedValue = getNestedValue;
exports.renderValueWithMap = renderValueWithMap;
exports.setFormFieldsUntouched = setFormFieldsUntouched;
exports.toArr = toArr;
exports.transformFormObjToArrayWithUntouched = transformFormObjToArrayWithUntouched;
exports.withDataSource = withDataSource;
exports.withFormItem = withFormItem;
exports.withMode = withMode;
exports.withOptions = withOptions;
