import * as __WEBPACK_EXTERNAL_MODULE_react__ from "react";
import * as __WEBPACK_EXTERNAL_MODULE__tachybase_schema__ from "@tachybase/schema";
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__TreeLabel_mjs__ from "../TreeLabel.mjs";
const useCollectionState_rslib_entry_systemKeys = [
    'sort',
    'createdById',
    'createdBy',
    'createdAt',
    'updatedById',
    'updatedBy',
    'updatedAt',
    'password',
    'sequence'
];
const useCollectionState = (currentCollectionName)=>{
    const { getCollectionFields, getAllCollectionsInheritChain, getCollection, getInterface } = (0, __WEBPACK_EXTERNAL_MODULE__collection_manager_index_mjs__.useCollectionManager_deprecated)();
    const [collectionList] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)(getCollectionList);
    const compile = (0, __WEBPACK_EXTERNAL_MODULE__schema_component_index_mjs__.useCompile)();
    const templateField = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useField)();
    function getCollectionList() {
        const collections = getAllCollectionsInheritChain(currentCollectionName) || [];
        return collections.map((name)=>{
            var _getCollection;
            return {
                label: null === (_getCollection = getCollection(name)) || void 0 === _getCollection ? void 0 : _getCollection.title,
                value: name
            };
        });
    }
    const traverseFields = (collectionName, param)=>{
        let { exclude = [], depth = 0, maxDepth, prefix = '' } = param;
        if (depth > maxDepth) return [];
        return 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,
                role: 'button',
                title: __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
            };
            if ([
                'belongsTo',
                'belongsToMany'
            ].includes(field.type)) {
                node['type'] = 'reference';
                option['type'] = 'reference';
                option['title'] = __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: useCollectionState_rslib_entry_systemKeys
                });
            } else if ([
                'hasOne',
                'hasMany'
            ].includes(field.type)) {
                option.isLeaf = false;
                option['children'] = traverseFields(field.target, {
                    depth: depth + 1,
                    maxDepth,
                    prefix: option.key,
                    exclude: [
                        'id',
                        ...useCollectionState_rslib_entry_systemKeys
                    ]
                });
            }
            return option;
        }).filter(Boolean);
    };
    const traverseAssociations = (collectionName, param)=>{
        let { prefix, maxDepth, depth = 0, exclude = [] } = param;
        if (depth > maxDepth) return [];
        return getCollectionFields(collectionName).map((field)=>{
            var _field_uiSchema;
            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 {
                role: 'button',
                title: __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);
    };
    const parseTreeData = (data)=>data.map((v)=>({
                ...v,
                role: 'button',
                title: __WEBPACK_EXTERNAL_MODULE_react__["default"].createElement(__WEBPACK_EXTERNAL_MODULE__TreeLabel_mjs__.TreeNode, {
                    ...v,
                    type: v.type
                }),
                children: v.children ? parseTreeData(v.children) : null
            }));
    const getEnableFieldTree = (0, __WEBPACK_EXTERNAL_MODULE_react__.useCallback)((collectionName, field, treeData)=>{
        var _templateField_initialValue_items, _templateField_initialValue;
        const index = field.index;
        const targetTemplate = null === (_templateField_initialValue = templateField.initialValue) || void 0 === _templateField_initialValue ? void 0 : null === (_templateField_initialValue_items = _templateField_initialValue.items) || void 0 === _templateField_initialValue_items ? void 0 : _templateField_initialValue_items[index];
        if (!collectionName) return [];
        if ((null == targetTemplate ? void 0 : targetTemplate.treeData) || treeData) return parseTreeData(treeData || targetTemplate.treeData);
        try {
            return traverseFields(collectionName, {
                exclude: [
                    'id',
                    ...useCollectionState_rslib_entry_systemKeys
                ],
                maxDepth: 1
            });
        } catch (error) {
            console.error(error);
            return [];
        }
    }, []);
    const getOnLoadData = (0, __WEBPACK_EXTERNAL_MODULE_react__.useCallback)((fields)=>(node)=>new Promise((resolve)=>{
                if (node.children.length) {
                    node.children.forEach((child)=>{
                        loadChildren({
                            node: child,
                            traverseAssociations,
                            traverseFields,
                            systemKeys: useCollectionState_rslib_entry_systemKeys,
                            fields
                        });
                    });
                    return resolve(void 0);
                }
                loadChildren({
                    node,
                    traverseAssociations,
                    traverseFields,
                    systemKeys: useCollectionState_rslib_entry_systemKeys,
                    fields
                });
                resolve(void 0);
            }), []);
    const getOnCheck = (0, __WEBPACK_EXTERNAL_MODULE_react__.useCallback)((fields)=>(checkedKeys)=>{
            fields.value = checkedKeys;
        }, []);
    const getScopeDataSource = (resource)=>{
        const fields = getCollectionFields(resource);
        const field2option = (field, depth)=>{
            var _field_uiSchema, _operators_filter;
            if (!field.interface) return;
            const fieldInterface = getInterface(field.interface);
            if (!(null == fieldInterface ? void 0 : fieldInterface.filterable)) return;
            const { nested, children, operators } = fieldInterface.filterable;
            const option = {
                name: field.name,
                title: (null == field ? void 0 : null === (_field_uiSchema = field.uiSchema) || void 0 === _field_uiSchema ? void 0 : _field_uiSchema.title) || field.name,
                schema: null == field ? void 0 : field.uiSchema,
                operators: (null == operators ? void 0 : null === (_operators_filter = operators.filter) || void 0 === _operators_filter ? void 0 : _operators_filter.call(operators, (operator)=>!(null == operator ? void 0 : operator.visible) || operator.visible(field))) || [],
                interface: field.interface
            };
            if (field.target && depth > 2) return;
            if (depth > 2) return option;
            if (null == children ? void 0 : children.length) option['children'] = children;
            if (nested) {
                const targetFields = getCollectionFields(field.target);
                const options = getOptions(targetFields, depth + 1).filter(Boolean);
                option['children'] = option['children'] || [];
                option['children'].push(...options);
            }
            return option;
        };
        const getOptions = (fields, depth)=>{
            const options = [];
            fields.forEach((field)=>{
                const option = field2option(field, depth);
                if (option) options.push(option);
            });
            return options;
        };
        const options = getOptions(fields, 1);
        return options;
    };
    const useTitleFieldDataSource = (field)=>{
        const fieldPath = field.path.entire.replace('titleField', 'collection');
        const collectionName = field.query(fieldPath).get('value');
        const targetFields = getCollectionFields(collectionName);
        const options = targetFields.filter((field)=>{
            var _getInterface;
            return !field.isForeignKey && (null === (_getInterface = getInterface(field.interface)) || void 0 === _getInterface ? void 0 : _getInterface.titleUsable);
        }).map((field)=>{
            var _field_uiSchema;
            return {
                value: null == field ? void 0 : field.name,
                label: compile(null == field ? void 0 : null === (_field_uiSchema = field.uiSchema) || void 0 === _field_uiSchema ? void 0 : _field_uiSchema.title) || (null == field ? void 0 : field.name)
            };
        });
        field.dataSource = options;
    };
    return {
        collectionList,
        getEnableFieldTree,
        getOnLoadData,
        getOnCheck,
        getScopeDataSource,
        useTitleFieldDataSource
    };
};
function findNode(treeData, item) {
    const queue = [
        ...treeData
    ];
    while(queue.length){
        const node = queue.shift();
        if (node.key === item.key) return node;
        if (node.children) queue.push(...node.children);
    }
}
function loadChildren(param) {
    let { node, traverseAssociations, traverseFields, systemKeys, fields } = param;
    const activeNode = findNode(fields.dataSource || fields.componentProps.treeData, node);
    let children = [];
    if ([
        'belongsTo',
        'belongsToMany'
    ].includes(node.field.type) && (null == node ? void 0 : node.type) === 'reference') children = traverseAssociations(node.field.target, {
        exclude: systemKeys,
        prefix: node.key,
        maxDepth: 1
    });
    else if ([
        'hasOne',
        'hasMany'
    ].includes(node.field.type) || (null == node ? void 0 : node.type) === 'duplicate') children = traverseFields(node.field.target, {
        exclude: [
            'id',
            ...systemKeys
        ],
        prefix: node.key,
        maxDepth: 1
    });
    if (children.length) activeNode.children = children;
    else activeNode.isLeaf = true;
    return children;
}
export { useCollectionState_rslib_entry_systemKeys as systemKeys, useCollectionState };
