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_antd__ from "antd";
import * as __WEBPACK_EXTERNAL_MODULE_lru_cache__ from "lru-cache";
import * as __WEBPACK_EXTERNAL_MODULE_react_i18next__ from "react-i18next";
import * as __WEBPACK_EXTERNAL_MODULE__block_provider_hooks_index_mjs__ from "../../block-provider/hooks/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__collection_manager_index_mjs__ from "../../collection-manager/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__schema_component_index_mjs__ from "../../schema-component/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__hooks_useCollectionState_mjs__ from "./hooks/useCollectionState.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__TreeLabel_mjs__ from "./TreeLabel.mjs";
const useSyncFromForm = (fieldSchema, collection, callBack)=>{
    const { getCollectionJoinField, getCollectionFields } = (0, __WEBPACK_EXTERNAL_MODULE__collection_manager_index_mjs__.useCollectionManager_deprecated)();
    const { message } = __WEBPACK_EXTERNAL_MODULE_antd__.App.useApp();
    const array = __WEBPACK_EXTERNAL_MODULE__tachybase_components__.ArrayBase.useArray();
    const index = __WEBPACK_EXTERNAL_MODULE__tachybase_components__.ArrayBase.useIndex();
    const record = __WEBPACK_EXTERNAL_MODULE__tachybase_components__.ArrayBase.useRecord();
    const compile = (0, __WEBPACK_EXTERNAL_MODULE__schema_component_index_mjs__.useCompile)();
    const { t } = (0, __WEBPACK_EXTERNAL_MODULE_react_i18next__.useTranslation)();
    const from = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.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__*/ __WEBPACK_EXTERNAL_MODULE_react__["default"].createElement(__WEBPACK_EXTERNAL_MODULE__TreeLabel_mjs__.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__*/ __WEBPACK_EXTERNAL_MODULE_react__["default"].createElement(__WEBPACK_EXTERNAL_MODULE__TreeLabel_mjs__.TreeNode, {
                        ...node,
                        type: 'reference'
                    });
                    option.isLeaf = false;
                    option['children'] = traverseAssociations(field.target, {
                        depth: depth + 1,
                        maxDepth,
                        prefix: option.key,
                        exclude: __WEBPACK_EXTERNAL_MODULE__hooks_useCollectionState_mjs__.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',
                            ...__WEBPACK_EXTERNAL_MODULE__hooks_useCollectionState_mjs__.systemKeys
                        ],
                        disabled: childrenDisabled
                    }, formData);
                }
                return option;
            }).filter(Boolean);
            cache.set(cacheKey, result);
            return result;
        })(new __WEBPACK_EXTERNAL_MODULE_lru_cache__.LRUCache({
        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__*/ __WEBPACK_EXTERNAL_MODULE_react__["default"].createElement(__WEBPACK_EXTERNAL_MODULE__TreeLabel_mjs__.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 __WEBPACK_EXTERNAL_MODULE_lru_cache__.LRUCache({
        max: 100
    }));
    const getEnableFieldTree = (0, __WEBPACK_EXTERNAL_MODULE_react__.useCallback)((collectionName, formData)=>{
        if (!collectionName) return [];
        try {
            return traverseFields(collectionName, {
                exclude: [
                    'id',
                    ...__WEBPACK_EXTERNAL_MODULE__hooks_useCollectionState_mjs__.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, __WEBPACK_EXTERNAL_MODULE__block_provider_hooks_index_mjs__.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'));
        }
    };
};
export { useSyncFromForm };
