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