import { jsx, jsxs } from "react/jsx-runtime";
import "react";
import { observer, useField, useFieldSchema } from "@tachybase/schema";
import { error } from "@tego/client";
import { Select } from "antd";
import lodash from "lodash";
import { useTranslation } from "react-i18next";
import { GeneralSchemaDesigner, SchemaSettingsItem } from "../../index.mjs";
import { useFormBlockContext } from "../../../block-provider/index.mjs";
import { useCollectionManager_deprecated } from "../../../collection-manager/index.mjs";
import { mergeFilter } from "../../../filter-provider/utils.mjs";
import { removeNullCondition, useCompile, useDesignable } from "../../../schema-component/index.mjs";
import { SchemaSettingsDataScope } from "../../SchemaSettingsDataScope.mjs";
const Designer = observer(()=>{
    const { getCollectionFields, getCollectionField, getCollection, isTitleField } = useCollectionManager_deprecated();
    const field = useField();
    const fieldSchema = useFieldSchema();
    const { t } = useTranslation();
    const { dn } = useDesignable();
    const compile = useCompile();
    const { formSchema, data } = fieldSchema['x-designer-props'];
    const { form } = useFormBlockContext();
    const collectionName = field.componentProps.service.resource;
    const collection = getCollection(collectionName);
    const collectionFields = getCollectionFields(collectionName);
    if (!data) {
        error('data is required');
        return null;
    }
    const getFilter = ()=>{
        var _data_config_collectionName, _data_config;
        return (null == (_data_config = data.config) ? void 0 : null == (_data_config_collectionName = _data_config[collectionName]) ? void 0 : _data_config_collectionName.filter) || {};
    };
    const setFilter = (filter)=>{
        try {
            lodash.set(data, "config.".concat(collectionName, ".filter"), removeNullCondition(filter));
        } catch (err) {
            error(err);
        }
    };
    const getTitleFIeld = ()=>{
        var _data_config_collectionName, _data_config;
        return (null == (_data_config = data.config) ? void 0 : null == (_data_config_collectionName = _data_config[collectionName]) ? void 0 : _data_config_collectionName.titleField) || (null == collection ? void 0 : collection.titleField) || 'id';
    };
    const setTitleField = (titleField)=>{
        try {
            lodash.set(data, "config.".concat(collectionName, ".titleField"), titleField);
        } catch (err) {
            error(err);
        }
    };
    const options = collectionFields.filter((field)=>isTitleField(field)).map((field)=>{
        var _field_uiSchema;
        return {
            value: null == field ? void 0 : field.name,
            label: compile(null == field ? void 0 : null == (_field_uiSchema = field.uiSchema) ? void 0 : _field_uiSchema.title) || (null == field ? void 0 : field.name)
        };
    });
    return /*#__PURE__*/ jsxs(GeneralSchemaDesigner, {
        draggable: false,
        children: [
            /*#__PURE__*/ jsx(SchemaSettingsDataScope, {
                collectionName: collectionName,
                defaultFilter: getFilter(),
                form: form,
                onSubmit: (param)=>{
                    let { filter } = param;
                    setFilter(filter);
                    try {
                        field.query('fieldReaction.items.*.layout.dataId').forEach((item)=>{
                            if (item.componentProps.service.resource !== collectionName) return;
                            item.componentProps.service.params = {
                                filter: lodash.isEmpty(filter) ? {} : removeNullCondition(mergeFilter([
                                    filter,
                                    getSelectedIdFilter(field.value)
                                ], '$or'))
                            };
                        });
                    } catch (err) {
                        error(err);
                    }
                    formSchema['x-data-templates'] = data;
                    dn.emit('patch', {
                        schema: {
                            ['x-uid']: formSchema['x-uid'],
                            ['x-data-templates']: data
                        }
                    });
                    dn.refresh();
                }
            }),
            /*#__PURE__*/ jsx(SelectItem, {
                title: t('Title field'),
                options: options,
                value: getTitleFIeld(),
                onChange: (label)=>{
                    setTitleField(label);
                    try {
                        field.query('fieldReaction.items.*.layout.dataId').forEach((item)=>{
                            if (item.componentProps.service.resource !== collectionName) return;
                            item.componentProps.fieldNames.label = label;
                            item.componentProps.targetField = getCollectionField("".concat(collectionName, ".").concat(label || (null == collection ? void 0 : collection.titleField) || 'id'));
                        });
                    } catch (err) {
                        console.error(err);
                    }
                    formSchema['x-data-templates'] = data;
                    const schema = {
                        ['x-uid']: formSchema['x-uid'],
                        ['x-data-templates']: data
                    };
                    dn.emit('patch', {
                        schema
                    });
                    dn.refresh();
                }
            }, "title-field")
        ]
    });
}, {
    displayName: 'Designer'
});
function getSelectedIdFilter(selectedId) {
    return selectedId ? {
        id: {
            $eq: selectedId
        }
    } : null;
}
function SelectItem(props) {
    const { title, options, value, onChange, ...others } = props;
    return /*#__PURE__*/ jsx(SchemaSettingsItem, {
        title: title,
        ...others,
        children: /*#__PURE__*/ jsxs("div", {
            style: {
                alignItems: 'center',
                display: 'flex',
                justifyContent: 'space-between'
            },
            children: [
                title,
                /*#__PURE__*/ jsx(Select, {
                    popupMatchSelectWidth: false,
                    bordered: false,
                    value: value,
                    onChange: onChange,
                    options: options,
                    style: {
                        textAlign: 'right',
                        minWidth: 100
                    },
                    ...others
                })
            ]
        })
    });
}
export { Designer, getSelectedIdFilter };
