import { jsx } from "react/jsx-runtime";
import "react";
import { useField, useFieldSchema } from "@tachybase/schema";
import lodash from "lodash";
import { useTranslation } from "react-i18next";
import { SchemaSettings } from "../../../../application/schema-settings/SchemaSettings.mjs";
import { useFormBlockContext } from "../../../../block-provider/index.mjs";
import { useCollectionManager_deprecated, useCollection_deprecated } from "../../../../collection-manager/index.mjs";
import { useFieldComponentName } from "../../../../common/useFieldComponentName.mjs";
import { useCollectionField, useDataSourceManager } from "../../../../data-source/index.mjs";
import { useRecord } from "../../../../record-provider/index.mjs";
import { removeNullCondition, useCompile, useDesignable, useFieldModeOptions, useIsAddNewForm } from "../../../../schema-component/index.mjs";
import { isSubMode } from "../../../../schema-component/antd/association-field/util.mjs";
import { useIsAssociationField, useIsFieldReadPretty, useIsSelectFieldMode, useTitleFieldOptions } from "../../../../schema-component/antd/form-item/FormItem.Settings.mjs";
import { useColumnSchema } from "../../../../schema-component/antd/table-v2/Table.Column.Decorator.mjs";
import { VariableInput, getShouldChange, useFormulaTitleOptions } from "../../../../schema-settings/index.mjs";
import { useIsShowMultipleSwitch } from "../../../../schema-settings/hooks/useIsShowMultipleSwitch.mjs";
import { SchemaSettingsDataScope } from "../../../../schema-settings/SchemaSettingsDataScope.mjs";
import { SchemaSettingsSortingRule } from "../../../../schema-settings/SchemaSettingsSortingRule.mjs";
import { useLocalVariables, useVariables } from "../../../../variables/index.mjs";
const enableLink = {
    name: 'enableLink',
    type: 'switch',
    useVisible () {
        const field = useField();
        return field.readPretty;
    },
    useComponentProps () {
        var _fieldSchema_xcomponentprops;
        const { t } = useTranslation();
        const field = useField();
        const { fieldSchema: tableColumnSchema } = useColumnSchema();
        const schema = useFieldSchema();
        const fieldSchema = tableColumnSchema || schema;
        const { dn } = useDesignable();
        return {
            title: t('Enable link'),
            checked: (null == (_fieldSchema_xcomponentprops = fieldSchema['x-component-props']) ? void 0 : _fieldSchema_xcomponentprops.enableLink) !== false,
            onChange (flag) {
                fieldSchema['x-component-props'] = {
                    ...null == fieldSchema ? void 0 : fieldSchema['x-component-props'],
                    enableLink: flag
                };
                field.componentProps['enableLink'] = flag;
                dn.emit('patch', {
                    schema: {
                        'x-uid': fieldSchema['x-uid'],
                        'x-component-props': {
                            ...null == fieldSchema ? void 0 : fieldSchema['x-component-props']
                        }
                    }
                });
                dn.refresh();
            }
        };
    }
};
const titleField = {
    name: 'titleField',
    type: 'select',
    useComponentProps () {
        var _collectionField_uiSchema_xcomponentprops, _collectionField_uiSchema, _field_componentProps, _fieldSchema_xcomponentprops;
        const { t } = useTranslation();
        const field = useField();
        const { dn } = useDesignable();
        const options = useTitleFieldOptions();
        const { uiSchema, fieldSchema: tableColumnSchema, collectionField: tableColumnField } = useColumnSchema();
        const schema = useFieldSchema();
        const fieldSchema = tableColumnSchema || schema;
        const targetCollectionField = useCollectionField();
        const collectionField = tableColumnField || targetCollectionField;
        const { getCollectionFields } = useCollectionManager_deprecated();
        const fieldNames = {
            ...null == collectionField ? void 0 : null == (_collectionField_uiSchema = collectionField.uiSchema) ? void 0 : null == (_collectionField_uiSchema_xcomponentprops = _collectionField_uiSchema['x-component-props']) ? void 0 : _collectionField_uiSchema_xcomponentprops['fieldNames'],
            ...null == field ? void 0 : null == (_field_componentProps = field.componentProps) ? void 0 : _field_componentProps.fieldNames,
            ...null == fieldSchema ? void 0 : null == (_fieldSchema_xcomponentprops = fieldSchema['x-component-props']) ? void 0 : _fieldSchema_xcomponentprops['fieldNames']
        };
        return {
            title: t('Title field'),
            options,
            value: null == fieldNames ? void 0 : fieldNames.label,
            onChange (label) {
                var _collectionField_uiSchema_xcomponentprops, _collectionField_uiSchema, _fieldSchema_xcomponentprops, _field_path, _field_path1;
                const schema = {
                    ['x-uid']: fieldSchema['x-uid']
                };
                const newFieldNames = {
                    ...null == collectionField ? void 0 : null == (_collectionField_uiSchema = collectionField.uiSchema) ? void 0 : null == (_collectionField_uiSchema_xcomponentprops = _collectionField_uiSchema['x-component-props']) ? void 0 : _collectionField_uiSchema_xcomponentprops['fieldNames'],
                    ...null == (_fieldSchema_xcomponentprops = fieldSchema['x-component-props']) ? void 0 : _fieldSchema_xcomponentprops['fieldNames'],
                    label
                };
                fieldSchema['x-component-props'] = fieldSchema['x-component-props'] || {};
                fieldSchema['x-component-props']['fieldNames'] = newFieldNames;
                const target = getCollectionFields(collectionField.target).find((field)=>field.name === label);
                if ('m2o' === target.interface) fieldSchema['x-component-props']['x-next-title'] = {
                    label,
                    collection: target.collectionName
                };
                else fieldSchema['x-component-props']['x-next-title'] = null;
                schema['x-component-props'] = fieldSchema['x-component-props'];
                field.componentProps.fieldNames = fieldSchema['x-component-props'].fieldNames;
                const path = null == (_field_path1 = field.path) ? void 0 : _field_path1.splice((null == (_field_path = field.path) ? void 0 : _field_path.length) - 1, 1);
                field.form.query("".concat(path.concat("*." + fieldSchema.name))).forEach((f)=>{
                    f.componentProps.fieldNames = fieldNames;
                });
                dn.emit('patch', {
                    schema
                });
                dn.refresh();
            }
        };
    }
};
const allowMultiple = {
    name: 'allowMultiple',
    type: 'switch',
    useVisible () {
        const isFieldReadPretty = useIsFieldReadPretty();
        const collectionField = useCollectionField();
        return !isFieldReadPretty && [
            'hasMany',
            'belongsToMany'
        ].includes(null == collectionField ? void 0 : collectionField.type);
    },
    useComponentProps () {
        const { t } = useTranslation();
        const field = useField();
        const { fieldSchema: tableColumnSchema } = useColumnSchema();
        const schema = useFieldSchema();
        const fieldSchema = tableColumnSchema || schema;
        const { dn, refresh } = useDesignable();
        return {
            title: t('Allow multiple'),
            checked: void 0 === (fieldSchema['x-component-props'] || {}).multiple ? true : fieldSchema['x-component-props'].multiple,
            onChange (value) {
                const schema = {
                    ['x-uid']: fieldSchema['x-uid']
                };
                fieldSchema['x-component-props'] = fieldSchema['x-component-props'] || {};
                field.componentProps = field.componentProps || {};
                fieldSchema['x-component-props'].multiple = value;
                field.componentProps.multiple = value;
                schema['x-component-props'] = fieldSchema['x-component-props'];
                dn.emit('patch', {
                    schema
                });
                refresh();
            }
        };
    }
};
const quickCreate = {
    name: 'quickCreate',
    type: 'select',
    useComponentProps () {
        var _field_componentProps;
        const { t } = useTranslation();
        const field = useField();
        const fieldSchema = useFieldSchema();
        const { dn, insertAdjacent } = useDesignable();
        return {
            title: t('Quick create'),
            options: [
                {
                    label: t('None'),
                    value: 'none'
                },
                {
                    label: t('Dropdown'),
                    value: 'quickAdd'
                },
                {
                    label: t('Pop-up'),
                    value: 'modalAdd'
                }
            ],
            value: (null == (_field_componentProps = field.componentProps) ? void 0 : _field_componentProps.addMode) || 'none',
            onChange (mode) {
                if ('modalAdd' === mode) {
                    const hasAddNew = fieldSchema.reduceProperties((buf, schema)=>{
                        if ('Action' === schema['x-component']) return schema;
                        return buf;
                    }, null);
                    if (!hasAddNew) {
                        const addNewActionschema = {
                            'x-action': 'create',
                            'x-acl-action': 'create',
                            title: "{{t('Add new')}}",
                            'x-toolbar': 'ActionSchemaToolbar',
                            'x-settings': 'actionSettings:addNew',
                            'x-component': 'Action',
                            'x-decorator': 'ACLActionProvider',
                            'x-component-props': {
                                openMode: 'drawer',
                                type: 'default',
                                component: 'CreateRecordAction'
                            }
                        };
                        insertAdjacent('afterBegin', addNewActionschema);
                    }
                }
                const schema = {
                    ['x-uid']: fieldSchema['x-uid']
                };
                fieldSchema['x-component-props'] = fieldSchema['x-component-props'] || {};
                fieldSchema['x-component-props']['addMode'] = mode;
                schema['x-component-props'] = fieldSchema['x-component-props'];
                field.componentProps = field.componentProps || {};
                field.componentProps.addMode = mode;
                dn.emit('patch', {
                    schema
                });
                dn.refresh();
            }
        };
    }
};
const setDefaultSortingRules = {
    name: 'setDefaultSortingRules',
    Component: SchemaSettingsSortingRule
};
const setTheDataScope = {
    name: 'setTheDataScope',
    Component: SchemaSettingsDataScope,
    useComponentProps () {
        var _fieldSchema_xcomponentprops_service_params, _fieldSchema_xcomponentprops_service, _fieldSchema_xcomponentprops;
        const { getCollectionJoinField, getAllCollectionsInheritChain } = useCollectionManager_deprecated();
        const { getField } = useCollection_deprecated();
        const { form } = useFormBlockContext();
        const record = useRecord();
        useField();
        const { fieldSchema: tableColumnSchema, collectionField: tableColumnField } = useColumnSchema();
        const schema = useFieldSchema();
        const fieldSchema = tableColumnSchema || schema;
        const collectionField = tableColumnField || getField(fieldSchema['name']) || getCollectionJoinField(fieldSchema['x-collection-field']);
        const variables = useVariables();
        const localVariables = useLocalVariables();
        const { dn } = useDesignable();
        return {
            collectionName: null == collectionField ? void 0 : collectionField.target,
            defaultFilter: (null == fieldSchema ? void 0 : null == (_fieldSchema_xcomponentprops = fieldSchema['x-component-props']) ? void 0 : null == (_fieldSchema_xcomponentprops_service = _fieldSchema_xcomponentprops.service) ? void 0 : null == (_fieldSchema_xcomponentprops_service_params = _fieldSchema_xcomponentprops_service.params) ? void 0 : _fieldSchema_xcomponentprops_service_params.filter) || {},
            form,
            dynamicComponent: (props)=>/*#__PURE__*/ jsx(VariableInput, {
                    ...props,
                    form: form,
                    collectionField: props.collectionField,
                    record: record,
                    shouldChange: getShouldChange({
                        collectionField: props.collectionField,
                        variables,
                        localVariables,
                        getAllCollectionsInheritChain
                    })
                }),
            onSubmit: (param)=>{
                let { filter } = param;
                filter = removeNullCondition(filter);
                lodash.set(fieldSchema['x-component-props'], 'service.params.filter', filter);
                dn.emit('patch', {
                    schema: {
                        ['x-uid']: fieldSchema['x-uid'],
                        'x-component-props': fieldSchema['x-component-props']
                    }
                });
            }
        };
    }
};
const fieldComponent = {
    name: 'fieldComponent',
    type: 'select',
    useComponentProps () {
        var _collectionInterface_componentOptions_filter, _collectionInterface_componentOptions;
        const { t } = useTranslation();
        const field = useField();
        const collectionFieldCurrent = useCollectionField();
        const { fieldSchema: tableColumnSchema, collectionField } = useColumnSchema();
        const schema = useFieldSchema();
        const fieldSchema = tableColumnSchema || schema;
        const fieldModeOptions = useFieldModeOptions({
            fieldSchema: tableColumnSchema,
            collectionField
        });
        const isAddNewForm = useIsAddNewForm();
        const fieldMode = useFieldComponentName();
        const { dn } = useDesignable();
        const isMuiltipleSelect = [
            'select',
            'multipleSelect'
        ].includes(null == collectionFieldCurrent ? void 0 : collectionFieldCurrent.interface);
        const optionsMuiltipleSelect = [
            {
                label: t('Select'),
                value: 'Select'
            },
            {
                label: t('Radio group'),
                value: 'Radio group'
            }
        ];
        if ((null == collectionFieldCurrent ? void 0 : collectionFieldCurrent.interface) === 'multipleSelect') {
            const index = optionsMuiltipleSelect.findIndex((item)=>'Radio group' === item.value);
            optionsMuiltipleSelect.splice(index, 1);
        }
        const dm = useDataSourceManager();
        const collectionInterface = dm.collectionFieldInterfaceManager.getFieldInterface(null == collectionFieldCurrent ? void 0 : collectionFieldCurrent.interface);
        const compile = useCompile();
        if (fieldSchema['x-component-props']['multiple']) {
            const index = fieldModeOptions.findIndex((item)=>'Radio group' === item.value);
            fieldModeOptions.splice(index, 1);
        }
        const componentOptions = isMuiltipleSelect ? optionsMuiltipleSelect : fieldModeOptions;
        null == collectionInterface || null == (_collectionInterface_componentOptions = collectionInterface.componentOptions) || null == (_collectionInterface_componentOptions_filter = _collectionInterface_componentOptions.filter((item)=>!item.useVisible || item.useVisible())) || _collectionInterface_componentOptions_filter.forEach((item)=>{
            if (!(null == componentOptions ? void 0 : componentOptions.find((modeItem)=>modeItem.value === item.value))) null == componentOptions || componentOptions.push({
                label: compile(item.label),
                value: item.value
            });
        });
        return {
            title: t('Field component'),
            options: componentOptions,
            value: fieldMode,
            onChange (mode) {
                const schema = {
                    ['x-uid']: fieldSchema['x-uid']
                };
                fieldSchema['x-component-props'] = fieldSchema['x-component-props'] || {};
                fieldSchema['x-component-props']['mode'] = mode;
                schema['x-component-props'] = fieldSchema['x-component-props'];
                field.componentProps = field.componentProps || {};
                field.componentProps.mode = mode;
                if (isSubMode(fieldSchema) && isAddNewForm) {
                    var _field_setInitialValue, _field_setValue;
                    schema.default = null;
                    fieldSchema.default = null;
                    null == field || null == (_field_setInitialValue = field.setInitialValue) || _field_setInitialValue.call(field, null);
                    null == field || null == (_field_setValue = field.setValue) || _field_setValue.call(field, null);
                }
                dn.emit('patch', {
                    schema
                });
                dn.refresh();
            }
        };
    }
};
const CustomTitle = {
    name: 'customTitle',
    type: 'modal',
    useComponentProps () {
        var _fieldSchema_xcomponentprops_fieldNames, _fieldSchema_xcomponentprops;
        const schema = useFieldSchema();
        const { fieldSchema: tableColumnSchema } = useColumnSchema();
        const fieldSchema = tableColumnSchema || schema;
        const { t } = useTranslation();
        const { dn } = useDesignable();
        const options = useFormulaTitleOptions();
        const def = null == (_fieldSchema_xcomponentprops = fieldSchema['x-component-props']) ? void 0 : null == (_fieldSchema_xcomponentprops_fieldNames = _fieldSchema_xcomponentprops.fieldNames) ? void 0 : _fieldSchema_xcomponentprops_fieldNames.formula;
        const field = useField();
        return {
            title: t('Custom option label'),
            schema: {
                type: 'object',
                title: t('Custom option label'),
                properties: {
                    formula: {
                        required: true,
                        'x-decorator': 'FormItem',
                        'x-component': 'Variable.TextArea',
                        'x-component-props': {
                            scope: options
                        },
                        default: def
                    }
                }
            },
            onSubmit: (param)=>{
                let { formula } = param;
                if (formula) {
                    var _fieldSchema_xcomponentprops, _field_componentProps;
                    const componentProps = {
                        ...fieldSchema['x-component-props'],
                        fieldNames: {
                            ...null == (_fieldSchema_xcomponentprops = fieldSchema['x-component-props']) ? void 0 : _fieldSchema_xcomponentprops['fieldNames'],
                            formula
                        }
                    };
                    field.componentProps = {
                        ...field.componentProps,
                        fieldNames: {
                            ...null == (_field_componentProps = field.componentProps) ? void 0 : _field_componentProps.fieldNames,
                            formula
                        }
                    };
                    fieldSchema['x-component-props'] = componentProps;
                    dn.emit('patch', {
                        schema: {
                            'x-uid': fieldSchema['x-uid'],
                            'x-component-props': componentProps
                        }
                    });
                }
                dn.refresh();
            }
        };
    }
};
const selectComponentFieldSettings = new SchemaSettings({
    name: 'fieldSettings:component:Select',
    items: [
        {
            ...fieldComponent
        },
        {
            ...setTheDataScope,
            useVisible () {
                const isSelectFieldMode = useIsSelectFieldMode();
                const isFieldReadPretty = useIsFieldReadPretty();
                return isSelectFieldMode && !isFieldReadPretty;
            }
        },
        {
            ...setDefaultSortingRules,
            useComponentProps () {
                const { fieldSchema } = useColumnSchema();
                return {
                    fieldSchema
                };
            },
            useVisible () {
                const isSelectFieldMode = useIsSelectFieldMode();
                const isFieldReadPretty = useIsFieldReadPretty();
                return isSelectFieldMode && !isFieldReadPretty;
            }
        },
        {
            ...quickCreate,
            useVisible () {
                const isAssociationField = useIsAssociationField();
                const readPretty = useIsFieldReadPretty();
                const { fieldSchema } = useColumnSchema();
                return isAssociationField && !fieldSchema && !readPretty;
            }
        },
        {
            ...allowMultiple,
            useVisible () {
                const isAssociationField = useIsAssociationField();
                const IsShowMultipleSwitch = useIsShowMultipleSwitch();
                return isAssociationField && IsShowMultipleSwitch();
            }
        },
        {
            ...titleField,
            useVisible: useIsAssociationField
        },
        {
            ...enableLink,
            useVisible () {
                const readPretty = useIsFieldReadPretty();
                return useIsAssociationField() && readPretty;
            }
        }
    ]
});
export { CustomTitle, allowMultiple, enableLink, fieldComponent, quickCreate, selectComponentFieldSettings, setDefaultSortingRules, setTheDataScope, titleField };
