"use strict";
var __webpack_require__ = {};
(()=>{
    __webpack_require__.n = function(module) {
        var getter = module && module.__esModule ? function() {
            return module['default'];
        } : function() {
            return module;
        };
        __webpack_require__.d(getter, {
            a: getter
        });
        return getter;
    };
})();
(()=>{
    __webpack_require__.d = function(exports1, definition) {
        for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
            enumerable: true,
            get: definition[key]
        });
    };
})();
(()=>{
    __webpack_require__.o = function(obj, prop) {
        return Object.prototype.hasOwnProperty.call(obj, prop);
    };
})();
(()=>{
    __webpack_require__.r = function(exports1) {
        if ('undefined' != typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
            value: 'Module'
        });
        Object.defineProperty(exports1, '__esModule', {
            value: true
        });
    };
})();
var __webpack_exports__ = {};
__webpack_require__.r(__webpack_exports__);
__webpack_require__.d(__webpack_exports__, {
    useCollectionFieldFormValues: ()=>useCollectionFieldFormValues,
    AddCollectionField: ()=>AddCollectionField,
    AddFieldAction: ()=>AddFieldAction
});
const jsx_runtime_namespaceObject = require("react/jsx-runtime");
const external_react_namespaceObject = require("react");
const components_namespaceObject = require("@tachybase/components");
const schema_namespaceObject = require("@tachybase/schema");
const icons_namespaceObject = require("@ant-design/icons");
const external_antd_namespaceObject = require("antd");
const external_lodash_namespaceObject = require("lodash");
const external_react_i18next_namespaceObject = require("react-i18next");
const index_js_namespaceObject = require("../../api-client/index.js");
const external_record_provider_index_js_namespaceObject = require("../../record-provider/index.js");
const external_schema_component_index_js_namespaceObject = require("../../schema-component/index.js");
const external_action_hooks_js_namespaceObject = require("../action-hooks.js");
const external_hooks_index_js_namespaceObject = require("../hooks/index.js");
const useDialect_js_namespaceObject = require("../hooks/useDialect.js");
var useDialect_js_default = /*#__PURE__*/ __webpack_require__.n(useDialect_js_namespaceObject);
const external_ResourceActionProvider_js_namespaceObject = require("../ResourceActionProvider.js");
const external_components_index_js_namespaceObject = require("./components/index.js");
const external_interfaces_js_namespaceObject = require("./interfaces.js");
const getSchema = (schema, record, compile)=>{
    if (!schema) return;
    const properties = (0, external_lodash_namespaceObject.cloneDeep)(schema.properties);
    if (true === schema.hasDefaultValue) {
        var _schema_default;
        properties['defaultValue'] = (0, external_lodash_namespaceObject.cloneDeep)(null == schema ? void 0 : null === (_schema_default = schema.default) || void 0 === _schema_default ? void 0 : _schema_default.uiSchema);
        properties.defaultValue.required = false;
        properties['defaultValue']['title'] = compile('{{ t("Default value") }}');
        properties['defaultValue']['x-decorator'] = 'FormItem';
        properties['defaultValue']['x-reactions'] = [
            {
                dependencies: [
                    'uiSchema.x-component-props.gmt',
                    'uiSchema.x-component-props.showTime',
                    'uiSchema.x-component-props.dateFormat',
                    'uiSchema.x-component-props.timeFormat'
                ],
                fulfill: {
                    state: {
                        componentProps: {
                            gmt: '{{$deps[0]}}',
                            showTime: '{{$deps[1]}}',
                            dateFormat: '{{$deps[2]}}',
                            timeFormat: '{{$deps[3]}}'
                        }
                    }
                }
            },
            {
                dependencies: [
                    'primaryKey',
                    'unique',
                    'autoIncrement'
                ],
                when: '{{$deps[0]||$deps[1]||$deps[2]}}',
                fulfill: {
                    state: {
                        hidden: true,
                        value: null
                    }
                },
                otherwise: {
                    state: {
                        hidden: false
                    }
                }
            }
        ];
    }
    const initialValue = {
        name: "f_".concat((0, schema_namespaceObject.uid)()),
        ...(0, external_lodash_namespaceObject.cloneDeep)(schema.default),
        interface: schema.name
    };
    if (initialValue.reverseField) initialValue.reverseField.name = "f_".concat((0, schema_namespaceObject.uid)());
    return {
        type: 'object',
        properties: {
            [(0, schema_namespaceObject.uid)()]: {
                type: 'void',
                'x-component': 'Action.Drawer',
                'x-component-props': {
                    getContainer: '{{ getContainer }}'
                },
                'x-decorator': 'Form',
                'x-decorator-props': {
                    useValues (options) {
                        return (0, index_js_namespaceObject.useRequest)(()=>Promise.resolve({
                                data: initialValue
                            }), options);
                    }
                },
                title: "".concat(compile(record.title), " - ").concat(compile('{{ t("Add field") }}')),
                properties: {
                    summary: {
                        type: 'void',
                        'x-component': 'FieldSummary',
                        'x-component-props': {
                            schemaKey: schema.name
                        }
                    },
                    ...properties,
                    description: {
                        type: 'string',
                        title: '{{t("Description")}}',
                        'x-decorator': 'FormItem',
                        'x-component': 'Input.TextArea'
                    },
                    footer: {
                        type: 'void',
                        'x-component': 'Action.Drawer.Footer',
                        properties: {
                            action1: {
                                title: '{{ t("Cancel") }}',
                                'x-component': 'Action',
                                'x-component-props': {
                                    useAction: '{{ useCancelAction }}'
                                }
                            },
                            action2: {
                                title: '{{ t("Submit") }}',
                                'x-component': 'Action',
                                'x-component-props': {
                                    type: 'primary',
                                    useAction: '{{ useCreateCollectionField }}'
                                }
                            }
                        }
                    }
                }
            }
        }
    };
};
const useCollectionFieldFormValues = ()=>{
    const form = (0, schema_namespaceObject.useForm)();
    return {
        getValues () {
            const values = (0, external_lodash_namespaceObject.cloneDeep)(form.values);
            values.autoCreateReverseField || delete values.reverseField;
            delete values.autoCreateReverseField;
            return values;
        }
    };
};
const useCreateCollectionField = ()=>{
    const form = (0, schema_namespaceObject.useForm)();
    const { refreshCM } = (0, external_hooks_index_js_namespaceObject.useCollectionManager_deprecated)();
    const ctx = (0, external_schema_component_index_js_namespaceObject.useActionContext)();
    const { refresh } = (0, external_ResourceActionProvider_js_namespaceObject.useResourceActionContext)();
    const { resource } = (0, external_ResourceActionProvider_js_namespaceObject.useResourceContext)();
    const field = (0, schema_namespaceObject.useField)();
    return {
        async run () {
            await form.submit();
            field.data = field.data || {};
            field.data.loading = true;
            const values = (0, external_lodash_namespaceObject.cloneDeep)(form.values);
            values.autoCreateReverseField || delete values.reverseField;
            delete values.autoCreateReverseField;
            try {
                await resource.create({
                    values
                });
                ctx.setVisible(false);
                await form.reset();
                field.data.loading = false;
                refresh();
                await refreshCM();
            } catch (error) {
                field.data.loading = false;
            }
        }
    };
};
const AddCollectionField = (props)=>{
    const record = (0, external_record_provider_index_js_namespaceObject.useRecord)();
    return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(AddFieldAction, {
        item: record,
        ...props
    });
};
const AddFieldAction = (props)=>{
    var _getCollection_options, _getCollection;
    const { scope, getContainer, item: record, children, trigger, align, database } = props;
    const { getInterface, getTemplate, collections, getCollection } = (0, external_hooks_index_js_namespaceObject.useCollectionManager_deprecated)();
    const [visible, setVisible] = (0, external_react_namespaceObject.useState)(false);
    const [targetScope, setTargetScope] = (0, external_react_namespaceObject.useState)();
    const [schema, setSchema] = (0, external_react_namespaceObject.useState)({});
    const compile = (0, external_schema_component_index_js_namespaceObject.useCompile)();
    const { t } = (0, external_react_i18next_namespaceObject.useTranslation)();
    const { isDialect } = useDialect_js_default()();
    const options = (0, external_interfaces_js_namespaceObject.useFieldInterfaceOptions)();
    const fields = (null === (_getCollection = getCollection(record.name)) || void 0 === _getCollection ? void 0 : null === (_getCollection_options = _getCollection.options) || void 0 === _getCollection_options ? void 0 : _getCollection_options.fields) || record.fields || [];
    const currentCollections = (0, external_react_namespaceObject.useMemo)(()=>collections.map((v)=>({
                label: compile(v.title),
                value: v.name
            })), []);
    const getFieldOptions = (0, external_react_namespaceObject.useCallback)(()=>{
        const { availableFieldInterfaces } = getTemplate(record.template) || {};
        const { exclude, include } = availableFieldInterfaces || {};
        const optionArr = [];
        options.forEach((v)=>{
            if ('systemInfo' === v.key) optionArr.push({
                ...v,
                children: v.children.filter((v)=>{
                    if (v.hidden) return false;
                    if ('tableoid' !== v.value) return 'boolean' != typeof record[v.value] || record[v.value];
                    if (null == include ? void 0 : include.length) return include.includes(v.value);
                    return (null == database ? void 0 : database.dialect) === 'postgres';
                })
            });
            else {
                let children = [];
                if (null == include ? void 0 : include.length) include.forEach((k)=>{
                    var _v_children;
                    const field = null == v ? void 0 : null === (_v_children = v.children) || void 0 === _v_children ? void 0 : _v_children.find((h)=>[
                            k,
                            k.interface
                        ].includes(h.name));
                    field && children.push({
                        ...field,
                        targetScope: null == k ? void 0 : k.targetScope
                    });
                });
                else if (null == exclude ? void 0 : exclude.length) {
                    var _v_children;
                    children = null == v ? void 0 : null === (_v_children = v.children) || void 0 === _v_children ? void 0 : _v_children.filter((v)=>!exclude.includes(v.name));
                } else children = null == v ? void 0 : v.children;
                (null == children ? void 0 : children.length) && optionArr.push({
                    ...v,
                    children
                });
            }
        });
        return optionArr;
    }, [
        getTemplate,
        record
    ]);
    const items = (0, external_react_namespaceObject.useMemo)(()=>getFieldOptions().map((option)=>{
            var _option_children;
            if ((null == option ? void 0 : null === (_option_children = option.children) || void 0 === _option_children ? void 0 : _option_children.length) === 0) return null;
            if ('view' === record.template) return {
                type: 'group',
                label: compile(option.label),
                title: compile(option.label),
                key: option.label,
                children: option.children.filter((child)=>[
                        'm2o',
                        'custom',
                        'm2m'
                    ].includes(child.name)).map((child)=>({
                        label: compile(child.title),
                        title: compile(child.title),
                        key: child.name,
                        dataTargetScope: child.targetScope
                    }))
            };
            return {
                type: 'group',
                label: compile(option.label),
                title: compile(option.label),
                key: option.label,
                children: null == option ? void 0 : option.children.filter((child)=>![
                        'o2o',
                        'subTable',
                        'linkTo'
                    ].includes(child.name)).map((child)=>({
                        label: compile(child.title),
                        title: compile(child.title),
                        key: child.name,
                        dataTargetScope: child.targetScope
                    }))
            };
        }).filter((v)=>{
            var _v_children;
            return null == v ? void 0 : null === (_v_children = v.children) || void 0 === _v_children ? void 0 : _v_children.length;
        }), [
        getFieldOptions
    ]);
    const menu = (0, external_react_namespaceObject.useMemo)(()=>({
            style: {
                maxHeight: '60vh',
                overflow: 'auto'
            },
            onClick: (e)=>{
                const targetScope = e.item.props['data-targetScope'];
                targetScope && setTargetScope(targetScope);
                const schema = getSchema(getInterface(e.key), record, compile);
                if (schema) {
                    setSchema(schema);
                    setVisible(true);
                }
            },
            items
        }), [
        getInterface,
        items,
        record
    ]);
    const scopeKeyOptions = (0, external_react_namespaceObject.useMemo)(()=>fields.filter((v)=>[
                'string',
                'bigInt',
                'integer'
            ].includes(v.type)).map((k)=>{
            var _k_uiSchema;
            return {
                value: k.name,
                label: compile(null === (_k_uiSchema = k.uiSchema) || void 0 === _k_uiSchema ? void 0 : _k_uiSchema.title)
            };
        }), [
        null == fields ? void 0 : fields.length
    ]);
    return 'sql' !== record.template && /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(external_record_provider_index_js_namespaceObject.RecordProvider, {
        record: record,
        children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)(external_schema_component_index_js_namespaceObject.ActionContextProvider, {
            value: {
                visible,
                setVisible
            },
            children: [
                /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(external_antd_namespaceObject.Dropdown, {
                    getPopupContainer: getContainer,
                    trigger: trigger,
                    align: align,
                    menu: menu,
                    children: children || /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(external_antd_namespaceObject.Button, {
                        icon: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(icons_namespaceObject.PlusOutlined, {}),
                        type: 'primary',
                        children: t('Add field')
                    })
                }),
                /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(external_schema_component_index_js_namespaceObject.SchemaComponent, {
                    schema: schema,
                    components: {
                        ...external_components_index_js_namespaceObject,
                        ArrayTable: components_namespaceObject.ArrayTable
                    },
                    scope: {
                        getContainer,
                        useCancelAction: external_action_hooks_js_namespaceObject.useCancelAction,
                        createOnly: true,
                        isOverride: false,
                        override: false,
                        useCreateCollectionField,
                        record,
                        showReverseFieldConfig: true,
                        targetScope,
                        collections: currentCollections,
                        isDialect,
                        disabledJSONB: false,
                        scopeKeyOptions,
                        createMainOnly: true,
                        ...scope
                    }
                })
            ]
        })
    });
};
var __webpack_export_target__ = exports;
for(var __webpack_i__ in __webpack_exports__)__webpack_export_target__[__webpack_i__] = __webpack_exports__[__webpack_i__];
if (__webpack_exports__.__esModule) Object.defineProperty(__webpack_export_target__, '__esModule', {
    value: true
});
