function _array_like_to_array(arr, len) {
    if (len == null || len > arr.length) len = arr.length;
    for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
    return arr2;
}
function _array_with_holes(arr) {
    if (Array.isArray(arr)) return arr;
}
function _define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}
function _iterable_to_array_limit(arr, i) {
    var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
    if (_i == null) return;
    var _arr = [];
    var _n = true;
    var _d = false;
    var _s, _e;
    try {
        for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
            _arr.push(_s.value);
            if (i && _arr.length === i) break;
        }
    } catch (err) {
        _d = true;
        _e = err;
    } finally{
        try {
            if (!_n && _i["return"] != null) _i["return"]();
        } finally{
            if (_d) throw _e;
        }
    }
    return _arr;
}
function _non_iterable_rest() {
    throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _object_spread(target) {
    for(var i = 1; i < arguments.length; i++){
        var source = arguments[i] != null ? arguments[i] : {};
        var ownKeys = Object.keys(source);
        if (typeof Object.getOwnPropertySymbols === "function") {
            ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
                return Object.getOwnPropertyDescriptor(source, sym).enumerable;
            }));
        }
        ownKeys.forEach(function(key) {
            _define_property(target, key, source[key]);
        });
    }
    return target;
}
function ownKeys(object, enumerableOnly) {
    var keys = Object.keys(object);
    if (Object.getOwnPropertySymbols) {
        var symbols = Object.getOwnPropertySymbols(object);
        if (enumerableOnly) {
            symbols = symbols.filter(function(sym) {
                return Object.getOwnPropertyDescriptor(object, sym).enumerable;
            });
        }
        keys.push.apply(keys, symbols);
    }
    return keys;
}
function _object_spread_props(target, source) {
    source = source != null ? source : {};
    if (Object.getOwnPropertyDescriptors) {
        Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
    } else {
        ownKeys(Object(source)).forEach(function(key) {
            Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
        });
    }
    return target;
}
function _sliced_to_array(arr, i) {
    return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
}
function _unsupported_iterable_to_array(o, minLen) {
    if (!o) return;
    if (typeof o === "string") return _array_like_to_array(o, minLen);
    var n = Object.prototype.toString.call(o).slice(8, -1);
    if (n === "Object" && o.constructor) n = o.constructor.name;
    if (n === "Map" || n === "Set") return Array.from(n);
    if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
}
/* eslint-disable @typescript-eslint/no-use-before-define */ import { MinusCircleOutlined } from "@ant-design/icons";
import { Plus } from "@sofa-design/icons";
import { Button, Card, Form, Input, InputNumber, Select, Space } from "antd";
import { merge } from "lodash-es";
import React, { memo, useCallback, useContext, useEffect, useMemo } from "react";
import { I18nContext } from "../../I18n";
/**
 * SchemaForm 组件 - 基于Schema的表单组件
 *
 * 该组件根据JSON Schema自动生成表单，支持多种数据类型和验证规则。
 * 提供动态表单生成、数据验证、只读模式等功能。
 *
 * @component
 * @description 基于Schema的表单组件，自动生成表单字段和验证规则
 * @param {SchemaFormProps} props - 组件属性
 * @param {LowCodeSchema} props.schema - 表单Schema定义
 * @param {Function} [props.onValuesChange] - 表单值变化回调
 * @param {Record<string, any>} [props.initialValues] - 初始值
 * @param {boolean} [props.readonly=false] - 是否只读模式
 *
 * @example
 * ```tsx
 * <SchemaForm
 *   schema={{
 *     component: {
 *       properties: {
 *         name: {
 *           type: 'string',
 *           title: '姓名',
 *           required: true
 *         },
 *         age: {
 *           type: 'number',
 *           title: '年龄',
 *           minimum: 0,
 *           maximum: 150
 *         }
 *       }
 *     }
 *   }}
 *   onValuesChange={(changed, values) => console.log(values)}
 *   initialValues={{ name: '张三', age: 25 }}
 * />
 * ```
 *
 * @returns {React.ReactElement} 渲染的Schema表单组件
 *
 * @remarks
 * - 根据JSON Schema自动生成表单
 * - 支持多种数据类型（string、number、array、object等）
 * - 提供完整的验证规则支持
 * - 支持只读模式
 * - 提供国际化支持
 * - 支持嵌套对象和数组
 * - 提供动态字段添加/删除
 * - 响应式布局适配
 */ var SchemaFormComponent = function SchemaFormComponent(param) {
    var schema = param.schema, onValuesChange = param.onValuesChange, initialValues = param.initialValues, _param_readonly = param.readonly, readonly = _param_readonly === void 0 ? false : _param_readonly;
    var _Form_useForm = _sliced_to_array(Form.useForm(), 1), form = _Form_useForm[0];
    var _ref = (schema === null || schema === void 0 ? void 0 : schema.component) || {}, _ref_properties = _ref.properties, properties = _ref_properties === void 0 ? {} : _ref_properties;
    var locale = useContext(I18nContext).locale;
    // 生成表单验证规则
    var generateRules = useCallback(function(property) {
        var rules = [];
        if (property.required) {
            rules.push({
                required: true,
                message: "".concat((locale === null || locale === void 0 ? void 0 : locale.inputPlaceholder) || '请输入', " ").concat(property.title || property.description || '')
            });
        }
        if (property.type === 'string' && property.pattern) {
            rules.push({
                pattern: new RegExp(property.pattern),
                message: property.patternMessage || "".concat(property.title || property.description || '', "格式不正确")
            });
        }
        if (property.type === 'number') {
            rules.push({
                type: 'number',
                message: "".concat(property.title || property.description || '', "必须是数字")
            });
            if (typeof property.minimum === 'number') {
                rules.push({
                    type: 'number',
                    min: property.minimum,
                    message: "".concat(property.title || property.description || '', "不能小于 ").concat(property.minimum)
                });
            }
            if (typeof property.maximum === 'number') {
                rules.push({
                    type: 'number',
                    max: property.maximum,
                    message: "".concat(property.title || property.description || '', "不能大于 ").concat(property.maximum)
                });
            }
        }
        if (property.type === 'array') {
            if (typeof property.minItems === 'number') {
                rules.push({
                    type: 'array',
                    min: property.minItems,
                    message: "".concat(property.title || property.description || '', "至少需要 ").concat(property.minItems, " 项")
                });
            }
            if (typeof property.maxItems === 'number') {
                rules.push({
                    type: 'array',
                    max: property.maxItems,
                    message: "".concat(property.title || property.description || '', "最多只能有 ").concat(property.maxItems, " 项")
                });
            }
        }
        return rules;
    }, [
        locale
    ]);
    // 获取属性标题
    var getPropertyTitle = useCallback(function(property, key) {
        return property.title || property.description || key;
    }, []);
    // 获取通用输入框属性
    var getCommonInputProps = useCallback(function(property) {
        return {
            placeholder: "".concat((locale === null || locale === void 0 ? void 0 : locale.inputPlaceholder) || '请输入', " ").concat(property.title || property.description),
            readOnly: readonly,
            disabled: readonly
        };
    }, [
        readonly,
        locale
    ]);
    // 渲染基础表单项
    var renderBasicFormItem = useCallback(function(property) {
        var commonProps = getCommonInputProps(property);
        switch(property.type){
            case 'number':
                return /*#__PURE__*/ React.createElement(InputNumber, _object_spread_props(_object_spread({}, commonProps), {
                    style: {
                        width: '100%'
                    },
                    min: property.minimum,
                    max: property.maximum,
                    step: property.step || 1
                }));
            case 'string':
                if (property.enum) {
                    return /*#__PURE__*/ React.createElement(Select, commonProps, property.enum.map(function(option) {
                        return /*#__PURE__*/ React.createElement(Select.Option, {
                            key: option,
                            value: option
                        }, option);
                    }));
                }
                return /*#__PURE__*/ React.createElement(Input, commonProps);
            default:
                return /*#__PURE__*/ React.createElement(Input, commonProps);
        }
    }, [
        getCommonInputProps,
        locale
    ]);
    // 渲染数组项内容
    var renderArrayItemContent = useCallback(function(name, items) {
        var isNested = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : false;
        if (!items) {
            return /*#__PURE__*/ React.createElement(Form.Item, {
                name: name,
                style: {
                    margin: 0
                }
            }, /*#__PURE__*/ React.createElement(Input, {
                placeholder: (locale === null || locale === void 0 ? void 0 : locale.inputPlaceholder) || '请输入',
                readOnly: readonly,
                disabled: readonly
            }));
        }
        if (items.type === 'object' && items.properties) {
            return /*#__PURE__*/ React.createElement(Space, {
                direction: "vertical",
                style: {
                    width: '100%'
                }
            }, Object.entries(items.properties).map(function(param) {
                var _param = _sliced_to_array(param, 2), objKey = _param[0], objProperty = _param[1];
                return /*#__PURE__*/ React.createElement(Form.Item, {
                    key: objKey,
                    label: getPropertyTitle(objProperty, objKey),
                    name: isNested ? [
                        name,
                        objKey
                    ] : [
                        name,
                        objKey
                    ],
                    rules: generateRules(objProperty),
                    style: {
                        margin: 0
                    }
                }, renderFormItem(objKey, objProperty));
            }));
        }
        return /*#__PURE__*/ React.createElement(Form.Item, {
            name: name,
            style: {
                margin: 0
            }
        }, renderBasicFormItem(items));
    }, [
        readonly,
        getPropertyTitle,
        generateRules,
        renderBasicFormItem
    ]);
    // 渲染数组表单项
    var renderArrayFormItem = useCallback(function(key, property, baseName) {
        var fieldName = baseName !== undefined ? [
            baseName,
            key
        ] : key;
        return /*#__PURE__*/ React.createElement(Form.List, {
            name: fieldName
        }, function(fields, param) {
            var add = param.add, remove = param.remove;
            return /*#__PURE__*/ React.createElement(React.Fragment, null, fields.map(function(param) {
                var fieldKey = param.key, name = param.name;
                return /*#__PURE__*/ React.createElement(Card, {
                    key: fieldKey,
                    size: "small",
                    style: {
                        marginBottom: 8
                    },
                    extra: !readonly && /*#__PURE__*/ React.createElement(Button, {
                        type: "link",
                        danger: true,
                        size: "small",
                        icon: /*#__PURE__*/ React.createElement(MinusCircleOutlined, null),
                        onClick: function onClick() {
                            return remove(name);
                        }
                    })
                }, renderArrayItemContent(name, property.items, true));
            }), !readonly && /*#__PURE__*/ React.createElement(Form.Item, null, /*#__PURE__*/ React.createElement(Button, {
                type: "dashed",
                onClick: function onClick() {
                    return add();
                },
                block: true,
                icon: /*#__PURE__*/ React.createElement(Plus, null)
            }, "添加 ", getPropertyTitle(property, key))));
        });
    }, [
        readonly,
        renderArrayItemContent,
        getPropertyTitle
    ]);
    // 渲染对象表单项
    var renderObjectFormItem = useCallback(function(key, property, baseName) {
        if (!property.properties) {
            return /*#__PURE__*/ React.createElement(Input, {
                placeholder: "".concat((locale === null || locale === void 0 ? void 0 : locale.inputPlaceholder) || '请输入', " ").concat(property.title || property.description),
                disabled: true
            });
        }
        return /*#__PURE__*/ React.createElement(Card, {
            size: "small",
            style: {
                marginTop: 8
            }
        }, Object.entries(property.properties).map(function(param) {
            var _param = _sliced_to_array(param, 2), objKey = _param[0], objProperty = _param[1];
            return /*#__PURE__*/ React.createElement(Form.Item, {
                key: objKey,
                label: getPropertyTitle(objProperty, objKey),
                name: baseName !== undefined ? [
                    baseName,
                    key,
                    objKey
                ] : [
                    key,
                    objKey
                ],
                rules: generateRules(objProperty),
                style: {
                    marginBottom: 16
                }
            }, renderFormItem(objKey, objProperty));
        }));
    }, [
        getPropertyTitle,
        generateRules,
        locale
    ]);
    // 根据属性类型返回对应的表单组件
    var renderFormItem = useCallback(function(key, property, baseName) {
        switch(property.type){
            case 'array':
                return renderArrayFormItem(key, property, baseName);
            case 'object':
                return renderObjectFormItem(key, property, baseName);
            default:
                return renderBasicFormItem(property);
        }
    }, [
        renderArrayFormItem,
        renderObjectFormItem,
        renderBasicFormItem
    ]);
    // 计算默认值
    var defaultValues = useMemo(function() {
        return Object.entries(properties).reduce(function(acc, param) {
            var _param = _sliced_to_array(param, 2), key = _param[0], prop = _param[1];
            if (prop.default !== undefined) {
                acc[key] = prop.default;
            }
            return acc;
        }, {});
    }, [
        properties
    ]);
    // 设置初始值
    useEffect(function() {
        var mergedValues = merge({}, defaultValues, initialValues);
        form.setFieldsValue(mergedValues);
    }, [
        form,
        defaultValues,
        initialValues
    ]);
    // 生成表单项
    var formItems = useMemo(function() {
        return Object.entries(properties).map(function(param) {
            var _param = _sliced_to_array(param, 2), key = _param[0], property = _param[1];
            var shouldUseFormItemName = property.type !== 'object' && property.type !== 'array';
            return /*#__PURE__*/ React.createElement(Form.Item, {
                key: key,
                label: getPropertyTitle(property, key),
                name: shouldUseFormItemName ? key : undefined,
                rules: generateRules(property)
            }, renderFormItem(key, property));
        });
    }, [
        properties,
        getPropertyTitle,
        generateRules,
        renderFormItem
    ]);
    return /*#__PURE__*/ React.createElement(Form, {
        form: form,
        layout: "vertical",
        initialValues: defaultValues,
        onValuesChange: function onValuesChange1(_, allValues) {
            onValuesChange === null || onValuesChange === void 0 ? void 0 : onValuesChange(_, allValues);
        },
        style: {
            maxWidth: 400,
            padding: 24,
            background: '#fff',
            borderRadius: 8,
            boxShadow: '0 2px 8px rgba(0,0,0,0.15)'
        }
    }, formItems);
};
SchemaFormComponent.displayName = 'SchemaForm';
// 使用 React.memo 优化性能，避免不必要的重新渲染
export var SchemaForm = /*#__PURE__*/ memo(SchemaFormComponent);
