import * as __WEBPACK_EXTERNAL_MODULE__tachybase_schema__ from "@tachybase/schema";
import * as __WEBPACK_EXTERNAL_MODULE_antd__ from "antd";
import * as __WEBPACK_EXTERNAL_MODULE_lodash__ from "lodash";
import * as __WEBPACK_EXTERNAL_MODULE_react_i18next__ from "react-i18next";
import * as __WEBPACK_EXTERNAL_MODULE__schema_component_index_mjs__ from "../../../schema-component/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__xlsxFormValueContextProvider_mjs__ from "./xlsxFormValueContextProvider.mjs";
const setUpdateXlsxCollectionField = ()=>{
    const form = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useForm)();
    const { value, setFormValue } = (0, __WEBPACK_EXTERNAL_MODULE__xlsxFormValueContextProvider_mjs__.useFormValueContext)();
    const ctx = (0, __WEBPACK_EXTERNAL_MODULE__schema_component_index_mjs__.useActionContext)();
    const { t } = (0, __WEBPACK_EXTERNAL_MODULE_react_i18next__.useTranslation)();
    const handleFieldChange = (index, updatedField)=>{
        const updatedFieldData = [
            ...value
        ];
        if (updatedField.primaryKey) {
            const existingPrimaryKey = updatedFieldData.find((field, i)=>true === field.primaryKey && i !== index);
            if (existingPrimaryKey) {
                __WEBPACK_EXTERNAL_MODULE_antd__.message.error(t('existingPrimaryKeyError', {
                    name: existingPrimaryKey.name
                }));
                return;
            }
        }
        updatedFieldData[index] = updatedField;
        setFormValue(updatedFieldData);
    };
    return {
        async onClick () {
            await form.submit();
            const values = (0, __WEBPACK_EXTERNAL_MODULE_lodash__.cloneDeep)(form.values);
            values.autoCreateReverseField || delete values.reverseField;
            delete values.autoCreateReverseField;
            const { index, ...updatedField } = values;
            if (index < 0 || index >= value.length) {
                __WEBPACK_EXTERNAL_MODULE_antd__.message.error('Invalid field index');
                return;
            }
            handleFieldChange(index, updatedField);
            ctx.setVisible(false);
        }
    };
};
export { setUpdateXlsxCollectionField };
