"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__, {
    useSyncFromForm: ()=>useSyncFromForm
});
const external_react_namespaceObject = require("react");
var external_react_default = /*#__PURE__*/ __webpack_require__.n(external_react_namespaceObject);
const components_namespaceObject = require("@tachybase/components");
const schema_namespaceObject = require("@tachybase/schema");
const external_antd_namespaceObject = require("antd");
const external_lru_cache_namespaceObject = require("lru-cache");
var external_lru_cache_default = /*#__PURE__*/ __webpack_require__.n(external_lru_cache_namespaceObject);
const external_react_i18next_namespaceObject = require("react-i18next");
const index_js_namespaceObject = require("../../block-provider/hooks/index.js");
const external_collection_manager_index_js_namespaceObject = require("../../collection-manager/index.js");
const external_schema_component_index_js_namespaceObject = require("../../schema-component/index.js");
const useCollectionState_js_namespaceObject = require("./hooks/useCollectionState.js");
const external_TreeLabel_js_namespaceObject = require("./TreeLabel.js");
const useSyncFromForm = (fieldSchema, collection, callBack)=>{
    const { getCollectionJoinField, getCollectionFields } = (0, external_collection_manager_index_js_namespaceObject.useCollectionManager_deprecated)();
    const { message } = external_antd_namespaceObject.App.useApp();
    const array = components_namespaceObject.ArrayBase.useArray();
    const index = components_namespaceObject.ArrayBase.useIndex();
    const record = components_namespaceObject.ArrayBase.useRecord();
    const compile = (0, external_schema_component_index_js_namespaceObject.useCompile)();
    const { t } = (0, external_react_i18next_namespaceObject.useTranslation)();
    const from = (0, schema_namespaceObject.useForm)();
    const traverseFields = ((cache)=>(collectionName, param, formData)=>{
            let { exclude = [], depth = 0, maxDepth, prefix = '', disabled = false } = param;
            const cacheKey = "".concat(collectionName, "-").concat(exclude.join(','), "-").concat(depth, "-").concat(maxDepth, "-").concat(prefix);
            const cachedResult = cache.get(cacheKey);
            if (cachedResult) return cachedResult;
            if (depth > maxDepth) return [];
            const result = getCollectionFields(collectionName).map((field)=>{
                var _field_uiSchema;
                if (exclude.includes(field.name)) return;
                if (!field.interface) return;
                if ([
                    'sort',
                    'password',
                    'sequence'
                ].includes(field.type)) return;
                const node = {
                    type: 'duplicate',
                    tag: compile(null === (_field_uiSchema = field.uiSchema) || void 0 === _field_uiSchema ? void 0 : _field_uiSchema.title) || field.name
                };
                const option = {
                    ...node,
                    title: /*#__PURE__*/ external_react_default().createElement(external_TreeLabel_js_namespaceObject.TreeNode, node),
                    key: prefix ? "".concat(prefix, ".").concat(field.name) : field.name,
                    isLeaf: true,
                    field,
                    disabled
                };
                const tatgetFormField = formData.find((v)=>v.name === option.key);
                if ([
                    'belongsTo',
                    'belongsToMany'
                ].includes(field.type) && (!tatgetFormField || [
                    'Select',
                    'Picker'
                ].includes(null == tatgetFormField ? void 0 : tatgetFormField.fieldMode))) {
                    node['type'] = 'reference';
                    option['type'] = 'reference';
                    option['title'] = /*#__PURE__*/ external_react_default().createElement(external_TreeLabel_js_namespaceObject.TreeNode, {
                        ...node,
                        type: 'reference'
                    });
                    option.isLeaf = false;
                    option['children'] = traverseAssociations(field.target, {
                        depth: depth + 1,
                        maxDepth,
                        prefix: option.key,
                        exclude: useCollectionState_js_namespaceObject.systemKeys
                    });
                } else if ([
                    'hasOne',
                    'hasMany'
                ].includes(field.type) || [
                    'Nester',
                    'SubTable'
                ].includes(null == tatgetFormField ? void 0 : tatgetFormField.fieldMode)) {
                    let childrenDisabled = false;
                    if ([
                        'hasOne',
                        'hasMany'
                    ].includes(field.type) && [
                        'Select',
                        'Picker'
                    ].includes(null == tatgetFormField ? void 0 : tatgetFormField.fieldMode)) childrenDisabled = true;
                    option.disabled = true;
                    option.isLeaf = false;
                    option['children'] = traverseFields(field.target, {
                        depth: depth + 1,
                        maxDepth,
                        prefix: option.key,
                        exclude: [
                            'id',
                            ...useCollectionState_js_namespaceObject.systemKeys
                        ],
                        disabled: childrenDisabled
                    }, formData);
                }
                return option;
            }).filter(Boolean);
            cache.set(cacheKey, result);
            return result;
        })(new (external_lru_cache_default())({
        max: 100
    }));
    const traverseAssociations = ((cache)=>(collectionName, param)=>{
            let { prefix, maxDepth, depth = 0, exclude = [] } = param;
            const cacheKey = "".concat(collectionName, "-").concat(exclude.join(','), "-").concat(depth, "-").concat(maxDepth, "-").concat(prefix);
            const cachedResult = cache.get(cacheKey);
            if (cachedResult) return cachedResult;
            if (depth > maxDepth) return [];
            const result = getCollectionFields(collectionName).map((field)=>{
                var _field_uiSchema, _field_uiSchema1;
                if (!field.target || !field.interface) return;
                if (exclude.includes(field.name)) return;
                const option = {
                    type: 'preloading',
                    tag: compile(null === (_field_uiSchema = field.uiSchema) || void 0 === _field_uiSchema ? void 0 : _field_uiSchema.title) || field.name
                };
                const value = prefix ? "".concat(prefix, ".").concat(field.name) : field.name;
                return {
                    type: 'preloading',
                    tag: compile(null === (_field_uiSchema1 = field.uiSchema) || void 0 === _field_uiSchema1 ? void 0 : _field_uiSchema1.title) || field.name,
                    title: /*#__PURE__*/ external_react_default().createElement(external_TreeLabel_js_namespaceObject.TreeNode, option),
                    key: value,
                    isLeaf: false,
                    field,
                    children: traverseAssociations(field.target, {
                        prefix: value,
                        depth: depth + 1,
                        maxDepth,
                        exclude
                    })
                };
            }).filter(Boolean);
            cache.set(cacheKey, result);
            return result;
        })(new (external_lru_cache_default())({
        max: 100
    }));
    const getEnableFieldTree = (0, external_react_namespaceObject.useCallback)((collectionName, formData)=>{
        if (!collectionName) return [];
        try {
            return traverseFields(collectionName, {
                exclude: [
                    'id',
                    ...useCollectionState_js_namespaceObject.systemKeys
                ],
                maxDepth: 1,
                disabled: false
            }, formData);
        } catch (error) {
            console.error(error);
            return [];
        }
    }, []);
    return {
        async run () {
            const formData = new Set([]);
            const selectFields = new Set([]);
            const getAssociationAppends = (schema, str)=>{
                var _schema_reduceProperties;
                null == schema || null === (_schema_reduceProperties = schema.reduceProperties) || void 0 === _schema_reduceProperties || _schema_reduceProperties.call(schema, (pre, s)=>{
                    var _s_xcomponentprops;
                    const prefix = pre || str;
                    const collectionfield = s['x-collection-field'] && getCollectionJoinField(s['x-collection-field']);
                    const isAssociationSubfield = s.name.includes('.');
                    const isAssociationField = collectionfield && [
                        'hasOne',
                        'hasMany',
                        'belongsTo',
                        'belongsToMany'
                    ].includes(collectionfield.type);
                    const fieldPath = !isAssociationField && isAssociationSubfield ? (0, index_js_namespaceObject.getAssociationPath)(s.name) : s.name;
                    const path = '' !== prefix && prefix ? prefix + '.' + fieldPath : fieldPath;
                    if (collectionfield && !([
                        'hasOne',
                        'hasMany'
                    ].includes(collectionfield.type) || [
                        'SubForm',
                        'Nester'
                    ].includes(null === (_s_xcomponentprops = s['x-component-props']) || void 0 === _s_xcomponentprops ? void 0 : _s_xcomponentprops.mode))) selectFields.add(path);
                    if (collectionfield && (isAssociationField || isAssociationSubfield) && 'TableField' !== s['x-component']) {
                        var _s_xcomponentprops1, _s_xcomponentprops2;
                        formData.add({
                            name: path,
                            fieldMode: (null === (_s_xcomponentprops1 = s['x-component-props']) || void 0 === _s_xcomponentprops1 ? void 0 : _s_xcomponentprops1['mode']) || 'Select'
                        });
                        if ([
                            'Nester',
                            'SubTable'
                        ].includes(null === (_s_xcomponentprops2 = s['x-component-props']) || void 0 === _s_xcomponentprops2 ? void 0 : _s_xcomponentprops2.mode)) {
                            const bufPrefix = prefix && '' !== prefix ? prefix + '.' + s.name : s.name;
                            getAssociationAppends(s, bufPrefix);
                        }
                    } else if (![
                        'ActionBar',
                        'Action',
                        'Action.Link',
                        'Action.Modal',
                        'Selector',
                        'Viewer',
                        'AddNewer',
                        'AssociationField.Selector',
                        'AssociationField.AddNewer',
                        'TableField'
                    ].includes(s['x-component'])) getAssociationAppends(s, str);
                }, str);
            };
            getAssociationAppends(fieldSchema, '');
            const treeData = getEnableFieldTree((null == record ? void 0 : record.collection) || collection, [
                ...formData
            ]);
            if (callBack) callBack(treeData, [
                ...selectFields
            ], from);
            else {
                var _array_field;
                null == array || array.field.form.query("fieldReaction.items.".concat(index, ".layout.fields")).take((f)=>{
                    f.componentProps.treeData = [];
                    setTimeout(()=>f.componentProps.treeData = treeData);
                });
                null == array || array.field.value.splice(index, 1, {
                    ...null == array ? void 0 : null === (_array_field = array.field) || void 0 === _array_field ? void 0 : _array_field.value[index],
                    fields: [
                        ...selectFields
                    ],
                    treeData: treeData
                });
            }
            message.success(t('Sync successfully'));
        }
    };
};
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
});
