import { jsx } from "react/jsx-runtime";
import "react";
import { ArrayItems } from "@tachybase/components";
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, useSortFields } from "../../../../collection-manager/index.mjs";
import { useFieldComponentName } from "../../../../common/useFieldComponentName.mjs";
import { useCollectionField } from "../../../../data-source/index.mjs";
import { useRecord } from "../../../../record-provider/index.mjs";
import { removeNullCondition, useDesignable, useFieldModeOptions, useIsAddNewForm } from "../../../../schema-component/index.mjs";
import { isSubMode } from "../../../../schema-component/antd/association-field/util.mjs";
import { useIsAssociationField, useIsFieldReadPretty, useTitleFieldOptions } from "../../../../schema-component/antd/form-item/FormItem.Settings.mjs";
import { useColumnSchema } from "../../../../schema-component/antd/table-v2/Table.Column.Decorator.mjs";
import { SchemaSettingsModalItem, SchemaSettingsSwitchItem, VariableInput, getShouldChange } from "../../../../schema-settings/index.mjs";
import { SchemaSettingsDataScope } from "../../../../schema-settings/SchemaSettingsDataScope.mjs";
import { useLocalVariables, useVariables } from "../../../../variables/index.mjs";
const SchemaSettingsSortingRule = function(props) {
    var _fieldSchema_xcomponentprops_service_params, _fieldSchema_xcomponentprops_service, _fieldSchema_xcomponentprops;
    const field = useField();
    const { dn } = useDesignable();
    const { t } = useTranslation();
    const currentSchema = useFieldSchema();
    const { getField } = useCollection_deprecated();
    const { getCollectionJoinField } = useCollectionManager_deprecated();
    var _props_fieldSchema;
    const fieldSchema = null != (_props_fieldSchema = null == props ? void 0 : props.fieldSchema) ? _props_fieldSchema : currentSchema;
    const collectionField = getField(fieldSchema['name']) || getCollectionJoinField(fieldSchema['x-collection-field']);
    const sortFields = useSortFields(null == collectionField ? void 0 : collectionField.target);
    const defaultSort = (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.sort) || [];
    const sort = null == defaultSort ? void 0 : defaultSort.map((item)=>(null == item ? void 0 : item.startsWith('-')) ? {
            field: item.substring(1),
            direction: 'desc'
        } : {
            field: item,
            direction: 'asc'
        });
    return /*#__PURE__*/ jsx(SchemaSettingsModalItem, {
        title: t('Set default sorting rules'),
        components: {
            ArrayItems: ArrayItems
        },
        schema: {
            type: 'object',
            title: t('Set default sorting rules'),
            properties: {
                sort: {
                    type: 'array',
                    default: sort,
                    'x-component': 'ArrayItems',
                    'x-decorator': 'FormItem',
                    items: {
                        type: 'object',
                        properties: {
                            space: {
                                type: 'void',
                                'x-component': 'Space',
                                properties: {
                                    sort: {
                                        type: 'void',
                                        'x-decorator': 'FormItem',
                                        'x-component': 'ArrayItems.SortHandle'
                                    },
                                    field: {
                                        type: 'string',
                                        enum: sortFields,
                                        required: true,
                                        'x-decorator': 'FormItem',
                                        'x-component': 'Select',
                                        'x-component-props': {
                                            style: {
                                                width: 260
                                            },
                                            optionLabelProp: 'fullLabel'
                                        }
                                    },
                                    direction: {
                                        type: 'string',
                                        'x-decorator': 'FormItem',
                                        'x-component': 'Radio.Group',
                                        'x-component-props': {
                                            optionType: 'button'
                                        },
                                        enum: [
                                            {
                                                label: t('ASC'),
                                                value: 'asc'
                                            },
                                            {
                                                label: t('DESC'),
                                                value: 'desc'
                                            }
                                        ]
                                    },
                                    remove: {
                                        type: 'void',
                                        'x-decorator': 'FormItem',
                                        'x-component': 'ArrayItems.Remove'
                                    }
                                }
                            }
                        }
                    },
                    properties: {
                        add: {
                            type: 'void',
                            title: t('Add sort field'),
                            'x-component': 'ArrayItems.Addition'
                        }
                    }
                }
            }
        },
        onSubmit: (param)=>{
            let { sort } = param;
            var _props_onSubmitCallBack, _fieldSchema_xcomponentprops, _field_path, _field_path1;
            const sortArr = sort.map((item)=>'desc' === item.direction ? "-".concat(item.field) : item.field);
            lodash.set(field.componentProps, 'service.params.sort', sortArr);
            null == props || null == (_props_onSubmitCallBack = props.onSubmitCallBack) || _props_onSubmitCallBack.call(props, sortArr);
            const service = null == (_fieldSchema_xcomponentprops = fieldSchema['x-component-props']) ? void 0 : _fieldSchema_xcomponentprops.service;
            if (service) {
                var _field_componentProps_service_params, _field_componentProps;
                service.params['sort'] = null == (_field_componentProps = field.componentProps) ? void 0 : null == (_field_componentProps_service_params = _field_componentProps.service.params) ? void 0 : _field_componentProps_service_params.sort;
            } else {
                var _field_componentProps_service_params1, _field_componentProps1;
                fieldSchema['x-component-props']['service'] = {
                    params: {
                        sort: null == (_field_componentProps1 = field.componentProps) ? void 0 : null == (_field_componentProps_service_params1 = _field_componentProps1.service.params) ? void 0 : _field_componentProps_service_params1.sort
                    }
                };
            }
            const componentProps = fieldSchema['x-component-props'];
            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 = componentProps;
            });
            dn.emit('patch', {
                schema: {
                    ['x-uid']: fieldSchema['x-uid'],
                    'x-component-props': componentProps
                }
            });
        }
    });
};
const setIsChangOnSelect = function(props) {
    var _fieldSchema_xcomponentprops;
    const { dn } = useDesignable();
    const { t } = useTranslation();
    const { fieldSchema: tableColumnSchema, collectionField } = useColumnSchema();
    useField();
    const schema = useFieldSchema();
    const fieldSchema = tableColumnSchema || schema;
    return /*#__PURE__*/ jsx(SchemaSettingsSwitchItem, {
        title: t('Chang on Parent'),
        checked: !!(null == fieldSchema ? void 0 : null == (_fieldSchema_xcomponentprops = fieldSchema['x-component-props']) ? void 0 : _fieldSchema_xcomponentprops.changOnSelect),
        onChange: (value)=>{
            fieldSchema['x-component-props']['changOnSelect'] = value;
            dn.emit('patch', {
                schema: {
                    ['x-uid']: fieldSchema['x-uid'],
                    'x-component-props': {
                        ...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 = newFieldNames;
                });
                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();
        const field = 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;
                var _fieldSchema_xcomponentprops, _field_path, _field_path1;
                filter = removeNullCondition(filter);
                lodash.set(field.componentProps, 'service.params.filter', filter);
                const service = null == (_fieldSchema_xcomponentprops = fieldSchema['x-component-props']) ? void 0 : _fieldSchema_xcomponentprops.service;
                if (service) service.params['filter'] = filter;
                else fieldSchema['x-component-props']['service'] = {
                    params: {
                        filter: {
                            ...filter
                        }
                    }
                };
                const componentProps = fieldSchema['x-component-props'];
                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 = componentProps;
                });
                dn.emit('patch', {
                    schema: {
                        ['x-uid']: fieldSchema['x-uid'],
                        'x-component-props': componentProps
                    }
                });
                dn.refresh();
            }
        };
    }
};
const fieldComponent = {
    name: 'fieldComponent',
    type: 'select',
    useComponentProps () {
        const { t } = useTranslation();
        const field = useField();
        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();
        return {
            title: t('Field component'),
            options: fieldModeOptions,
            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 ChangOnSelect = {
    name: 'changOnSelect',
    Component: setIsChangOnSelect
};
const cascaderComponentFieldSettings = new SchemaSettings({
    name: 'fieldSettings:component:Cascader',
    items: [
        {
            ...fieldComponent,
            useVisible: useIsAssociationField
        },
        {
            ...setTheDataScope,
            useVisible () {
                const isFieldReadPretty = useIsFieldReadPretty();
                return !isFieldReadPretty;
            }
        },
        {
            ...setDefaultSortingRules,
            useComponentProps () {
                const { fieldSchema } = useColumnSchema();
                return {
                    fieldSchema
                };
            },
            useVisible () {
                const isFieldReadPretty = useIsFieldReadPretty();
                return !isFieldReadPretty;
            }
        },
        {
            ...titleField,
            useVisible: useIsAssociationField
        },
        {
            ...ChangOnSelect,
            useVisible: useIsAssociationField
        }
    ]
});
export { SchemaSettingsSortingRule, cascaderComponentFieldSettings, setIsChangOnSelect };
