import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import react, { createContext, useCallback, useContext, useEffect, useMemo, useState, useTransition } from "react";
import { SchemaOptionsContext, createForm, uid as schema_uid, useField, useFieldSchema, useForm } from "@tachybase/schema";
import { ArrayCollapse, ArrayItems, FormItem, FormLayout, Input, error } from "@tego/client";
import { Alert, App, Button, Cascader, ConfigProvider, Dropdown, Empty, Modal, Space, Switch } from "antd";
import { createStyles } from "antd-style";
import lodash, { cloneDeep, get, set } from "lodash";
import { createPortal } from "react-dom";
import { useTranslation } from "react-i18next";
import { Router } from "react-router-dom";
import { APIClientProvider, ActionContextProvider, ApplicationContext, AssociationOrCollectionProvider, Cascader as external_index_mjs_Cascader, Checkbox, CollectionRecordProvider, DataSourceApplicationProvider, DatePicker, FormDialog, FormProvider, Icon, Input as external_index_mjs_Input, Radio, RemoteSchemaComponent, SchemaComponent, SchemaComponentContext, SchemaComponentOptions, Select, createDesignable, findFormBlock, useAPIClient, useApp, useBlockRequestContext, useCollectionManager_deprecated, useCollectionRecord, useCollection_deprecated, useCompile, useDataBlockProps, useDesignable, useFilterBlock, useGlobalTheme, useLinkageCollectionFilterOptions, useRecord, useSchemaSettingsItem, useSortFields } from "../index.mjs";
import { BlockRequestContext_deprecated, FormBlockContext, useFormBlockContext, useFormBlockType, useTableBlockContext } from "../block-provider/index.mjs";
import { FormActiveFieldsProvider, findFilterTargets, updateFilterTargets, useFormActiveFields } from "../block-provider/hooks/index.mjs";
import { SelectWithTitle } from "../common/SelectWithTitle.mjs";
import { useNiceDropdownMaxHeight } from "../common/useNiceDropdownHeight.mjs";
import { useDataSourceManager } from "../data-source/data-source/DataSourceManagerProvider.mjs";
import { useDataSourceKey } from "../data-source/data-source/DataSourceProvider.mjs";
import { getSupportFieldsByAssociation, getSupportFieldsByForeignKey, isSameCollection, useSupportedBlocks } from "../filter-provider/utils.mjs";
import { FlagProvider } from "../flag-provider/index.mjs";
import { useCollectMenuItem, useCollectMenuItems, useMenuItem } from "../hooks/useMenuItem.mjs";
import { DeclareVariable } from "../modules/variable/DeclareVariable.mjs";
import { useVariable } from "../modules/variable/useVariable.mjs";
import { SubFormProvider, useSubFormValue } from "../schema-component/antd/association-field/hooks.mjs";
import { getTargetKey } from "../schema-component/antd/association-filter/utilts.mjs";
import { useSchemaTemplateManager } from "../schema-templates/index.mjs";
import { useBlockTemplateContext } from "../schema-templates/BlockTemplate.mjs";
import { useLocalVariables, useVariables } from "../variables/index.mjs";
import { FormDataTemplates } from "./DataTemplates/index.mjs";
import { EnableChildCollections } from "./EnableChildCollections/index.mjs";
import { ChildDynamicComponent } from "./EnableChildCollections/DynamicComponent.mjs";
import { FormLinkageRules } from "./LinkageRules/index.mjs";
import { useLinkageCollectionFieldOptions } from "./LinkageRules/action-hooks.mjs";
function _tagged_template_literal(strings, raw) {
    if (!raw) raw = strings.slice(0);
    return Object.freeze(Object.defineProperties(strings, {
        raw: {
            value: Object.freeze(raw)
        }
    }));
}
function _templateObject() {
    const data = _tagged_template_literal([
        "\n      .ant-dropdown-menu-item-group-list {\n        max-height: 400px;\n        overflow-y: auto;\n      }\n    "
    ]);
    _templateObject = function() {
        return data;
    };
    return data;
}
function _templateObject1() {
    const data = _tagged_template_literal([
        "\n      // screen > 576px\n      @media (min-width: 576px) {\n        min-width: 520px;\n      }\n\n      // screen <= 576px\n      @media (max-width: 576px) {\n        min-width: 320px;\n      }\n    "
    ]);
    _templateObject1 = function() {
        return data;
    };
    return data;
}
const SchemaSettingsContext = /*#__PURE__*/ createContext(null);
SchemaSettingsContext.displayName = 'SchemaSettingsContext';
function useSchemaSettings() {
    return useContext(SchemaSettingsContext);
}
const useStyles = createStyles((param)=>{
    let { css } = param;
    return {
        menu: css(_templateObject()),
        modal: css(_templateObject1())
    };
});
const SchemaSettingsProvider = (props)=>{
    const { children, fieldSchema, ...others } = props;
    const { getTemplateBySchema } = useSchemaTemplateManager();
    const { name } = useCollection_deprecated();
    const template = getTemplateBySchema(fieldSchema);
    return /*#__PURE__*/ jsx(SchemaSettingsContext.Provider, {
        value: {
            collectionName: name,
            template,
            fieldSchema,
            ...others
        },
        children: children
    });
};
const SchemaSettingsDropdown = (props)=>{
    const { title, dn, ...others } = props;
    const { styles } = useStyles();
    const [visible, setVisible] = useState(false);
    const { Component, getMenuItems } = useMenuItem();
    const [, startTransition] = useTransition();
    const dropdownMaxHeight = useNiceDropdownMaxHeight([
        visible
    ]);
    const changeMenu = useCallback((nextOpen, info)=>{
        if ('trigger' === info.source || nextOpen) startTransition(()=>{
            setVisible(nextOpen);
        });
    }, []);
    const items = getMenuItems(()=>props.children);
    return /*#__PURE__*/ jsxs(SchemaSettingsProvider, {
        visible: visible,
        setVisible: setVisible,
        dn: dn,
        ...others,
        children: [
            /*#__PURE__*/ jsx(Component, {}),
            /*#__PURE__*/ jsx(Dropdown, {
                open: visible,
                onOpenChange: changeMenu,
                overlayClassName: styles.menu,
                menu: {
                    items,
                    style: {
                        maxHeight: dropdownMaxHeight,
                        overflowY: 'auto'
                    }
                },
                children: /*#__PURE__*/ jsx("div", {
                    "data-testid": props['data-testid'],
                    children: 'string' == typeof title ? /*#__PURE__*/ jsx("span", {
                        children: title
                    }) : title
                })
            })
        ]
    });
};
const SchemaSettingsTemplate = function(props) {
    const { componentName, collectionName, resourceName, needRender } = props;
    const { t } = useTranslation();
    const { getCollection } = useCollectionManager_deprecated();
    const { dn, setVisible, template, fieldSchema } = useSchemaSettings();
    const compile = useCompile();
    const api = useAPIClient();
    const { dn: tdn } = useBlockTemplateContext();
    const { saveAsTemplate, copyTemplateSchema } = useSchemaTemplateManager();
    const { theme } = useGlobalTheme();
    if (!collectionName && !needRender) return null;
    if (template) return /*#__PURE__*/ jsx(SchemaSettingsItem, {
        title: "Convert reference to duplicate",
        onClick: async ()=>{
            const schema = await copyTemplateSchema(template);
            const removed = tdn.removeWithoutEmit();
            tdn.insertAfterEnd(schema, {
                async onSuccess () {
                    await api.request({
                        url: "/uiSchemas:remove/".concat(removed['x-uid'])
                    });
                }
            });
        },
        children: t('Convert reference to duplicate')
    });
    return /*#__PURE__*/ jsx(SchemaSettingsItem, {
        title: "Save as template",
        onClick: async ()=>{
            setVisible(false);
            const collection = collectionName && getCollection(collectionName);
            const values = await FormDialog(t('Save as template'), ()=>/*#__PURE__*/ jsx(FormLayout, {
                    layout: 'vertical',
                    children: /*#__PURE__*/ jsx(SchemaComponent, {
                        components: {
                            Input: Input,
                            FormItem: FormItem
                        },
                        schema: {
                            type: 'object',
                            properties: {
                                name: {
                                    title: t('Template name'),
                                    required: true,
                                    default: collection ? "".concat(compile((null == collection ? void 0 : collection.title) || (null == collection ? void 0 : collection.name)), "_").concat(t(componentName)) : t(componentName),
                                    'x-decorator': 'FormItem',
                                    'x-component': 'Input'
                                }
                            }
                        }
                    })
                }), theme).open({});
            const sdn = createDesignable({
                t,
                api,
                refresh: dn.refresh.bind(dn),
                current: fieldSchema.parent
            });
            sdn.loadAPIClientEvents();
            const { key } = await saveAsTemplate({
                collectionName,
                resourceName,
                componentName,
                dataSourceKey: collection.dataSource,
                name: values.name,
                uid: fieldSchema['x-uid']
            });
            sdn.removeWithoutEmit(fieldSchema);
            sdn.insertBeforeEnd({
                type: 'void',
                'x-component': 'BlockTemplate',
                'x-component-props': {
                    templateId: key
                }
            });
        },
        children: t('Save as template')
    });
};
const findGridSchema = (fieldSchema)=>fieldSchema.reduceProperties((buf, s)=>{
        if ('FormV2' === s['x-component'] || 'Details' === s['x-component']) {
            const f = s.reduceProperties((buf, s)=>{
                if ('Grid' === s['x-component'] || 'BlockTemplate' === s['x-component']) return s;
                return buf;
            }, null);
            if (f) return f;
        }
        return buf;
    }, null);
const findBlockTemplateSchema = (fieldSchema)=>fieldSchema.reduceProperties((buf, s)=>{
        if ('FormV2' === s['x-component'] || 'Details' === s['x-component']) {
            const f = s.reduceProperties((buf, s)=>{
                if ('BlockTemplate' === s['x-component']) return s;
                return buf;
            }, null);
            if (f) return f;
        }
        return buf;
    }, null);
const SchemaSettingsFormItemTemplate = function(props) {
    const { insertAdjacentPosition = 'beforeEnd', componentName, collectionName, resourceName } = props;
    const { t } = useTranslation();
    const compile = useCompile();
    const { getCollection } = useCollectionManager_deprecated();
    const { dn, setVisible, template, fieldSchema } = useSchemaSettings();
    const api = useAPIClient();
    const { saveAsTemplate, copyTemplateSchema } = useSchemaTemplateManager();
    const { theme } = useGlobalTheme();
    if (!collectionName) return null;
    if (template) return /*#__PURE__*/ jsx(SchemaSettingsItem, {
        title: "Convert reference to duplicate",
        onClick: async ()=>{
            const schema = await copyTemplateSchema(template);
            const templateSchema = findBlockTemplateSchema(fieldSchema);
            const sdn = createDesignable({
                t,
                api,
                refresh: dn.refresh.bind(dn),
                current: templateSchema.parent
            });
            sdn.loadAPIClientEvents();
            sdn.removeWithoutEmit(templateSchema);
            sdn.insertAdjacent(insertAdjacentPosition, schema, {
                async onSuccess () {
                    await api.request({
                        url: "/uiSchemas:remove/".concat(templateSchema['x-uid'])
                    });
                }
            });
            fieldSchema['x-template-key'] = null;
            await api.request({
                url: "uiSchemas:patch",
                method: 'post',
                data: {
                    'x-uid': fieldSchema['x-uid'],
                    'x-template-key': null
                }
            });
            dn.refresh();
        },
        children: t('Convert reference to duplicate')
    });
    return /*#__PURE__*/ jsx(SchemaSettingsItem, {
        title: "Save as block template",
        onClick: async ()=>{
            setVisible(false);
            const collection = collectionName && getCollection(collectionName);
            const gridSchema = findGridSchema(fieldSchema);
            const values = await FormDialog(t('Save as template'), ()=>{
                const componentTitle = {
                    FormItem: t('Form'),
                    ReadPrettyFormItem: t('Details')
                };
                return /*#__PURE__*/ jsx(FormLayout, {
                    layout: 'vertical',
                    children: /*#__PURE__*/ jsx(SchemaComponent, {
                        components: {
                            Input: Input,
                            FormItem: FormItem
                        },
                        schema: {
                            type: 'object',
                            properties: {
                                name: {
                                    title: t('Template name'),
                                    required: true,
                                    default: collection ? "".concat(compile((null == collection ? void 0 : collection.title) || (null == collection ? void 0 : collection.name)), "_").concat(t(componentTitle[componentName] || componentName)) : t(componentTitle[componentName] || componentName),
                                    'x-decorator': 'FormItem',
                                    'x-component': 'Input'
                                }
                            }
                        }
                    })
                });
            }, theme).open({});
            const sdn = createDesignable({
                t,
                api,
                refresh: dn.refresh.bind(dn),
                current: gridSchema.parent
            });
            sdn.loadAPIClientEvents();
            const { key } = await saveAsTemplate({
                collectionName,
                resourceName,
                componentName,
                dataSourceKey: collection.dataSource,
                name: values.name,
                uid: gridSchema['x-uid']
            });
            sdn.removeWithoutEmit(gridSchema);
            sdn.insertAdjacent(insertAdjacentPosition, {
                type: 'void',
                'x-component': 'BlockTemplate',
                'x-component-props': {
                    templateId: key
                }
            });
            fieldSchema['x-template-key'] = key;
            await api.request({
                url: "uiSchemas:patch",
                method: 'post',
                data: {
                    'x-uid': fieldSchema['x-uid'],
                    'x-template-key': key
                }
            });
        },
        children: t('Save as block template')
    });
};
const SchemaSettingsItem = (props)=>{
    const { eventKey, title } = props;
    const { pushMenuItem } = useCollectMenuItems();
    const { collectMenuItem } = useCollectMenuItem();
    const { name } = useSchemaSettingsItem();
    const item = {
        key: title,
        ...lodash.omit(props, [
            'children',
            'name'
        ]),
        eventKey: eventKey,
        onClick: (info)=>{
            var _props_onClick;
            info.domEvent.preventDefault();
            info.domEvent.stopPropagation();
            null == props || null == (_props_onClick = props.onClick) || _props_onClick.call(props, info);
        },
        style: {
            minWidth: 120
        },
        label: props.children || props.title,
        title: props.title
    };
    null == pushMenuItem || pushMenuItem(item);
    null == collectMenuItem || collectMenuItem(item);
    return null;
};
const SchemaSettingsItemGroup = (props)=>{
    const { Component, getMenuItems } = useMenuItem();
    const { pushMenuItem } = useCollectMenuItems();
    const key = useMemo(()=>schema_uid(), []);
    const item = {
        key,
        type: 'group',
        title: props.title,
        label: props.title,
        children: getMenuItems(()=>props.children)
    };
    pushMenuItem(item);
    return /*#__PURE__*/ jsx(Component, {});
};
const SchemaSettingsSubMenu = function(props) {
    const { Component, getMenuItems } = useMenuItem();
    const { pushMenuItem } = useCollectMenuItems();
    const key = useMemo(()=>schema_uid(), []);
    const item = {
        key,
        label: props.title,
        title: props.title,
        children: getMenuItems(()=>props.children)
    };
    pushMenuItem(item);
    return /*#__PURE__*/ jsx(Component, {});
};
const SchemaSettingsDivider = function() {
    const { pushMenuItem } = useCollectMenuItems();
    const key = useMemo(()=>schema_uid(), []);
    const item = {
        key,
        type: 'divider'
    };
    pushMenuItem(item);
    return null;
};
const SchemaSettingsRemove = (props)=>{
    const { icon, confirm, removeParentsIfNoChildren, breakRemoveOn } = props;
    const { dn, template } = useSchemaSettings();
    const { t } = useTranslation();
    const field = useField();
    const fieldSchema = useFieldSchema();
    const ctx = useBlockTemplateContext();
    const form = useForm();
    const { modal } = App.useApp();
    const { removeActiveFieldName } = useFormActiveFields() || {};
    return /*#__PURE__*/ jsx(SchemaSettingsItem, {
        title: "Delete",
        eventKey: "remove",
        icon: icon ? /*#__PURE__*/ jsx(Icon, {
            style: {
                color: '#eb5050'
            },
            type: icon
        }) : null,
        onClick: ()=>{
            modal.confirm({
                title: t('Delete block'),
                content: t('Are you sure you want to delete it?'),
                ...confirm,
                async onOk () {
                    var _confirm_onOk;
                    const options = {
                        removeParentsIfNoChildren,
                        breakRemoveOn
                    };
                    if (null == field ? void 0 : field.required) {
                        field.required = false;
                        fieldSchema['required'] = false;
                    }
                    if (template && template.uid === fieldSchema['x-uid'] && (null == ctx ? void 0 : ctx.dn)) await (null == ctx ? void 0 : ctx.dn.remove(null, options));
                    else await dn.remove(null, options);
                    await (null == confirm ? void 0 : null == (_confirm_onOk = confirm.onOk) ? void 0 : _confirm_onOk.call(confirm));
                    delete form.values[fieldSchema.name];
                    null == removeActiveFieldName || removeActiveFieldName(fieldSchema.name);
                    if ((null == field ? void 0 : field.setInitialValue) && (null == field ? void 0 : field.reset)) {
                        field.setInitialValue(null);
                        field.reset();
                    }
                }
            });
        },
        children: /*#__PURE__*/ jsx("span", {
            style: {
                color: '#eb5050'
            },
            children: t('Delete')
        })
    });
};
const SchemaSettingsConnectDataBlocks = (props)=>{
    const { type, emptyDescription } = props;
    const fieldSchema = useFieldSchema();
    const { dn } = useDesignable();
    const { t } = useTranslation();
    const collection = useCollection_deprecated();
    const { inProvider } = useFilterBlock();
    const dataBlocks = useSupportedBlocks(type);
    let { targets = [], uid } = findFilterTargets(fieldSchema);
    const compile = useCompile();
    const { getAllCollectionsInheritChain } = useCollectionManager_deprecated();
    if (!inProvider) return null;
    const Content = dataBlocks.map((block)=>{
        const title = "".concat(compile(block.collection.title), " #").concat(block.uid.slice(0, 4));
        const onHover = ()=>{
            const originalScrollPosition = window.scrollY || window.pageYOffset || document.documentElement.scrollTop;
            const dom = block.dom;
            const designer = dom.querySelector('.general-schema-designer');
            if (designer) designer.style.display = 'block';
            dom.style.boxShadow = '0 0 10px rgba(0, 0, 0, 0.2)';
            setTimeout(()=>{
                dom.scrollIntoView({
                    behavior: 'smooth',
                    block: 'center'
                });
            }, 1000);
            setTimeout(()=>{
                window.scrollTo({
                    top: originalScrollPosition,
                    behavior: 'smooth'
                });
            }, 2000);
        };
        const onLeave = ()=>{
            const dom = block.dom;
            const designer = dom.querySelector('.general-schema-designer');
            if (designer) designer.style.display = null;
            dom.style.boxShadow = 'none';
        };
        if (isSameCollection(block.collection, collection)) return /*#__PURE__*/ jsx(SchemaSettingsSwitchItem, {
            title: title,
            checked: targets.some((target)=>target.uid === block.uid),
            onChange: (checked)=>{
                if (checked) targets.push({
                    uid: block.uid
                });
                else {
                    targets = targets.filter((target)=>target.uid !== block.uid);
                    block.clearFilter(uid);
                }
                updateFilterTargets(fieldSchema, targets);
                dn.emit('patch', {
                    schema: {
                        ['x-uid']: uid,
                        'x-filter-targets': targets
                    }
                }).catch(error);
                dn.refresh();
            },
            onMouseLeave: onLeave,
            onMouseUp: onHover
        }, block.uid);
        const target = targets.find((target)=>target.uid === block.uid);
        return /*#__PURE__*/ jsx(SchemaSettingsSelectItem, {
            title: title,
            value: (null == target ? void 0 : target.field) || '',
            options: [
                ...getSupportFieldsByAssociation(getAllCollectionsInheritChain(collection.name), block).map((field)=>({
                        label: compile(field.uiSchema.title) || field.name,
                        value: "".concat(field.name, ".").concat(getTargetKey(field))
                    })),
                ...getSupportFieldsByForeignKey(collection, block).map((field)=>({
                        label: "".concat(compile(field.uiSchema.title) || field.name, " [").concat(t('Foreign key'), "]"),
                        value: field.name
                    })),
                {
                    label: t('Unconnected'),
                    value: ''
                }
            ],
            onChange: (value)=>{
                if ('' === value) {
                    targets = targets.filter((target)=>target.uid !== block.uid);
                    block.clearFilter(uid);
                } else {
                    targets = targets.filter((target)=>target.uid !== block.uid);
                    targets.push({
                        uid: block.uid,
                        field: value
                    });
                }
                updateFilterTargets(fieldSchema, targets);
                dn.emit('patch', {
                    schema: {
                        ['x-uid']: uid,
                        'x-filter-targets': targets
                    }
                });
                dn.refresh();
            },
            onMouseEnter: onHover,
            onMouseLeave: onLeave
        }, block.uid);
    });
    return /*#__PURE__*/ jsx(SchemaSettingsSubMenu, {
        title: t('Connect data blocks'),
        children: Content.length ? Content : /*#__PURE__*/ jsx(SchemaSettingsItem, {
            title: "empty",
            children: /*#__PURE__*/ jsx(Empty, {
                style: {
                    width: 160,
                    padding: '0 1em'
                },
                description: emptyDescription,
                image: Empty.PRESENTED_IMAGE_SIMPLE
            })
        })
    });
};
const SchemaSettingsSelectItem = (props)=>{
    const { title, options, value, onChange, fieldNames, ...others } = props;
    return /*#__PURE__*/ jsx(SchemaSettingsItem, {
        title: title,
        ...others,
        children: /*#__PURE__*/ jsx(SelectWithTitle, {
            title,
            defaultValue: value,
            onChange,
            options,
            fieldNames
        })
    });
};
const SchemaSettingsCascaderItem = (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(Cascader, {
                    variant: "borderless",
                    defaultValue: value,
                    onChange: onChange,
                    options: options,
                    style: {
                        textAlign: 'right',
                        minWidth: 100
                    },
                    multiple: !!props.multiple,
                    ...props
                })
            ]
        })
    });
};
const SchemaSettingsSwitchItem = (props)=>{
    const { title, onChange, ...others } = props;
    const [checked, setChecked] = useState(!!props.checked);
    return /*#__PURE__*/ jsx(SchemaSettingsItem, {
        title: title,
        ...others,
        onClick: ()=>{
            null == onChange || onChange(!checked);
            setChecked(!checked);
        },
        children: /*#__PURE__*/ jsxs("div", {
            style: {
                alignItems: 'center',
                display: 'flex',
                justifyContent: 'space-between'
            },
            children: [
                title,
                /*#__PURE__*/ jsx(Switch, {
                    size: 'small',
                    checked: checked,
                    style: {
                        marginLeft: 32
                    }
                })
            ]
        })
    });
};
const SchemaSettingsPopupItem = (props)=>{
    const { schema, ...others } = props;
    const [visible, setVisible] = useState(false);
    const ctx = useContext(SchemaSettingsContext);
    return /*#__PURE__*/ jsxs(ActionContextProvider, {
        value: {
            visible,
            setVisible
        },
        children: [
            /*#__PURE__*/ jsx(SchemaSettingsItem, {
                title: props.title,
                ...others,
                onClick: ()=>{
                    ctx.setVisible(false);
                    setVisible(true);
                },
                children: props.children || props.title
            }),
            /*#__PURE__*/ jsx(SchemaComponent, {
                schema: {
                    name: schema_uid(),
                    ...schema
                }
            })
        ]
    });
};
const SchemaSettingsActionModalItem = /*#__PURE__*/ react.memo((props)=>{
    const { title, onSubmit, initialValues, beforeOpen, initialSchema, schema, modalTip, components, scope, ...others } = props;
    const [visible, setVisible] = useState(false);
    const [schemaUid, setSchemaUid] = useState(props.uid);
    const { t } = useTranslation();
    const fieldSchema = useFieldSchema();
    const ctx = useContext(SchemaSettingsContext);
    const { dn } = useSchemaSettings();
    const compile = useCompile();
    const api = useAPIClient();
    const upLevelActiveFields = useFormActiveFields();
    const form = useMemo(()=>createForm({
            initialValues: cloneDeep(initialValues),
            values: cloneDeep(initialValues)
        }), [
        initialValues
    ]);
    useEffect(()=>{
        form.setInitialValues(cloneDeep(initialValues));
    }, [
        JSON.stringify(initialValues || {})
    ]);
    const cancelHandler = useCallback(()=>{
        setVisible(false);
        form.reset();
    }, [
        form
    ]);
    const submitHandler = useCallback(async ()=>{
        await form.submit();
        null == onSubmit || onSubmit(cloneDeep(form.values));
        setVisible(false);
    }, [
        form,
        onSubmit
    ]);
    const openAssignedFieldValueHandler = useCallback(async ()=>{
        if (!schemaUid && (null == initialSchema ? void 0 : initialSchema['x-uid'])) {
            fieldSchema['x-action-settings'].schemaUid = initialSchema['x-uid'];
            dn.emit('patch', {
                schema: fieldSchema
            });
            await api.resource('uiSchemas').insert({
                values: initialSchema
            });
            setSchemaUid(initialSchema['x-uid']);
        }
        if ('function' == typeof beforeOpen) null == beforeOpen || beforeOpen();
        ctx.setVisible(false);
        setVisible(true);
    }, [
        api,
        ctx,
        dn,
        fieldSchema,
        initialSchema,
        schemaUid
    ]);
    const onKeyDown = useCallback((e)=>e.stopPropagation(), []);
    return /*#__PURE__*/ jsxs(Fragment, {
        children: [
            /*#__PURE__*/ jsx(SchemaSettingsItem, {
                title: compile(title),
                ...others,
                onClick: openAssignedFieldValueHandler,
                onKeyDown: onKeyDown,
                children: props.children || props.title
            }),
            /*#__PURE__*/ createPortal(/*#__PURE__*/ jsx(Modal, {
                width: '50%',
                title: compile(title),
                ...others,
                destroyOnClose: true,
                open: visible,
                onCancel: cancelHandler,
                footer: /*#__PURE__*/ jsxs(Space, {
                    children: [
                        /*#__PURE__*/ jsx(Button, {
                            onClick: cancelHandler,
                            children: t('Cancel')
                        }),
                        /*#__PURE__*/ jsx(Button, {
                            type: "primary",
                            onClick: submitHandler,
                            children: t('Submit')
                        })
                    ]
                }),
                children: /*#__PURE__*/ jsx(FormActiveFieldsProvider, {
                    name: "form",
                    getActiveFieldsName: null == upLevelActiveFields ? void 0 : upLevelActiveFields.getActiveFieldsName,
                    children: /*#__PURE__*/ jsx(FormProvider, {
                        form: form,
                        children: /*#__PURE__*/ jsxs(FormLayout, {
                            layout: 'vertical',
                            children: [
                                modalTip && /*#__PURE__*/ jsx(Alert, {
                                    message: modalTip
                                }),
                                modalTip && /*#__PURE__*/ jsx("br", {}),
                                visible && schemaUid && /*#__PURE__*/ jsx(RemoteSchemaComponent, {
                                    noForm: true,
                                    components: components,
                                    scope: scope,
                                    uid: schemaUid
                                }),
                                visible && schema && /*#__PURE__*/ jsx(SchemaComponent, {
                                    components: components,
                                    scope: scope,
                                    schema: schema
                                })
                            ]
                        })
                    })
                })
            }), document.body)
        ]
    });
});
SchemaSettingsActionModalItem.displayName = 'SchemaSettingsActionModalItem';
const SchemaSettingsModalItem = (props)=>{
    const { hidden, title, components, scope, effects, onSubmit, asyncGetInitialValues, initialValues, width = 'fit-content', ...others } = props;
    const options = useContext(SchemaOptionsContext);
    options.components = {
        ...options.components,
        Input: external_index_mjs_Input,
        'Input.TextArea': external_index_mjs_Input.TextArea,
        'Radio.Group': Radio.Group,
        'Checkbox.Group': Checkbox.Group,
        DatePicker: DatePicker,
        Select: Select,
        AlternativeAssociationSelect: void 0,
        Cascader: external_index_mjs_Cascader
    };
    const { styles } = useStyles();
    const collection = useCollection_deprecated();
    const apiClient = useAPIClient();
    const { theme } = useGlobalTheme();
    const ctx = useBlockRequestContext();
    const upLevelActiveFields = useFormActiveFields();
    const { locale } = useContext(ConfigProvider.ConfigContext);
    const dm = useDataSourceManager();
    const dataSourceKey = useDataSourceKey();
    const record = useCollectionRecord();
    const { association } = useDataBlockProps() || {};
    const formCtx = useFormBlockContext();
    const app = useApp();
    const { formValue: subFormValue, collection: subFormCollection } = useSubFormValue();
    const popupRecordVariable = useVariable('$nPopupRecord');
    if (hidden) return null;
    return /*#__PURE__*/ jsx(SchemaSettingsItem, {
        title: title,
        ...others,
        onClick: async ()=>{
            const values = asyncGetInitialValues ? await asyncGetInitialValues() : initialValues;
            const schema = lodash.isFunction(props.schema) ? props.schema() : props.schema;
            FormDialog({
                title: schema.title || title,
                width
            }, ()=>/*#__PURE__*/ jsx(DeclareVariable, {
                    name: "$nPopupRecord",
                    title: popupRecordVariable.title,
                    value: popupRecordVariable.value,
                    collection: popupRecordVariable.collection,
                    children: /*#__PURE__*/ jsx(ApplicationContext.Provider, {
                        value: app,
                        children: /*#__PURE__*/ jsx(CollectionRecordProvider, {
                            record: record,
                            children: /*#__PURE__*/ jsx(FormBlockContext.Provider, {
                                value: formCtx,
                                children: /*#__PURE__*/ jsx(SubFormProvider, {
                                    value: {
                                        value: subFormValue,
                                        collection: subFormCollection
                                    },
                                    children: /*#__PURE__*/ jsx(FormActiveFieldsProvider, {
                                        name: "form",
                                        getActiveFieldsName: null == upLevelActiveFields ? void 0 : upLevelActiveFields.getActiveFieldsName,
                                        children: /*#__PURE__*/ jsx(Router, {
                                            location: location,
                                            navigator: null,
                                            children: /*#__PURE__*/ jsx(BlockRequestContext_deprecated.Provider, {
                                                value: ctx,
                                                children: /*#__PURE__*/ jsx(DataSourceApplicationProvider, {
                                                    dataSourceManager: dm,
                                                    dataSource: dataSourceKey,
                                                    children: /*#__PURE__*/ jsx(AssociationOrCollectionProvider, {
                                                        allowNull: true,
                                                        collection: collection.name,
                                                        association: association,
                                                        children: /*#__PURE__*/ jsx(SchemaComponentOptions, {
                                                            scope: options.scope,
                                                            components: options.components,
                                                            children: /*#__PURE__*/ jsx(FormLayout, {
                                                                layout: 'vertical',
                                                                className: styles.modal,
                                                                children: /*#__PURE__*/ jsx(APIClientProvider, {
                                                                    apiClient: apiClient,
                                                                    children: /*#__PURE__*/ jsx(ConfigProvider, {
                                                                        locale: locale,
                                                                        children: /*#__PURE__*/ jsx(SchemaComponent, {
                                                                            components: components,
                                                                            scope: scope,
                                                                            schema: schema
                                                                        })
                                                                    })
                                                                })
                                                            })
                                                        })
                                                    })
                                                })
                                            })
                                        })
                                    })
                                })
                            })
                        })
                    })
                }), theme).open({
                initialValues: values,
                effects
            }).then((values)=>{
                onSubmit(values);
                return values;
            }).catch((err)=>{
                console.error(err);
            });
        },
        children: props.children || props.title
    });
};
const SchemaSettingsBlockTitleItem = function() {
    var _fieldSchema_xcomponentprops;
    const field = useField();
    const fieldSchema = useFieldSchema();
    const { dn } = useDesignable();
    const { t } = useTranslation();
    return /*#__PURE__*/ jsx(SchemaSettingsModalItem, {
        title: t('Edit block title'),
        schema: {
            type: 'object',
            title: t('Edit block title'),
            properties: {
                title: {
                    title: t('Block title'),
                    type: 'string',
                    default: null == fieldSchema ? void 0 : null == (_fieldSchema_xcomponentprops = fieldSchema['x-component-props']) ? void 0 : _fieldSchema_xcomponentprops['title'],
                    'x-decorator': 'FormItem',
                    'x-component': 'Input'
                }
            }
        },
        onSubmit: (param)=>{
            let { title } = param;
            const componentProps = fieldSchema['x-component-props'] || {};
            componentProps.title = title;
            fieldSchema['x-component-props'] = componentProps;
            field.componentProps.title = title;
            dn.emit('patch', {
                schema: {
                    ['x-uid']: fieldSchema['x-uid'],
                    'x-component-props': fieldSchema['x-component-props']
                }
            });
            dn.refresh();
        }
    });
};
const SchemaSettingsDefaultSortingRules = function(props) {
    const { path = 'x-component-props.params.sort' } = props;
    const { t } = useTranslation();
    const { dn } = useDesignable();
    const fieldSchema = useFieldSchema();
    const field = useField();
    const title = props.title || t('Set default sorting rules');
    const { name } = useCollection_deprecated();
    const defaultSort = get(fieldSchema, path) || [];
    const sort = null == defaultSort ? void 0 : defaultSort.map((item)=>item.startsWith('-') ? {
            field: item.substring(1),
            direction: 'desc'
        } : {
            field: item,
            direction: 'asc'
        });
    const sortFields = useSortFields(props.name || name);
    const onSubmit = async (param)=>{
        let { sort } = param;
        var _props_onSubmitAfter;
        if (null == props ? void 0 : props.onSubmit) return props.onSubmit({
            sort
        });
        const value = sort.map((item)=>'desc' === item.direction ? "-".concat(item.field) : item.field);
        set(field, path.replace('x-component-props', 'componentProps').replace('x-decorator-props', 'decoratorProps'), value);
        set(fieldSchema, path, value);
        await dn.emit('patch', {
            schema: fieldSchema
        });
        return null == (_props_onSubmitAfter = props.onSubmitAfter) ? void 0 : _props_onSubmitAfter.call(props);
    };
    return /*#__PURE__*/ jsx(SchemaSettingsModalItem, {
        title: title,
        components: {
            ArrayItems: ArrayItems
        },
        schema: {
            type: 'object',
            title,
            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: onSubmit
    });
};
const SchemaSettingsLinkageRules = function(props) {
    const { collectionName } = props;
    const fieldSchema = useFieldSchema();
    const { form } = useFormBlockContext();
    const { dn } = useDesignable();
    const { t } = useTranslation();
    const { getTemplateById } = useSchemaTemplateManager();
    const variables = useVariables();
    const localVariables = useLocalVariables();
    const record = useRecord();
    const { type: formBlockType } = useFormBlockType();
    const type = (null == props ? void 0 : props.type) || [
        'Action',
        'Action.Link'
    ].includes(fieldSchema['x-component']) ? 'button' : 'field';
    const gridSchema = findGridSchema(fieldSchema) || fieldSchema;
    const schema = useMemo(()=>({
            type: 'object',
            title: t('Linkage rules'),
            properties: {
                fieldReaction: {
                    'x-component': FormLinkageRules,
                    'x-use-component-props': ()=>{
                        const options = useLinkageCollectionFilterOptions(collectionName);
                        const result = {
                            options,
                            defaultValues: (null == gridSchema ? void 0 : gridSchema['x-linkage-rules']) || (null == fieldSchema ? void 0 : fieldSchema['x-linkage-rules']),
                            type,
                            linkageOptions: useLinkageCollectionFieldOptions(collectionName),
                            collectionName,
                            form,
                            variables,
                            localVariables,
                            record,
                            formBlockType
                        };
                        return result;
                    }
                }
            }
        }), [
        collectionName,
        fieldSchema,
        form,
        gridSchema,
        localVariables,
        record,
        t,
        type,
        variables
    ]);
    const components = useMemo(()=>({
            ArrayCollapse: ArrayCollapse,
            FormLayout: FormLayout
        }), []);
    const onSubmit = useCallback((v)=>{
        var _gridSchema_xcomponentprops;
        const rules = [];
        for (const rule of v.fieldReaction.rules)rules.push(lodash.pickBy(rule, lodash.identity));
        const templateId = 'BlockTemplate' === gridSchema['x-component'] && (null == (_gridSchema_xcomponentprops = gridSchema['x-component-props']) ? void 0 : _gridSchema_xcomponentprops.templateId);
        const uid = templateId && getTemplateById(templateId).uid || gridSchema['x-uid'];
        const schema = {
            ['x-uid']: uid
        };
        gridSchema['x-linkage-rules'] = rules;
        schema['x-linkage-rules'] = rules;
        dn.emit('patch', {
            schema
        });
        dn.refresh();
    }, [
        dn,
        getTemplateById,
        gridSchema
    ]);
    return /*#__PURE__*/ jsx(SchemaSettingsModalItem, {
        title: t('Linkage rules'),
        components: components,
        width: 770,
        schema: schema,
        onSubmit: onSubmit
    });
};
const useDataTemplates = (schema)=>{
    const fieldSchema = useFieldSchema();
    if (schema) return {
        templateData: lodash.cloneDeep(schema['x-data-templates'])
    };
    const formSchema = findFormBlock(fieldSchema) || fieldSchema;
    return {
        templateData: lodash.cloneDeep(null == formSchema ? void 0 : formSchema['x-data-templates'])
    };
};
const SchemaSettingsDataTemplates = function(props) {
    const designerCtx = useContext(SchemaComponentContext);
    const { collectionName } = props;
    const fieldSchema = useFieldSchema();
    const { dn } = useDesignable();
    const { t } = useTranslation();
    const formSchema = findFormBlock(fieldSchema) || fieldSchema;
    const { templateData } = useDataTemplates();
    const schema = useMemo(()=>({
            type: 'object',
            title: t('Form data templates'),
            properties: {
                fieldReaction: {
                    'x-decorator': (props)=>/*#__PURE__*/ jsx(FlagProvider, {
                            ...props,
                            isInFormDataTemplate: true
                        }),
                    'x-component': FormDataTemplates,
                    'x-use-component-props': ()=>({
                            defaultValues: templateData,
                            collectionName
                        }),
                    'x-component-props': {
                        designerCtx,
                        formSchema
                    }
                }
            }
        }), [
        templateData
    ]);
    const onSubmit = useCallback((v)=>{
        const data = {
            ...formSchema['x-data-templates'],
            ...v.fieldReaction
        };
        data.items.forEach((item)=>{
            item.fields = Array.isArray(item.fields) ? item.fields : item.fields.checked;
        });
        const schema = {
            ['x-uid']: formSchema['x-uid'],
            ['x-data-templates']: data
        };
        formSchema['x-data-templates'] = data;
        dn.emit('patch', {
            schema
        });
        dn.refresh();
    }, []);
    const title = useMemo(()=>t('Form data templates'), []);
    const components = useMemo(()=>({
            ArrayCollapse: ArrayCollapse,
            FormLayout: FormLayout
        }), []);
    return /*#__PURE__*/ jsx(SchemaSettingsModalItem, {
        title: title,
        components: components,
        width: 770,
        schema: schema,
        onSubmit: onSubmit
    });
};
function SchemaSettingsEnableChildCollections(props) {
    var _fieldSchema_parent, _fieldSchema_parent1, _fieldSchema_xcomponentprops;
    const { collectionName } = props;
    const fieldSchema = useFieldSchema();
    const field = useField();
    const { dn } = useDesignable();
    const { t } = useTranslation();
    const allowAddToCurrent = null == fieldSchema ? void 0 : fieldSchema['x-allow-add-to-current'];
    const { getCollectionJoinField } = useCollectionManager_deprecated();
    const ctx = useBlockRequestContext();
    const collectionField = getCollectionJoinField(null == fieldSchema ? void 0 : null == (_fieldSchema_parent = fieldSchema.parent) ? void 0 : _fieldSchema_parent['x-collection-field']) || {};
    const isAssocationAdd = (null == fieldSchema ? void 0 : null == (_fieldSchema_parent1 = fieldSchema.parent) ? void 0 : _fieldSchema_parent1['x-component']) === 'CollectionField';
    return /*#__PURE__*/ jsx(SchemaSettingsModalItem, {
        title: t('Enable child collections'),
        components: {
            ArrayItems: ArrayItems,
            FormLayout: FormLayout
        },
        scope: {
            isAssocationAdd
        },
        schema: {
            type: 'object',
            title: t('Enable child collections'),
            properties: {
                enableChildren: {
                    'x-component': EnableChildCollections,
                    'x-use-component-props': ()=>({
                            defaultValues: null == fieldSchema ? void 0 : fieldSchema['x-enable-children'],
                            collectionName
                        })
                },
                allowAddToCurrent: {
                    type: 'boolean',
                    'x-content': "{{t('Allow adding records to the current collection')}}",
                    'x-decorator': 'FormItem',
                    'x-component': 'Checkbox',
                    default: void 0 === allowAddToCurrent ? true : allowAddToCurrent
                },
                linkageFromForm: {
                    type: 'string',
                    title: "{{t('Linkage with form fields')}}",
                    'x-visible': '{{isAssocationAdd}}',
                    'x-decorator': 'FormItem',
                    'x-component': ChildDynamicComponent,
                    'x-component-props': {
                        rootCollection: ctx.props.collection || ctx.props.resource,
                        collectionField
                    },
                    default: null == fieldSchema ? void 0 : null == (_fieldSchema_xcomponentprops = fieldSchema['x-component-props']) ? void 0 : _fieldSchema_xcomponentprops['linkageFromForm']
                }
            }
        },
        onSubmit: (v)=>{
            const enableChildren = [];
            for (const item of v.enableChildren.childrenCollections)enableChildren.push(lodash.pickBy(item, lodash.identity));
            const uid = fieldSchema['x-uid'];
            const schema = {
                ['x-uid']: uid
            };
            fieldSchema['x-enable-children'] = enableChildren;
            fieldSchema['x-allow-add-to-current'] = v.allowAddToCurrent;
            fieldSchema['x-component-props'] = {
                ...fieldSchema['x-component-props'],
                component: 'CreateRecordAction',
                linkageFromForm: null == v ? void 0 : v.linkageFromForm
            };
            schema['x-enable-children'] = enableChildren;
            schema['x-allow-add-to-current'] = v.allowAddToCurrent;
            schema['x-component-props'] = {
                ...fieldSchema['x-component-props'],
                component: 'CreateRecordAction',
                linkageFromForm: null == v ? void 0 : v.linkageFromForm
            };
            field.componentProps['linkageFromForm'] = v.linkageFromForm;
            dn.emit('patch', {
                schema
            });
            dn.refresh();
        }
    });
}
const findParentFieldSchema = (fieldSchema)=>{
    let parent = fieldSchema.parent;
    while(parent){
        if ('CollectionField' === parent['x-component']) return parent;
        parent = parent.parent;
    }
};
const SchemaSettingsSortField = ()=>{
    const { fields } = useCollection_deprecated();
    const field = useField();
    const fieldSchema = useFieldSchema();
    const { t } = useTranslation();
    const { dn } = useDesignable();
    const compile = useCompile();
    const { service } = useTableBlockContext();
    const options = fields.filter((field)=>!(null == field ? void 0 : field.target) && 'sort' === field.interface).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__*/ jsx(SchemaSettingsSelectItem, {
        title: t('Drag and drop sorting field'),
        options: options,
        value: field.decoratorProps.dragSortBy,
        onChange: (dragSortBy)=>{
            var _service_params;
            fieldSchema['x-decorator-props'].dragSortBy = dragSortBy;
            service.run({
                ...null == (_service_params = service.params) ? void 0 : _service_params[0],
                sort: dragSortBy
            });
            field.decoratorProps.dragSortBy = dragSortBy;
            dn.emit('patch', {
                schema: {
                    ['x-uid']: fieldSchema['x-uid'],
                    'x-decorator-props': fieldSchema['x-decorator-props']
                }
            });
            dn.refresh();
        }
    }, "sort-field");
};
const isSystemField = (collectionField, getInterface)=>{
    const i = null == getInterface ? void 0 : getInterface(null == collectionField ? void 0 : collectionField.interface);
    return (null == i ? void 0 : i.group) === 'systemInfo';
};
function getFieldDefaultValue(fieldSchema, collectionField) {
    var _fieldSchema_default;
    const result = null != (_fieldSchema_default = null == fieldSchema ? void 0 : fieldSchema.default) ? _fieldSchema_default : null == collectionField ? void 0 : collectionField.defaultValue;
    return result;
}
export { SchemaSettingsActionModalItem, SchemaSettingsBlockTitleItem, SchemaSettingsCascaderItem, SchemaSettingsConnectDataBlocks, SchemaSettingsDataTemplates, SchemaSettingsDefaultSortingRules, SchemaSettingsDivider, SchemaSettingsDropdown, SchemaSettingsEnableChildCollections, SchemaSettingsFormItemTemplate, SchemaSettingsItem, SchemaSettingsItemGroup, SchemaSettingsLinkageRules, SchemaSettingsModalItem, SchemaSettingsPopupItem, SchemaSettingsProvider, SchemaSettingsRemove, SchemaSettingsSelectItem, SchemaSettingsSortField, SchemaSettingsSubMenu, SchemaSettingsSwitchItem, SchemaSettingsTemplate, findParentFieldSchema, getFieldDefaultValue, isSystemField, useDataTemplates, useSchemaSettings };
