"use strict";
var __webpack_require__ = {};
(()=>{
    __webpack_require__.d = function(exports1, definition) {
        for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
            enumerable: true,
            get: definition[key]
        });
    };
})();
(()=>{
    __webpack_require__.o = function(obj, prop) {
        return Object.prototype.hasOwnProperty.call(obj, prop);
    };
})();
(()=>{
    __webpack_require__.r = function(exports1) {
        if ('undefined' != typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
            value: 'Module'
        });
        Object.defineProperty(exports1, '__esModule', {
            value: true
        });
    };
})();
var __webpack_exports__ = {};
__webpack_require__.r(__webpack_exports__);
__webpack_require__.d(__webpack_exports__, {
    xlsxFieldsConfigure: ()=>xlsxFieldsConfigure
});
const jsx_runtime_namespaceObject = require("react/jsx-runtime");
const external_react_namespaceObject = require("react");
const schema_namespaceObject = require("@tachybase/schema");
const external_antd_namespaceObject = require("antd");
const external_lodash_namespaceObject = require("lodash");
const external_react_i18next_namespaceObject = require("react-i18next");
const index_js_namespaceObject = require("../../../data-source/index.js");
const external_schema_component_index_js_namespaceObject = require("../../../schema-component/index.js");
const external_hooks_index_js_namespaceObject = require("../../hooks/index.js");
const external_interfaces_js_namespaceObject = require("../interfaces.js");
const external_xlsxFormValueContextProvider_js_namespaceObject = require("./xlsxFormValueContextProvider.js");
const external_xlsxImportAction_js_namespaceObject = require("./xlsxImportAction.js");
const xlsxFieldsConfigure = (0, schema_namespaceObject.observer)((props)=>{
    const { filedata } = props;
    const { fields, data } = filedata;
    (0, index_js_namespaceObject.useDataSourceManager)();
    const { t } = (0, external_react_i18next_namespaceObject.useTranslation)();
    const initOptions = (0, external_interfaces_js_namespaceObject.useFieldInterfaceOptions)();
    const compile = (0, external_schema_component_index_js_namespaceObject.useCompile)();
    const [selectedTitleField, setSelectedTitleField] = (0, external_react_namespaceObject.useState)();
    const form = (0, schema_namespaceObject.useForm)();
    const [formValue, setFormValue] = (0, external_react_namespaceObject.useState)(fields);
    const { getInterface } = (0, external_hooks_index_js_namespaceObject.useCollectionManager_deprecated)();
    const getDefaultUiSchema = (interfaceType, title)=>{
        var _interfaceConfigValues_default;
        const interfaceConfig = getInterface(interfaceType) || {};
        const interfaceConfigValues = (0, external_lodash_namespaceObject.cloneDeep)(interfaceConfig);
        const defaultUiSchema = (null == interfaceConfigValues ? void 0 : null === (_interfaceConfigValues_default = interfaceConfigValues.default) || void 0 === _interfaceConfigValues_default ? void 0 : _interfaceConfigValues_default.uiSchema) || {};
        return {
            ...defaultUiSchema,
            title
        };
    };
    const handleFieldChange = (updatedField, index)=>{
        const updatedFieldData = [
            ...formValue
        ];
        updatedFieldData[index] = updatedField;
        setFormValue(updatedFieldData);
    };
    const handleFieldTypeChange = async (updatedField, index)=>{
        const { type, name: dataIndex, uiSchema } = updatedField;
        const updatedData = [
            ...data
        ];
        let hasError = false;
        const typeToInterface = {
            json: 'json',
            boolean: 'checkbox',
            string: 'input',
            integer: 'integer',
            float: 'number',
            date: 'datetime'
        };
        updatedField.interface = await typeToInterface[type] || null;
        const currentUiSchema = await getDefaultUiSchema(updatedField.interface, uiSchema.title);
        updatedField.uiSchema = currentUiSchema;
        updatedData.forEach((row, rowIndex)=>{
            try {
                if (void 0 !== row[dataIndex]) row[dataIndex] = parseValue(row[dataIndex], type);
            } catch (error) {
                hasError = true;
                external_antd_namespaceObject.message.error("Row ".concat(rowIndex + 1, ", Column ").concat(uiSchema.title, ": ").concat(error.message));
            }
        });
        if (!hasError) {
            external_antd_namespaceObject.message.success("".concat(t('Fields'), ' "').concat(uiSchema.title, '"').concat(t('Converted to'), " ").concat(type));
            const updatedFieldData = [
                ...formValue
            ];
            updatedFieldData[index] = updatedField;
            setFormValue(updatedFieldData);
        }
    };
    const handleFieldInterfaceChange = async (updatedField, index)=>{
        const currentUiSchema = await getDefaultUiSchema(updatedField.interface, updatedField.uiSchema.title);
        updatedField.uiSchema = currentUiSchema;
        const updatedFieldData = [
            ...formValue
        ];
        updatedFieldData[index] = updatedField;
        setFormValue(updatedFieldData);
    };
    const parseValue = (value, type)=>{
        try {
            switch(type){
                case 'boolean':
                    if ('true' === value.toLowerCase()) return true;
                    if ('false' === value.toLowerCase()) return false;
                    throw new Error('Invalid boolean');
                case 'integer':
                    if (!/^-?\d+$/.test(value)) throw new Error('Invalid integer');
                    return parseInt(value, 10);
                case 'float':
                    if (!/^-?\d+(\.\d+)?$/.test(value)) throw new Error('Invalid number');
                    return Number(value);
                case 'json':
                    return JSON.parse(value);
                case 'date':
                    if (isNaN(Date.parse(value))) throw new Error('Invalid date');
                    return new Date(value);
                default:
                    if (null == value || '' === value) return '';
                    return value.toString();
            }
        } catch (error) {
            throw new Error("Type conversion error: ".concat(error.message));
        }
    };
    const handleTitleChange = (checked, field)=>{
        const newTitleField = checked ? field.name : null;
        setSelectedTitleField(newTitleField);
        form.setValuesIn('titleField', newTitleField);
    };
    const isTitleField = (field)=>{
        var _getInterface;
        return !field.isForeignKey && (null === (_getInterface = getInterface(field.interface)) || void 0 === _getInterface ? void 0 : _getInterface.titleUsable);
    };
    const getOptions = (type)=>{
        const InterfaceOptions = getInterfaceOptions(initOptions, type);
        const options = InterfaceOptions.map((group)=>({
                label: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("span", {
                    children: compile(group.label)
                }),
                title: group.key,
                options: group.children.map((item)=>({
                        label: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("span", {
                            children: compile(item.label)
                        }),
                        value: item.name
                    }))
            }));
        return options;
    };
    const getInterfaceOptions = (data, type)=>{
        const interfaceOptions = [];
        data.forEach((item)=>{
            const options = item.children.filter((h)=>{
                var _h_availableTypes;
                return null == h ? void 0 : null === (_h_availableTypes = h.availableTypes) || void 0 === _h_availableTypes ? void 0 : _h_availableTypes.includes(type);
            });
            interfaceOptions.push({
                label: item.label,
                key: item.key,
                children: options
            });
        });
        return interfaceOptions.filter((v)=>{
            if ('sort' === type) return 'advanced' === v.key;
            return v.children.length > 0;
        });
    };
    const columns = [
        {
            title: t('Field display name'),
            dataIndex: 'title',
            key: 'title',
            render: (text, record, index)=>{
                const field = formValue[index];
                return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(external_antd_namespaceObject.Input, {
                    value: field.uiSchema.title || text,
                    onChange: (e)=>handleFieldChange({
                            ...field,
                            uiSchema: {
                                title: e.target.value
                            }
                        }, index)
                });
            }
        },
        {
            title: t('Field name'),
            dataIndex: 'name',
            key: 'name',
            render: (text, record, index)=>{
                const field = formValue[index];
                return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(external_antd_namespaceObject.Input, {
                    value: field.name || text,
                    variant: "borderless",
                    disabled: true
                });
            }
        },
        {
            title: t('Field type'),
            dataIndex: 'type',
            key: 'type',
            render: (text, record, index)=>{
                const field = formValue[index];
                return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(external_antd_namespaceObject.Select, {
                    value: field.type || text,
                    onChange: (e)=>handleFieldTypeChange({
                            ...field,
                            type: e
                        }, index),
                    options: [
                        {
                            value: 'string',
                            label: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("span", {
                                children: "string"
                            })
                        },
                        {
                            value: 'boolean',
                            label: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("span", {
                                children: "boolean"
                            })
                        },
                        {
                            value: 'integer',
                            label: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("span", {
                                children: "integer"
                            })
                        },
                        {
                            value: 'float',
                            label: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("span", {
                                children: "float"
                            })
                        },
                        {
                            value: 'json',
                            label: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("span", {
                                children: "json"
                            })
                        },
                        {
                            value: 'date',
                            label: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("span", {
                                children: "date"
                            })
                        }
                    ]
                });
            }
        },
        {
            title: t('Field interface'),
            dataIndex: 'interface',
            key: 'interface',
            render: (text, record, index)=>{
                const field = formValue[index];
                const options = getOptions(field.type);
                return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(external_antd_namespaceObject.Select, {
                    "aria-label": "field-interface-".concat(null == field ? void 0 : field.type),
                    role: "button",
                    value: field.interface,
                    popupMatchSelectWidth: false,
                    onChange: (e)=>handleFieldInterfaceChange({
                            ...field,
                            interface: e
                        }, index),
                    options: options
                });
            }
        },
        {
            dataIndex: 'titleField',
            title: t('Title field'),
            render: function(_, record, index) {
                const field = formValue[index];
                return isTitleField(field) ? /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(external_antd_namespaceObject.Tooltip, {
                    title: t('Default title for each record'),
                    placement: "right",
                    overlayInnerStyle: {
                        textAlign: 'center'
                    },
                    children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(external_antd_namespaceObject.Switch, {
                        "aria-label": "switch-title-field-".concat(field.name),
                        size: "small",
                        checked: field.name === selectedTitleField,
                        onChange: (checked)=>handleTitleChange(checked, field)
                    })
                }) : null;
            }
        },
        {
            title: t('Description'),
            dataIndex: 'description',
            key: 'description',
            render: (text, record, index)=>{
                const field = formValue[index];
                return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(external_antd_namespaceObject.Input.TextArea, {
                    value: field.description,
                    variant: "borderless",
                    disabled: true
                });
            }
        },
        {
            title: t('Actions'),
            dataIndex: 'actions',
            key: 'actions',
            render: (text, record, index)=>{
                const field = formValue[index];
                return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(external_antd_namespaceObject.Space, {
                    size: "middle",
                    children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(external_xlsxImportAction_js_namespaceObject.XlsxEditFieldAction, {
                        record: {
                            index,
                            ...field
                        },
                        ...props
                    })
                });
            }
        }
    ];
    const previewTablecolumns = formValue.map((field)=>({
            title: field.uiSchema.title,
            dataIndex: field.name,
            key: field.name,
            render: (text)=>{
                if ('boolean' == typeof text) return text ? 'True' : 'False';
                if ('date' === field.type && text) return new Date(text).toLocaleString();
                if ('json' === field.type && text) try {
                    return 'string' == typeof text ? text : JSON.stringify(text, null, 2);
                } catch (error) {
                    return 'Invalid JSON';
                }
                return text;
            },
            width: 200
        }));
    (0, external_react_namespaceObject.useEffect)(()=>{
        form.setValuesIn('fields', formValue);
        form.setValuesIn('collectionData', filedata.data);
        console.log('%c Line:294 🍔 filedata.data', 'font-size:18px;color:#42b983;background:#3f7cff', filedata.data);
    }, [
        formValue
    ]);
    return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)(external_xlsxFormValueContextProvider_js_namespaceObject.xlsxFormValueContext.Provider, {
        value: {
            value: formValue,
            setFormValue
        },
        children: [
            /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(external_antd_namespaceObject.Table, {
                bordered: true,
                size: "small",
                columns: columns,
                dataSource: formValue,
                scroll: {
                    y: 300
                },
                pagination: false,
                rowClassName: "row",
                rowKey: "uid",
                style: {
                    marginBottom: '16px'
                },
                ...props
            }),
            /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("div", {
                style: {
                    fontWeight: 'bold',
                    marginBottom: '10px'
                },
                children: [
                    t('Preview'),
                    ":"
                ]
            }),
            /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(external_antd_namespaceObject.Table, {
                bordered: true,
                size: "small",
                columns: previewTablecolumns,
                dataSource: filedata.data,
                scroll: {
                    y: 300,
                    x: 'max-content'
                },
                rowKey: "name"
            })
        ]
    });
}, {
    displayName: 'FieldsConfigure'
});
var __webpack_export_target__ = exports;
for(var __webpack_i__ in __webpack_exports__)__webpack_export_target__[__webpack_i__] = __webpack_exports__[__webpack_i__];
if (__webpack_exports__.__esModule) Object.defineProperty(__webpack_export_target__, '__esModule', {
    value: true
});
