import { jsx } from "react/jsx-runtime";
import { useEffect, useState } from "react";
import { connect, isValid, mapProps, useField, useFieldSchema } from "@tachybase/schema";
import { Tree } from "antd";
import { useTranslation } from "react-i18next";
import { useSchemaToolbar } from "../../../application/index.mjs";
import { SchemaSettings } from "../../../application/schema-settings/SchemaSettings.mjs";
import { useCollection_deprecated } from "../../../collection-manager/index.mjs";
import { OpenMode, useActionContext, useDesignable } from "../../../schema-component/index.mjs";
import { AfterSuccess, ButtonEditor, RemoveButton, SecondConFirm, WorkflowConfig, findSchema } from "../../../schema-component/antd/action/Action.Designer.mjs";
import { useCollectionState } from "../../../schema-settings/DataTemplates/hooks/useCollectionState.mjs";
import { SchemaSettingsModalItem } from "../../../schema-settings/SchemaSettings.mjs";
const createSubmitActionSettings_Tree = connect(Tree, mapProps((props, field)=>{
    useEffect(()=>{
        field.value = props.defaultCheckedKeys || [];
    }, [
        field.value,
        props.defaultCheckedKeys
    ]);
    const [checkedKeys, setCheckedKeys] = useState(props.defaultCheckedKeys || []);
    const onCheck = (checkedKeys)=>{
        setCheckedKeys(checkedKeys);
        field.value = checkedKeys;
    };
    field.onCheck = onCheck;
    return {
        ...props,
        checkedKeys,
        onCheck
    };
}));
function SaveMode() {
    const { dn } = useDesignable();
    const { t } = useTranslation();
    const field = useField();
    const fieldSchema = useFieldSchema();
    const { name } = useCollection_deprecated();
    const { getEnableFieldTree, getOnLoadData } = useCollectionState(name);
    return /*#__PURE__*/ jsx(SchemaSettingsModalItem, {
        title: t('Save mode'),
        components: {
            Tree: createSubmitActionSettings_Tree
        },
        scope: {
            getEnableFieldTree,
            name,
            getOnLoadData
        },
        schema: {
            type: 'object',
            title: t('Save mode'),
            properties: {
                saveMode: {
                    'x-decorator': 'FormItem',
                    'x-component': 'Radio.Group',
                    default: field.componentProps.saveMode || 'create',
                    enum: [
                        {
                            value: 'create',
                            label: '{{t("Insert")}}'
                        },
                        {
                            value: 'firstOrCreate',
                            label: '{{t("Insert if not exists")}}'
                        },
                        {
                            value: 'updateOrCreate',
                            label: '{{t("Insert if not exists, or update")}}'
                        }
                    ]
                },
                filterKeys: {
                    type: 'array',
                    title: '{{ t("Determine whether a record exists by the following fields") }}',
                    required: true,
                    default: field.componentProps.filterKeys,
                    'x-decorator': 'FormItem',
                    'x-component': 'Tree',
                    'x-component-props': {
                        treeData: [],
                        checkable: true,
                        checkStrictly: true,
                        selectable: false,
                        loadData: '{{ getOnLoadData($self) }}',
                        defaultCheckedKeys: field.componentProps.filterKeys,
                        rootStyle: {
                            padding: '8px 0',
                            border: '1px solid #d9d9d9',
                            borderRadius: '2px',
                            maxHeight: '30vh',
                            overflow: 'auto',
                            margin: '2px 0'
                        }
                    },
                    'x-reactions': [
                        {
                            dependencies: [
                                '.saveMode'
                            ],
                            fulfill: {
                                state: {
                                    hidden: '{{ $deps[0]==="create"}}',
                                    componentProps: {
                                        treeData: '{{ getEnableFieldTree(name, $self) }}'
                                    }
                                }
                            }
                        }
                    ]
                }
            }
        },
        onSubmit: (param)=>{
            let { saveMode, filterKeys } = param;
            field.componentProps.saveMode = saveMode;
            field.componentProps.filterKeys = filterKeys;
            fieldSchema['x-component-props'] = fieldSchema['x-component-props'] || {};
            fieldSchema['x-component-props'].saveMode = saveMode;
            fieldSchema['x-component-props'].filterKeys = filterKeys;
            dn.emit('patch', {
                schema: {
                    ['x-uid']: fieldSchema['x-uid'],
                    'x-component-props': {
                        ...fieldSchema['x-component-props']
                    }
                }
            });
            dn.refresh();
        }
    });
}
const createSubmitActionSettings = new SchemaSettings({
    name: 'actionSettings:createSubmit',
    items: [
        {
            name: 'editButton',
            Component: ButtonEditor,
            useComponentProps () {
                const { buttonEditorProps } = useSchemaToolbar();
                return buttonEditorProps;
            }
        },
        {
            name: 'secondConfirmation',
            Component: SecondConFirm
        },
        {
            name: 'afterSuccessfulSubmission',
            Component: AfterSuccess
        },
        {
            name: 'jumpDetails',
            type: 'switch',
            useVisible () {
                const { fieldSchema } = useActionContext();
                const openMode = findSchema(fieldSchema);
                return !openMode || openMode === OpenMode.PAGE;
            },
            useComponentProps () {
                var _fieldSchema_xactionsettings;
                const { t } = useTranslation();
                const fieldSchema = useFieldSchema();
                const field = useField();
                const { dn, refresh } = useDesignable();
                return {
                    title: t('Jump details'),
                    checked: null == fieldSchema ? void 0 : null == (_fieldSchema_xactionsettings = fieldSchema['x-action-settings']) ? void 0 : _fieldSchema_xactionsettings.pageMode,
                    onChange (checked) {
                        const schema = {
                            'x-uid': fieldSchema['x-uid']
                        };
                        field['actionSetting'] = {
                            ...null == field ? void 0 : field['ationSetting'],
                            pageMode: checked
                        };
                        fieldSchema['x-action-settings'] = {
                            ...null == fieldSchema ? void 0 : fieldSchema['x-action-settings'],
                            pageMode: checked
                        };
                        schema['x-action-settings'] = fieldSchema['x-action-settings'];
                        dn.emit('patch', {
                            schema
                        });
                        refresh();
                    }
                };
            }
        },
        {
            name: 'workflowConfig',
            Component: WorkflowConfig,
            useVisible () {
                var _fieldSchema_xactionsettings;
                const fieldSchema = useFieldSchema();
                return isValid(null == fieldSchema ? void 0 : null == (_fieldSchema_xactionsettings = fieldSchema['x-action-settings']) ? void 0 : _fieldSchema_xactionsettings.triggerWorkflows);
            }
        },
        {
            name: 'saveMode',
            Component: SaveMode
        },
        {
            name: 'remove',
            sort: 100,
            Component: RemoveButton,
            useComponentProps () {
                const { removeButtonProps } = useSchemaToolbar();
                return removeButtonProps;
            }
        }
    ]
});
export { SaveMode, createSubmitActionSettings };
