import * as __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__ from "react/jsx-runtime";
import * as __WEBPACK_EXTERNAL_MODULE_react__ from "react";
import * as __WEBPACK_EXTERNAL_MODULE__tachybase_schema__ from "@tachybase/schema";
import * as __WEBPACK_EXTERNAL_MODULE__ant_design_icons__ from "@ant-design/icons";
import * as __WEBPACK_EXTERNAL_MODULE_antd__ from "antd";
import * as __WEBPACK_EXTERNAL_MODULE_dayjs__ from "dayjs";
import * as __WEBPACK_EXTERNAL_MODULE_lodash__ from "lodash";
import * as __WEBPACK_EXTERNAL_MODULE_react_i18next__ from "react-i18next";
import * as __WEBPACK_EXTERNAL_MODULE_xlsx__ from "xlsx";
import * as __WEBPACK_EXTERNAL_MODULE__schema_component_index_mjs__ from "../../../schema-component/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__hooks_index_mjs__ from "../../hooks/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__XlsxCollectionSchema_mjs__ from "./XlsxCollectionSchema.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__XlsxEditFieldAction_mjs__ from "./XlsxEditFieldAction.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__xlsxFieldsConfigure_mjs__ from "./xlsxFieldsConfigure.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__xlsxPreviewTable_mjs__ from "./xlsxPreviewTable.mjs";
const { Dragger } = __WEBPACK_EXTERNAL_MODULE_antd__.Upload;
const ImportUpload = (props)=>{
    const { t } = (0, __WEBPACK_EXTERNAL_MODULE_react_i18next__.useTranslation)();
    const { close } = props;
    const { getInterface } = (0, __WEBPACK_EXTERNAL_MODULE__hooks_index_mjs__.useCollectionManager_deprecated)();
    const [fileList, setFile] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)([]);
    const [filedata, setFileData] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)({});
    const [visible, setVisible] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)(false);
    const [schema, setSchema] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)({});
    const inferType = (values, header)=>{
        const isDateHeader = /date|time|日期/i.test(header);
        const isPossibleDate = isDateHeader && values.every((value)=>(0, __WEBPACK_EXTERNAL_MODULE_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 = __WEBPACK_EXTERNAL_MODULE_xlsx__.read(binaryStr, {
                type: 'binary'
            });
            const firstSheetName = workbook.SheetNames[0];
            const worksheet = workbook.Sheets[firstSheetName];
            const jsonData = __WEBPACK_EXTERNAL_MODULE_xlsx__.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, __WEBPACK_EXTERNAL_MODULE_lodash__.cloneDeep)(interfaceConfig);
                const defaultUiSchema = (null == interfaceConfigValues ? void 0 : interfaceConfigValues.default.uiSchema) || {};
                const fieldsName = "f_".concat((0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.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;
                        __WEBPACK_EXTERNAL_MODULE_antd__.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) {
                __WEBPACK_EXTERNAL_MODULE_antd__.message.error(t('You can only upload Excel files!'));
                return __WEBPACK_EXTERNAL_MODULE_antd__.Upload.LIST_IGNORE;
            }
            handleFileUpload(file);
            setFile([
                file
            ]);
            return false;
        },
        fileList
    };
    return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsxs)(__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.Fragment, {
        children: [
            /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsxs)(Dragger, {
                maxCount: 1,
                ...importProps,
                children: [
                    /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)("p", {
                        className: "ant-upload-drag-icon",
                        children: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__ant_design_icons__.InboxOutlined, {})
                    }),
                    /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsxs)("p", {
                        className: "ant-upload-text",
                        children: [
                            " ",
                            t('Click or drag file to this area to upload')
                        ]
                    })
                ]
            }),
            /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsxs)(__WEBPACK_EXTERNAL_MODULE__schema_component_index_mjs__.ActionContextProvider, {
                value: {
                    visible,
                    setVisible
                },
                children: [
                    /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Button, {
                        type: "primary",
                        onClick: async ()=>{
                            const xlsxCollectionSchema = (0, __WEBPACK_EXTERNAL_MODULE__XlsxCollectionSchema_mjs__.createXlsxCollectionSchema)(fileList, filedata);
                            setSchema(xlsxCollectionSchema);
                            setVisible(true);
                            close();
                        },
                        disabled: 0 === fileList.length,
                        style: {
                            marginTop: 16
                        },
                        children: t('Upload')
                    }),
                    /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__schema_component_index_mjs__.SchemaComponent, {
                        schema: schema,
                        components: {
                            xlsxFieldsConfigure: __WEBPACK_EXTERNAL_MODULE__xlsxFieldsConfigure_mjs__.xlsxFieldsConfigure
                        },
                        scope: {
                            xlsxPreviewTable: __WEBPACK_EXTERNAL_MODULE__xlsxPreviewTable_mjs__.xlsxPreviewTable,
                            xlsxImportAction: __WEBPACK_EXTERNAL_MODULE__XlsxEditFieldAction_mjs__.xlsxImportAction
                        }
                    })
                ]
            })
        ]
    });
};
const ImportXlsxMetaAction = /*#__PURE__*/ __WEBPACK_EXTERNAL_MODULE_react__["default"].forwardRef((props, ref)=>{
    const { t } = (0, __WEBPACK_EXTERNAL_MODULE_react_i18next__.useTranslation)();
    const [isModalOpen, setIsModalOpen] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)(false);
    const [loading, setLoading] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)(false);
    const showModal = ()=>{
        setIsModalOpen(true);
    };
    (0, __WEBPACK_EXTERNAL_MODULE_react__.useImperativeHandle)(ref, ()=>({
            showModal
        }));
    const handleCancel = ()=>{
        setIsModalOpen(false);
    };
    return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.Fragment, {
        children: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Drawer, {
            title: t('Import collection'),
            footer: void 0,
            open: isModalOpen,
            onClose: handleCancel,
            children: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Spin, {
                spinning: loading,
                children: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(ImportUpload, {
                    close: handleCancel
                })
            })
        })
    });
});
export { ImportXlsxMetaAction };
