import { jsx } from "react/jsx-runtime";
import { useMemo } from "react";
import { connect, mapProps, observable, observer } from "@tachybase/schema";
import { Tree } from "antd";
import lodash from "lodash";
import { useTranslation } from "react-i18next";
import { withDynamicSchemaProps } from "../../application/hoc/withDynamicSchemaProps.mjs";
import { useCollectionManager_deprecated } from "../../collection-manager/index.mjs";
import { mergeFilter } from "../../filter-provider/utils.mjs";
import { SchemaComponent, SchemaComponentContext, removeNullCondition, useProps } from "../../schema-component/index.mjs";
import { VariableInput } from "../VariableInput/index.mjs";
import { AsDefaultTemplate } from "./components/AsDefaultTemplate.mjs";
import { ArrayCollapse } from "./components/DataTemplateTitle.mjs";
import { getSelectedIdFilter } from "./components/Designer.mjs";
import { useCollectionState } from "./hooks/useCollectionState.mjs";
import { useSyncFromForm } from "./utils.mjs";
const FormDataTemplates_Tree = connect(Tree, mapProps({
    value: 'checkedKeys',
    dataSource: 'treeData'
}));
FormDataTemplates_Tree.displayName = 'Tree';
const compatibleDataId = (data, config)=>null == data ? void 0 : data.map((v)=>{
        const { dataId, ...others } = v;
        const obj = {
            ...others
        };
        if (dataId) {
            var _config_v_collection;
            obj.dataScope = {
                $and: [
                    {
                        id: {
                            $eq: dataId
                        }
                    }
                ]
            };
            obj.titleField = (null == obj ? void 0 : obj.titleField) || (null == config ? void 0 : null == (_config_v_collection = config[v.collection]) ? void 0 : _config_v_collection['titleField']) || 'id';
        }
        return obj;
    });
const FormDataTemplates = withDynamicSchemaProps(observer((props)=>{
    const { formSchema, designerCtx, defaultValues, collectionName } = useProps(props);
    const { collectionList, getEnableFieldTree, getOnLoadData, getOnCheck, getScopeDataSource, useTitleFieldDataSource } = useCollectionState(collectionName);
    const { getCollection, getCollectionField } = useCollectionManager_deprecated();
    const { t } = useTranslation();
    const activeData = useMemo(()=>observable({
            ...defaultValues,
            items: compatibleDataId((null == defaultValues ? void 0 : defaultValues.items) || [], null == defaultValues ? void 0 : defaultValues.config)
        }), []);
    const getTargetField = (collectionName)=>{
        var _activeData_config_collectionName;
        const collection = getCollection(collectionName);
        return getCollectionField("".concat(collectionName, ".").concat((null == activeData ? void 0 : null == (_activeData_config_collectionName = activeData.config[collectionName]) ? void 0 : _activeData_config_collectionName.titleField) || (null == collection ? void 0 : collection.titleField) || 'id'));
    };
    const getFieldNames = (collectionName)=>{
        var _activeData_config_collectionName, _activeData_config;
        const collection = getCollection(collectionName);
        return {
            label: getLabel((null == (_activeData_config = activeData.config) ? void 0 : null == (_activeData_config_collectionName = _activeData_config[collectionName]) ? void 0 : _activeData_config_collectionName.titleField) || (null == collection ? void 0 : collection.titleField) || 'id'),
            value: 'id'
        };
    };
    const getFilter = (collectionName, value)=>{
        var _activeData_config_collectionName, _activeData_config;
        const filter = null == (_activeData_config = activeData.config) ? void 0 : null == (_activeData_config_collectionName = _activeData_config[collectionName]) ? void 0 : _activeData_config_collectionName.filter;
        return lodash.isEmpty(filter) ? {} : removeNullCondition(mergeFilter([
            filter,
            getSelectedIdFilter(value)
        ], '$or'));
    };
    const components = useMemo(()=>({
            ArrayCollapse: ArrayCollapse
        }), []);
    const scope = useMemo(()=>({
            getEnableFieldTree,
            getTargetField,
            getFieldNames,
            getFilter,
            getResource,
            getOnLoadData,
            getOnCheck,
            collectionName,
            getScopeDataSource,
            useTitleFieldDataSource
        }), []);
    const schema = useMemo(()=>({
            type: 'object',
            properties: {
                items: {
                    type: 'array',
                    default: null == activeData ? void 0 : activeData.items,
                    'x-component': 'ArrayCollapse',
                    'x-decorator': 'FormItem',
                    'x-component-props': {
                        accordion: true
                    },
                    items: {
                        type: 'object',
                        'x-component': 'ArrayCollapse.CollapsePanel',
                        'x-component-props': {
                            extra: [
                                /*#__PURE__*/ jsx(AsDefaultTemplate, {}, "0")
                            ]
                        },
                        properties: {
                            layout: {
                                type: 'void',
                                'x-component': 'FormLayout',
                                'x-component-props': {
                                    layout: 'vertical'
                                },
                                properties: {
                                    collection: {
                                        type: 'string',
                                        title: '{{ t("Collection") }}',
                                        required: true,
                                        description: t('If collection inherits, choose inherited collections as templates'),
                                        default: '{{ collectionName }}',
                                        'x-display': collectionList.length > 1 ? 'visible' : 'hidden',
                                        'x-decorator': 'FormItem',
                                        'x-component': 'Select',
                                        'x-component-props': {
                                            options: collectionList
                                        }
                                    },
                                    dataScope: {
                                        type: 'object',
                                        title: '{{ t("Assign  data scope for the template") }}',
                                        'x-decorator': 'FormItem',
                                        'x-component': 'Filter',
                                        'x-component-props': {
                                            dynamicComponent: VariableInput
                                        },
                                        'x-decorator-props': {
                                            style: {
                                                marginBottom: '0px'
                                            }
                                        },
                                        required: true,
                                        'x-reactions': [
                                            {
                                                dependencies: [
                                                    '.collection'
                                                ],
                                                fulfill: {
                                                    state: {
                                                        disabled: '{{ !$deps[0] }}'
                                                    },
                                                    schema: {
                                                        enum: '{{ getScopeDataSource($deps[0]) }}'
                                                    }
                                                }
                                            }
                                        ]
                                    },
                                    titleField: {
                                        type: 'string',
                                        'x-decorator': 'FormItem',
                                        title: '{{ t("Title field") }}',
                                        'x-component': 'Select',
                                        required: true,
                                        'x-reactions': '{{useTitleFieldDataSource}}'
                                    },
                                    syncFromForm: {
                                        type: 'void',
                                        title: '{{ t("Sync from form fields") }}',
                                        'x-component': 'Action.Link',
                                        'x-component-props': {
                                            type: 'primary',
                                            style: {
                                                float: 'right',
                                                position: 'relative',
                                                zIndex: 1200
                                            },
                                            useAction: ()=>useSyncFromForm(formSchema)
                                        }
                                    },
                                    fields: {
                                        type: 'array',
                                        title: '{{ t("Data fields") }}',
                                        required: true,
                                        description: t('Only the selected fields will be used as the initialization data for the form'),
                                        'x-decorator': 'FormItem',
                                        'x-component': FormDataTemplates_Tree,
                                        'x-component-props': {
                                            treeData: [],
                                            checkable: true,
                                            checkStrictly: true,
                                            selectable: false,
                                            loadData: '{{ getOnLoadData($self) }}',
                                            onCheck: '{{ getOnCheck($self) }}',
                                            rootStyle: {
                                                padding: '8px 0',
                                                border: '1px solid #d9d9d9',
                                                borderRadius: '2px',
                                                maxHeight: '30vh',
                                                overflow: 'auto',
                                                margin: '2px 0'
                                            }
                                        },
                                        'x-reactions': [
                                            {
                                                dependencies: [
                                                    '.collection'
                                                ],
                                                fulfill: {
                                                    state: {
                                                        disabled: '{{ !$deps[0] }}',
                                                        componentProps: {
                                                            treeData: '{{ getEnableFieldTree($deps[0], $self) }}'
                                                        }
                                                    }
                                                }
                                            }
                                        ]
                                    }
                                }
                            },
                            remove: {
                                type: 'void',
                                'x-component': 'ArrayCollapse.Remove'
                            },
                            moveUp: {
                                type: 'void',
                                'x-component': 'ArrayCollapse.MoveUp'
                            },
                            moveDown: {
                                type: 'void',
                                'x-component': 'ArrayCollapse.MoveDown'
                            }
                        }
                    },
                    properties: {
                        add: {
                            type: 'void',
                            title: '{{ t("Add template") }}',
                            'x-component': 'ArrayCollapse.Addition'
                        }
                    }
                },
                display: {
                    type: 'boolean',
                    'x-content': '{{ t("Display data template selector") }}',
                    default: (null == activeData ? void 0 : activeData.display) !== false,
                    'x-decorator': 'FormItem',
                    'x-component': 'Checkbox'
                }
            }
        }), []);
    return /*#__PURE__*/ jsx(SchemaComponentContext.Provider, {
        value: {
            ...designerCtx,
            designable: true
        },
        children: /*#__PURE__*/ jsx(SchemaComponent, {
            components: components,
            scope: scope,
            schema: schema
        })
    });
}, {
    displayName: 'FormDataTemplates'
}), {
    displayName: 'FormDataTemplates'
});
function getLabel(titleField) {
    return titleField || 'label';
}
function getResource(resource, field) {
    if (resource !== field.componentProps.service.resource) field.value = void 0;
    return resource;
}
export { FormDataTemplates, compatibleDataId, getLabel };
