"use strict";
var __webpack_require__ = {};
(()=>{
    __webpack_require__.n = function(module) {
        var getter = module && module.__esModule ? function() {
            return module['default'];
        } : function() {
            return module;
        };
        __webpack_require__.d(getter, {
            a: getter
        });
        return getter;
    };
})();
(()=>{
    __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__, {
    ImportXlsxMetaAction: ()=>ImportXlsxMetaAction
});
const jsx_runtime_namespaceObject = require("react/jsx-runtime");
const external_react_namespaceObject = require("react");
var external_react_default = /*#__PURE__*/ __webpack_require__.n(external_react_namespaceObject);
const schema_namespaceObject = require("@tachybase/schema");
const icons_namespaceObject = require("@ant-design/icons");
const external_antd_namespaceObject = require("antd");
const external_dayjs_namespaceObject = require("dayjs");
var external_dayjs_default = /*#__PURE__*/ __webpack_require__.n(external_dayjs_namespaceObject);
const external_lodash_namespaceObject = require("lodash");
const external_react_i18next_namespaceObject = require("react-i18next");
const external_xlsx_namespaceObject = require("xlsx");
const index_js_namespaceObject = require("../../../schema-component/index.js");
const external_hooks_index_js_namespaceObject = require("../../hooks/index.js");
const external_XlsxCollectionSchema_js_namespaceObject = require("./XlsxCollectionSchema.js");
const external_XlsxEditFieldAction_js_namespaceObject = require("./XlsxEditFieldAction.js");
const external_xlsxFieldsConfigure_js_namespaceObject = require("./xlsxFieldsConfigure.js");
const external_xlsxPreviewTable_js_namespaceObject = require("./xlsxPreviewTable.js");
const { Dragger } = external_antd_namespaceObject.Upload;
const ImportUpload = (props)=>{
    const { t } = (0, external_react_i18next_namespaceObject.useTranslation)();
    const { close } = props;
    const { getInterface } = (0, external_hooks_index_js_namespaceObject.useCollectionManager_deprecated)();
    const [fileList, setFile] = (0, external_react_namespaceObject.useState)([]);
    const [filedata, setFileData] = (0, external_react_namespaceObject.useState)({});
    const [visible, setVisible] = (0, external_react_namespaceObject.useState)(false);
    const [schema, setSchema] = (0, external_react_namespaceObject.useState)({});
    const inferType = (values, header)=>{
        const isDateHeader = /date|time|日期/i.test(header);
        const isPossibleDate = isDateHeader && values.every((value)=>external_dayjs_default()(value).isValid());
        if (isPossibleDate) return 'date';
        const types = values.map((value)=>{
            if (null != value) {
                const valueLower = value.toString().toLowerCase();
                if ('true' === valueLower || 'yes' === valueLower) return 'boolean';
                if ('false' === valueLower || 'no' === valueLower) return 'boolean';
            }
            const num = Number(value);
            if (!isNaN(num)) return Number.isInteger(num) ? 'integer' : 'float';
            try {
                JSON.parse(value);
                return 'json';
            } catch  {}
            return 'string';
        });
        const typeCount = types.reduce((acc, type)=>{
            acc[type] = (acc[type] || 0) + 1;
            return acc;
        }, {});
        const uniqueTypes = Object.keys(typeCount);
        if (uniqueTypes.length > 1) return 'string';
        return uniqueTypes[0];
    };
    const inferInterface = (type, header)=>{
        switch(type){
            case 'json':
                return 'json';
            case 'boolean':
                return 'checkbox';
            case 'string':
                return 'input';
            case 'integer':
                return 'integer';
            case 'float':
                return 'number';
            case 'date':
                return 'datetime';
            default:
                return null;
        }
    };
    const handleFileUpload = (file)=>{
        const reader = new FileReader();
        reader.onload = async (e)=>{
            const binaryStr = e.target.result;
            const workbook = external_xlsx_namespaceObject.read(binaryStr, {
                type: 'binary'
            });
            const firstSheetName = workbook.SheetNames[0];
            const worksheet = workbook.Sheets[firstSheetName];
            const jsonData = external_xlsx_namespaceObject.utils.sheet_to_json(worksheet, {
                header: 1
            });
            if (0 === jsonData.length) return;
            const headers = jsonData[0];
            const rows = jsonData.slice(1);
            const fields = await Promise.all(headers.map(async (header, index)=>{
                const columnValues = rows.map((row)=>row[index]);
                const type = inferType(columnValues, header);
                const interfaceType = type ? inferInterface(type, header) : null;
                const interfaceConfig = interfaceType ? getInterface(interfaceType) : null;
                const interfaceConfigValues = (0, external_lodash_namespaceObject.cloneDeep)(interfaceConfig);
                const defaultUiSchema = (null == interfaceConfigValues ? void 0 : interfaceConfigValues.default.uiSchema) || {};
                const fieldsName = "f_".concat((0, schema_namespaceObject.uid)());
                return {
                    name: fieldsName,
                    type,
                    interface: interfaceType,
                    uiSchema: {
                        title: header,
                        ...defaultUiSchema
                    }
                };
            }));
            const parseValue = (value, type)=>{
                try {
                    switch(type){
                        case 'boolean':
                            {
                                const valueLower = value.toString().toLowerCase();
                                if ('true' === valueLower || 'yes' === valueLower) return true;
                                if ('false' === valueLower || 'no' === valueLower) 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 convertedRows = rows.map((row, rowIndex)=>headers.reduce((acc, header, index)=>{
                    var _fields_index, _fields_index1;
                    const fieldsName = null === (_fields_index = fields[index]) || void 0 === _fields_index ? void 0 : _fields_index.name;
                    const type = null === (_fields_index1 = fields[index]) || void 0 === _fields_index1 ? void 0 : _fields_index1.type;
                    if (fieldsName && type) try {
                        const convertedValue = parseValue(row[index], type);
                        acc[fieldsName] = convertedValue;
                    } catch (error) {
                        acc[fieldsName] = null;
                        external_antd_namespaceObject.message.error('Error in column "'.concat(header, '" at row ').concat(rowIndex + 1, ": ").concat(error.message));
                    }
                    return acc;
                }, {}));
            const fileData = {
                fields: fields,
                data: convertedRows
            };
            setFileData(fileData);
        };
        reader.readAsBinaryString(file);
    };
    const importProps = {
        onRemove: (file)=>{
            const index = fileList.indexOf(file);
            const newFileList = fileList.slice();
            newFileList.splice(index, 1);
            setFile(newFileList);
        },
        beforeUpload: (file)=>{
            const isExcel = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' === file.type || file.name.endsWith('.xlsx') || file.name.endsWith('.xls');
            if (!isExcel) {
                external_antd_namespaceObject.message.error(t('You can only upload Excel files!'));
                return external_antd_namespaceObject.Upload.LIST_IGNORE;
            }
            handleFileUpload(file);
            setFile([
                file
            ]);
            return false;
        },
        fileList
    };
    return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)(jsx_runtime_namespaceObject.Fragment, {
        children: [
            /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)(Dragger, {
                maxCount: 1,
                ...importProps,
                children: [
                    /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("p", {
                        className: "ant-upload-drag-icon",
                        children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(icons_namespaceObject.InboxOutlined, {})
                    }),
                    /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("p", {
                        className: "ant-upload-text",
                        children: [
                            " ",
                            t('Click or drag file to this area to upload')
                        ]
                    })
                ]
            }),
            /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)(index_js_namespaceObject.ActionContextProvider, {
                value: {
                    visible,
                    setVisible
                },
                children: [
                    /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(external_antd_namespaceObject.Button, {
                        type: "primary",
                        onClick: async ()=>{
                            const xlsxCollectionSchema = (0, external_XlsxCollectionSchema_js_namespaceObject.createXlsxCollectionSchema)(fileList, filedata);
                            setSchema(xlsxCollectionSchema);
                            setVisible(true);
                            close();
                        },
                        disabled: 0 === fileList.length,
                        style: {
                            marginTop: 16
                        },
                        children: t('Upload')
                    }),
                    /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(index_js_namespaceObject.SchemaComponent, {
                        schema: schema,
                        components: {
                            xlsxFieldsConfigure: external_xlsxFieldsConfigure_js_namespaceObject.xlsxFieldsConfigure
                        },
                        scope: {
                            xlsxPreviewTable: external_xlsxPreviewTable_js_namespaceObject.xlsxPreviewTable,
                            xlsxImportAction: external_XlsxEditFieldAction_js_namespaceObject.xlsxImportAction
                        }
                    })
                ]
            })
        ]
    });
};
const ImportXlsxMetaAction = /*#__PURE__*/ external_react_default().forwardRef((props, ref)=>{
    const { t } = (0, external_react_i18next_namespaceObject.useTranslation)();
    const [isModalOpen, setIsModalOpen] = (0, external_react_namespaceObject.useState)(false);
    const [loading, setLoading] = (0, external_react_namespaceObject.useState)(false);
    const showModal = ()=>{
        setIsModalOpen(true);
    };
    (0, external_react_namespaceObject.useImperativeHandle)(ref, ()=>({
            showModal
        }));
    const handleCancel = ()=>{
        setIsModalOpen(false);
    };
    return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(jsx_runtime_namespaceObject.Fragment, {
        children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(external_antd_namespaceObject.Drawer, {
            title: t('Import collection'),
            footer: void 0,
            open: isModalOpen,
            onClose: handleCancel,
            children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(external_antd_namespaceObject.Spin, {
                spinning: loading,
                children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(ImportUpload, {
                    close: handleCancel
                })
            })
        })
    });
});
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
});
