import * as __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__ from "react/jsx-runtime";
import * as __WEBPACK_EXTERNAL_MODULE__tachybase_components__ from "@tachybase/components";
import * as __WEBPACK_EXTERNAL_MODULE__tachybase_schema__ from "@tachybase/schema";
import * as __WEBPACK_EXTERNAL_MODULE_antd__ from "antd";
import * as __WEBPACK_EXTERNAL_MODULE_file_saver__ from "file-saver";
import * as __WEBPACK_EXTERNAL_MODULE_react_i18next__ from "react-i18next";
import * as __WEBPACK_EXTERNAL_MODULE__index_mjs__ from "./index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__index_mjs__ from "../../index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__index_mjs__ from "../../../index.mjs";
const toItems = function() {
    let properties = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {};
    const items = [];
    for(const key in properties)if (Object.prototype.hasOwnProperty.call(properties, key)) {
        const element = properties[key];
        const item = {
            label: element.title,
            value: "".concat(element['x-uid'], "||").concat(element['x-component'])
        };
        if (element.properties) {
            const children = toItems(element.properties);
            if (null == children ? void 0 : children.length) item['children'] = children;
        }
        items.push(item);
    }
    return items;
};
const findMenuSchema = (fieldSchema)=>{
    let parent = fieldSchema.parent;
    while(parent){
        if ('Menu' === parent['x-component']) return parent;
        parent = parent.parent;
    }
};
const InsertMenuItemsGroup = (props)=>{
    const { t } = (0, __WEBPACK_EXTERNAL_MODULE_react_i18next__.useTranslation)();
    const designable = (0, __WEBPACK_EXTERNAL_MODULE__index_mjs__.useDesignable)();
    const api = (0, __WEBPACK_EXTERNAL_MODULE__index_mjs__.useAPIClient)();
    const serverHooks = [
        {
            type: 'onSelfCreate',
            method: 'bindMenuToRole'
        },
        {
            type: 'onSelfSave',
            method: 'extractTextToLocale'
        }
    ];
    const insertPosition = 'beforeEnd';
    const dn = props.dn || designable.dn;
    return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsxs)(__WEBPACK_EXTERNAL_MODULE__index_mjs__.SchemaSettingsItemGroup, {
        children: [
            /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__index_mjs__.SchemaSettingsModalItem, {
                eventKey: "".concat(insertPosition, "group"),
                icon: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__index_mjs__.Icon, {
                    type: 'FolderAddOutlined'
                }),
                title: t('Create group'),
                schema: {
                    type: 'object',
                    title: t('Create group'),
                    properties: {
                        title: {
                            'x-decorator': 'FormItem',
                            'x-component': 'Input',
                            'x-component-props': {},
                            title: t('Menu item title'),
                            required: true
                        },
                        icon: {
                            title: t('Icon'),
                            'x-component': 'IconPicker',
                            'x-decorator': 'FormItem'
                        }
                    }
                },
                onSubmit: (param)=>{
                    let { title, icon } = param;
                    dn.insertAdjacent(insertPosition, {
                        type: 'void',
                        title,
                        'x-component': 'Menu.SubMenu',
                        'x-decorator': 'ACLMenuItemProvider',
                        'x-component-props': {
                            icon
                        },
                        'x-server-hooks': serverHooks
                    });
                }
            }),
            /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__index_mjs__.SchemaSettingsModalItem, {
                eventKey: "".concat(insertPosition, "page"),
                icon: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__index_mjs__.Icon, {
                    type: 'FileOutlined'
                }),
                title: t('Create page'),
                schema: {
                    type: 'object',
                    title: t('Create page'),
                    properties: {
                        title: {
                            'x-decorator': 'FormItem',
                            'x-component': 'Input',
                            title: t('Menu item title'),
                            required: true,
                            'x-component-props': {}
                        },
                        icon: {
                            title: t('Icon'),
                            'x-component': 'IconPicker',
                            'x-decorator': 'FormItem'
                        }
                    }
                },
                onSubmit: (param)=>{
                    let { title, icon } = param;
                    dn.insertAdjacent(insertPosition, {
                        type: 'void',
                        title,
                        'x-component': 'Menu.Item',
                        'x-decorator': 'ACLMenuItemProvider',
                        'x-component-props': {
                            icon
                        },
                        'x-server-hooks': serverHooks,
                        properties: {
                            page: {
                                type: 'void',
                                'x-component': 'Page',
                                'x-async': true,
                                properties: {
                                    grid: {
                                        type: 'void',
                                        'x-component': 'Grid',
                                        'x-initializer': 'page:addBlock',
                                        properties: {}
                                    }
                                }
                            }
                        }
                    });
                }
            }),
            /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__index_mjs__.SchemaSettingsModalItem, {
                eventKey: "".concat(insertPosition, "link"),
                icon: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__index_mjs__.Icon, {
                    type: 'GlobalOutlined'
                }),
                title: t('Create link'),
                schema: {
                    type: 'object',
                    title: t('Create link'),
                    properties: {
                        title: {
                            title: t('Menu item title'),
                            required: true,
                            'x-component': 'Input',
                            'x-decorator': 'FormItem'
                        },
                        icon: {
                            title: t('Icon'),
                            'x-component': 'IconPicker',
                            'x-decorator': 'FormItem'
                        },
                        href: {
                            title: t('Link'),
                            'x-component': 'Input',
                            'x-decorator': 'FormItem'
                        }
                    }
                },
                onSubmit: (param)=>{
                    let { title, icon, href } = param;
                    dn.insertAdjacent(insertPosition, {
                        type: 'void',
                        title,
                        'x-component': 'Menu.URL',
                        'x-decorator': 'ACLMenuItemProvider',
                        'x-component-props': {
                            icon,
                            href
                        },
                        'x-server-hooks': serverHooks
                    });
                }
            }),
            /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__index_mjs__.SchemaSettingsDivider, {}),
            /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__index_mjs__.SchemaSettingsModalItem, {
                eventKey: "".concat(insertPosition, "restore"),
                icon: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__index_mjs__.Icon, {
                    type: 'UploadOutlined'
                }),
                title: t('Load menu config'),
                schema: {
                    type: 'object',
                    title: t('Load menu config'),
                    properties: {
                        title: {
                            'x-decorator': 'FormItem',
                            'x-component': 'Input',
                            title: t('Menu item title'),
                            required: true,
                            'x-component-props': {}
                        },
                        bindMenuToRole: {
                            type: 'boolean',
                            title: '{{ t("Automatically assign permissions to all matching roles") }}',
                            'x-decorator': 'FormItem',
                            'x-component': 'Checkbox',
                            default: true
                        },
                        file: {
                            type: 'object',
                            title: '{{ t("File") }}',
                            required: true,
                            'x-decorator': 'FormItem',
                            'x-component': 'Upload.Attachment',
                            'x-component-props': {
                                action: 'attachments:create',
                                multiple: false
                            }
                        }
                    }
                },
                onSubmit: async (param)=>{
                    let { title, file, bindMenuToRole } = param;
                    const { data } = await api.request({
                        url: file.url,
                        baseURL: '/'
                    });
                    const s = null != data ? data : {};
                    if (bindMenuToRole) {
                        const hooks = data['x-server-hooks'];
                        if (!hooks.some((v)=>'onSelfCreate' === v.type && 'bindMenuToRole' === v.method)) hooks.push({
                            type: 'onSelfCreate',
                            method: 'bindMenuToRole'
                        });
                    }
                    s.title = title;
                    dn.insertAdjacent(insertPosition, s);
                }
            })
        ]
    });
};
const MenuDesigner = (props)=>{
    const { isAdminMenu } = props;
    const field = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useField)();
    const fieldSchema = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useFieldSchema)();
    const api = (0, __WEBPACK_EXTERNAL_MODULE__index_mjs__.useAPIClient)();
    const { message } = __WEBPACK_EXTERNAL_MODULE_antd__.App.useApp();
    const { dn, refresh } = (0, __WEBPACK_EXTERNAL_MODULE__index_mjs__.useDesignable)();
    const { t } = (0, __WEBPACK_EXTERNAL_MODULE_react_i18next__.useTranslation)();
    const menuSchema = findMenuSchema(fieldSchema);
    const items = toItems(null == menuSchema ? void 0 : menuSchema.properties);
    const effects = (form)=>{
        (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.onFieldChange)('target', (field)=>{
            var _field_value_split, _field_value;
            const [, component] = (null == field ? void 0 : null === (_field_value = field.value) || void 0 === _field_value ? void 0 : null === (_field_value_split = _field_value.split) || void 0 === _field_value_split ? void 0 : _field_value_split.call(_field_value, '||')) || [];
            field.query('position').take((f)=>{
                f.dataSource = 'Menu.SubMenu' === component ? [
                    {
                        label: t('Before'),
                        value: 'beforeBegin'
                    },
                    {
                        label: t('After'),
                        value: 'afterEnd'
                    },
                    {
                        label: t('Inner'),
                        value: 'beforeEnd'
                    }
                ] : [
                    {
                        label: t('Before'),
                        value: 'beforeBegin'
                    },
                    {
                        label: t('After'),
                        value: 'afterEnd'
                    }
                ];
            });
        });
    };
    const schema = {
        type: 'object',
        title: t('Edit menu item'),
        properties: {
            title: {
                title: t('Menu item title'),
                required: true,
                'x-decorator': 'FormItem',
                'x-component': 'Input',
                'x-component-props': {}
            },
            icon: {
                title: t('Menu item icon'),
                'x-decorator': 'FormItem',
                'x-component': 'IconPicker'
            }
        }
    };
    const initialValues = {
        title: field.title,
        icon: field.componentProps.icon
    };
    const isSubMenu = 'Menu.SubMenu' === fieldSchema['x-component'];
    const hiddenAddMenu = isAdminMenu || !isSubMenu;
    if ('Menu.URL' === fieldSchema['x-component']) {
        schema.properties['href'] = {
            title: t('Link'),
            'x-component': 'Input',
            'x-decorator': 'FormItem'
        };
        initialValues['href'] = field.componentProps.href;
    }
    return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsxs)(__WEBPACK_EXTERNAL_MODULE__index_mjs__.GeneralSchemaDesigner, {
        draggable: false,
        AddMenuModalComponent: !hiddenAddMenu && /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(InsertMenuItemsGroup, {}),
        children: [
            /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__index_mjs__.SchemaSettingsModalItem, {
                title: t('Modify the name and icon'),
                eventKey: "edit",
                icon: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__index_mjs__.Icon, {
                    type: 'FormOutlined'
                }),
                schema: schema,
                initialValues: initialValues,
                onSubmit: (param)=>{
                    let { title, icon, href } = param;
                    const schema = {
                        ['x-uid']: fieldSchema['x-uid'],
                        'x-server-hooks': [
                            {
                                type: 'onSelfSave',
                                method: 'extractTextToLocale'
                            }
                        ]
                    };
                    if (title) {
                        fieldSchema.title = title;
                        field.title = title;
                        schema['title'] = title;
                        refresh();
                    }
                    field.componentProps.icon = icon;
                    field.componentProps.href = href;
                    schema['x-component-props'] = {
                        icon,
                        href
                    };
                    fieldSchema['x-component-props'] = fieldSchema['x-component-props'] || {};
                    fieldSchema['x-component-props']['icon'] = icon;
                    fieldSchema['x-component-props']['href'] = href;
                    dn.emit('patch', {
                        schema
                    });
                }
            }),
            /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__index_mjs__.SchemaSettingsModalItem, {
                title: t('Move to'),
                eventKey: "move-to",
                components: {
                    TreeSelect: __WEBPACK_EXTERNAL_MODULE__tachybase_components__.TreeSelect
                },
                effects: effects,
                icon: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__index_mjs__.Icon, {
                    type: 'DragOutlined'
                }),
                schema: {
                    type: 'object',
                    title: t('Move to'),
                    properties: {
                        target: {
                            title: t('Target'),
                            enum: items,
                            required: true,
                            'x-decorator': 'FormItem',
                            'x-component': 'TreeSelect',
                            'x-component-props': {}
                        },
                        position: {
                            title: t('Position'),
                            required: true,
                            enum: [
                                {
                                    label: t('Before'),
                                    value: 'beforeBegin'
                                },
                                {
                                    label: t('After'),
                                    value: 'afterEnd'
                                }
                            ],
                            default: 'afterEnd',
                            'x-component': 'Radio.Group',
                            'x-decorator': 'FormItem'
                        }
                    }
                },
                onSubmit: (param)=>{
                    let { target, position } = param;
                    var _target_split;
                    const [uid] = (null == target ? void 0 : null === (_target_split = target.split) || void 0 === _target_split ? void 0 : _target_split.call(target, '||')) || [];
                    if (!uid) return;
                    const current = (0, __WEBPACK_EXTERNAL_MODULE__index_mjs__.findByUid)(menuSchema, uid);
                    const dn = (0, __WEBPACK_EXTERNAL_MODULE__index_mjs__.createDesignable)({
                        t,
                        api,
                        refresh,
                        current
                    });
                    dn.loadAPIClientEvents();
                    dn.insertAdjacent(position, fieldSchema);
                }
            }),
            /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__index_mjs__.SchemaSettingsDivider, {}),
            /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__index_mjs__.SchemaSettingsItem, {
                title: t('Dump'),
                icon: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__index_mjs__.Icon, {
                    type: 'DownloadOutlined'
                }),
                onClick: async ()=>{
                    const deleteUid = (s)=>{
                        delete s['name'];
                        delete s['x-uid'];
                        Object.keys(s.properties || {}).forEach((key)=>{
                            deleteUid(s.properties[key]);
                        });
                    };
                    const { data } = await api.request({
                        url: "/uiSchemas:getJsonSchema/".concat(fieldSchema['x-uid'], "?includeAsyncNode=true")
                    });
                    const s = (null == data ? void 0 : data.data) || {};
                    deleteUid(s);
                    const blob = new Blob([
                        JSON.stringify(s, null, 2)
                    ], {
                        type: 'application/json'
                    });
                    (0, __WEBPACK_EXTERNAL_MODULE_file_saver__.saveAs)(blob, fieldSchema['x-uid'] + '.schema.json');
                    message.success('Save successful!');
                }
            }),
            /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__index_mjs__.SchemaSettingsRemove, {
                icon: "DeleteOutlined",
                confirm: {
                    title: t('Delete menu item')
                }
            })
        ]
    });
};
export { InsertMenuItemsGroup, MenuDesigner };
