import * as __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__ from "react/jsx-runtime";
import * as __WEBPACK_EXTERNAL_MODULE_react__ from "react";
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__ant_design_icons__ from "@ant-design/icons";
import * as __WEBPACK_EXTERNAL_MODULE_antd__ from "antd";
import * as __WEBPACK_EXTERNAL_MODULE_lodash__ from "lodash";
import * as __WEBPACK_EXTERNAL_MODULE_react_i18next__ from "react-i18next";
import * as __WEBPACK_EXTERNAL_MODULE__api_client_index_mjs__ from "../../api-client/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__record_provider_index_mjs__ from "../../record-provider/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__schema_component_index_mjs__ from "../../schema-component/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__action_hooks_mjs__ from "../action-hooks.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__hooks_index_mjs__ from "../hooks/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__hooks_useDialect_mjs__ from "../hooks/useDialect.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__ResourceActionProvider_mjs__ from "../ResourceActionProvider.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__components_index_mjs__ from "./components/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__interfaces_mjs__ from "./interfaces.mjs";
const getSchema = (schema, record, compile)=>{
    if (!schema) return;
    const properties = (0, __WEBPACK_EXTERNAL_MODULE_lodash__.cloneDeep)(schema.properties);
    if (true === schema.hasDefaultValue) {
        var _schema_default;
        properties['defaultValue'] = (0, __WEBPACK_EXTERNAL_MODULE_lodash__.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, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.uid)()),
        ...(0, __WEBPACK_EXTERNAL_MODULE_lodash__.cloneDeep)(schema.default),
        interface: schema.name
    };
    if (initialValue.reverseField) initialValue.reverseField.name = "f_".concat((0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.uid)());
    return {
        type: 'object',
        properties: {
            [(0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.uid)()]: {
                type: 'void',
                'x-component': 'Action.Drawer',
                'x-component-props': {
                    getContainer: '{{ getContainer }}'
                },
                'x-decorator': 'Form',
                'x-decorator-props': {
                    useValues (options) {
                        return (0, __WEBPACK_EXTERNAL_MODULE__api_client_index_mjs__.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, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useForm)();
    return {
        getValues () {
            const values = (0, __WEBPACK_EXTERNAL_MODULE_lodash__.cloneDeep)(form.values);
            values.autoCreateReverseField || delete values.reverseField;
            delete values.autoCreateReverseField;
            return values;
        }
    };
};
const useCreateCollectionField = ()=>{
    const form = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useForm)();
    const { refreshCM } = (0, __WEBPACK_EXTERNAL_MODULE__hooks_index_mjs__.useCollectionManager_deprecated)();
    const ctx = (0, __WEBPACK_EXTERNAL_MODULE__schema_component_index_mjs__.useActionContext)();
    const { refresh } = (0, __WEBPACK_EXTERNAL_MODULE__ResourceActionProvider_mjs__.useResourceActionContext)();
    const { resource } = (0, __WEBPACK_EXTERNAL_MODULE__ResourceActionProvider_mjs__.useResourceContext)();
    const field = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useField)();
    return {
        async run () {
            await form.submit();
            field.data = field.data || {};
            field.data.loading = true;
            const values = (0, __WEBPACK_EXTERNAL_MODULE_lodash__.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, __WEBPACK_EXTERNAL_MODULE__record_provider_index_mjs__.useRecord)();
    return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.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, __WEBPACK_EXTERNAL_MODULE__hooks_index_mjs__.useCollectionManager_deprecated)();
    const [visible, setVisible] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)(false);
    const [targetScope, setTargetScope] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)();
    const [schema, setSchema] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)({});
    const compile = (0, __WEBPACK_EXTERNAL_MODULE__schema_component_index_mjs__.useCompile)();
    const { t } = (0, __WEBPACK_EXTERNAL_MODULE_react_i18next__.useTranslation)();
    const { isDialect } = (0, __WEBPACK_EXTERNAL_MODULE__hooks_useDialect_mjs__["default"])();
    const options = (0, __WEBPACK_EXTERNAL_MODULE__interfaces_mjs__.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, __WEBPACK_EXTERNAL_MODULE_react__.useMemo)(()=>collections.map((v)=>({
                label: compile(v.title),
                value: v.name
            })), []);
    const getFieldOptions = (0, __WEBPACK_EXTERNAL_MODULE_react__.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, __WEBPACK_EXTERNAL_MODULE_react__.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, __WEBPACK_EXTERNAL_MODULE_react__.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, __WEBPACK_EXTERNAL_MODULE_react__.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, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__record_provider_index_mjs__.RecordProvider, {
        record: record,
        children: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsxs)(__WEBPACK_EXTERNAL_MODULE__schema_component_index_mjs__.ActionContextProvider, {
            value: {
                visible,
                setVisible
            },
            children: [
                /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Dropdown, {
                    getPopupContainer: getContainer,
                    trigger: trigger,
                    align: align,
                    menu: menu,
                    children: children || /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Button, {
                        icon: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__ant_design_icons__.PlusOutlined, {}),
                        type: 'primary',
                        children: t('Add field')
                    })
                }),
                /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__schema_component_index_mjs__.SchemaComponent, {
                    schema: schema,
                    components: {
                        ...__WEBPACK_EXTERNAL_MODULE__components_index_mjs__,
                        ArrayTable: __WEBPACK_EXTERNAL_MODULE__tachybase_components__.ArrayTable
                    },
                    scope: {
                        getContainer,
                        useCancelAction: __WEBPACK_EXTERNAL_MODULE__action_hooks_mjs__.useCancelAction,
                        createOnly: true,
                        isOverride: false,
                        override: false,
                        useCreateCollectionField,
                        record,
                        showReverseFieldConfig: true,
                        targetScope,
                        collections: currentCollections,
                        isDialect,
                        disabledJSONB: false,
                        scopeKeyOptions,
                        createMainOnly: true,
                        ...scope
                    }
                })
            ]
        })
    });
};
export { AddCollectionField, AddFieldAction, useCollectionFieldFormValues };
