"use strict";
var __webpack_require__ = {};
(()=>{
    __webpack_require__.n = (module)=>{
        var getter = module && module.__esModule ? ()=>module['default'] : ()=>module;
        __webpack_require__.d(getter, {
            a: getter
        });
        return getter;
    };
})();
(()=>{
    __webpack_require__.d = (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 = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
})();
(()=>{
    __webpack_require__.r = (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__, {
    mergeFilter: ()=>mergeFilter,
    transformToFilter: ()=>transformToFilter,
    isSameCollection: ()=>isSameCollection,
    getSupportFieldsByForeignKey: ()=>getSupportFieldsByForeignKey,
    FilterBlockType: ()=>utils_FilterBlockType,
    getSupportFieldsByAssociation: ()=>getSupportFieldsByAssociation,
    isAssocField: ()=>isAssocField,
    useAssociatedFields: ()=>useAssociatedFields,
    isInFilterFormBlock: ()=>isInFilterFormBlock,
    useFilterAPI: ()=>useFilterAPI,
    useSupportedBlocks: ()=>useSupportedBlocks
});
const external_react_namespaceObject = require("react");
const schema_namespaceObject = require("@tachybase/schema");
const client_namespaceObject = require("@tego/client");
const external_dayjs_namespaceObject = require("dayjs");
var external_dayjs_default = /*#__PURE__*/ __webpack_require__.n(external_dayjs_namespaceObject);
const external_lodash_namespaceObject = require("lodash");
var external_lodash_default = /*#__PURE__*/ __webpack_require__.n(external_lodash_namespaceObject);
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 SchemaSettingOptions_js_namespaceObject = require("../schema-component/antd/form-item/SchemaSettingOptions.js");
const external_FilterProvider_js_namespaceObject = require("./FilterProvider.js");
var utils_FilterBlockType = /*#__PURE__*/ function(FilterBlockType) {
    FilterBlockType[FilterBlockType["FORM"] = 0] = "FORM";
    FilterBlockType[FilterBlockType["TABLE"] = 1] = "TABLE";
    FilterBlockType[FilterBlockType["TREE"] = 2] = "TREE";
    FilterBlockType[FilterBlockType["COLLAPSE"] = 3] = "COLLAPSE";
    return FilterBlockType;
}({});
const mergeFilter = function(filters) {
    let op = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : '$and';
    const items = filters.filter((f)=>{
        if (f && 'object' == typeof f && !Array.isArray(f)) return Object.values(f).filter((v)=>void 0 !== v).length;
    });
    if (0 === items.length) return {};
    if (1 === items.length) return items[0];
    return {
        [op]: items
    };
};
const getSupportFieldsByAssociation = (inheritCollectionsChain, block)=>{
    var _block_associatedFields;
    return null == (_block_associatedFields = block.associatedFields) ? void 0 : _block_associatedFields.filter((field)=>null == inheritCollectionsChain ? void 0 : inheritCollectionsChain.some((collectionName)=>collectionName === field.target));
};
const getSupportFieldsByForeignKey = (filterBlockCollection, block)=>{
    var _block_foreignKeyFields;
    return null == (_block_foreignKeyFields = block.foreignKeyFields) ? void 0 : _block_foreignKeyFields.filter((foreignKeyField)=>filterBlockCollection.fields.some((field)=>'belongsTo' !== field.type && field.foreignKey === foreignKeyField.name));
};
const useSupportedBlocks = (filterBlockType)=>{
    const { getDataBlocks } = (0, external_FilterProvider_js_namespaceObject.useFilterBlock)();
    const fieldSchema = (0, schema_namespaceObject.useFieldSchema)();
    const collection = (0, external_collection_manager_index_js_namespaceObject.useCollection_deprecated)();
    const { getAllCollectionsInheritChain } = (0, external_collection_manager_index_js_namespaceObject.useCollectionManager_deprecated)();
    if (0 === filterBlockType || 3 === filterBlockType) return getDataBlocks().filter((block)=>isSameCollection(block.collection, collection));
    if (1 === filterBlockType || 2 === filterBlockType) return getDataBlocks().filter((block)=>{
        var _getSupportFieldsByAssociation, _getSupportFieldsByForeignKey;
        return fieldSchema['x-uid'] !== block.uid && (isSameCollection(block.collection, collection) || (null == (_getSupportFieldsByAssociation = getSupportFieldsByAssociation(getAllCollectionsInheritChain(collection.name, collection.dataSource), block)) ? void 0 : _getSupportFieldsByAssociation.length) || (null == (_getSupportFieldsByForeignKey = getSupportFieldsByForeignKey(collection, block)) ? void 0 : _getSupportFieldsByForeignKey.length));
    });
};
const transformToFilter = (values, fieldSchema, getCollectionJoinField, collectionName)=>{
    const { operators } = (0, SchemaSettingOptions_js_namespaceObject.findFilterOperators)(fieldSchema);
    values = (0, client_namespaceObject.flatten)(values, {
        breakOn (param) {
            let { value, path } = param;
            if ([
                '$match',
                '$notMatch',
                '$anyOf',
                '$noneOf',
                '$childIn',
                '$childNotIn',
                '$dateBetween',
                '$in',
                '$notIn'
            ].includes(operators[path])) return true;
            const collectionField = getCollectionJoinField("".concat(collectionName, ".").concat(path));
            if (null == collectionField ? void 0 : collectionField.target) {
                if (Array.isArray(value)) return true;
                const targetKey = collectionField.targetKey || 'id';
                if (value && null != value[targetKey]) return true;
            }
            return false;
        }
    });
    const result = {
        $and: Object.keys(values).map((key)=>{
            const defKey = key;
            let value = external_lodash_default().get(values, key);
            const collectionField = getCollectionJoinField("".concat(collectionName, ".").concat(key));
            if (null == collectionField ? void 0 : collectionField.target) {
                value = (0, client_namespaceObject.getValuesByPath)(value, collectionField.targetKey || 'id');
                key = "".concat(key, ".").concat(collectionField.targetKey || 'id');
            }
            if (!value) return null;
            if ('$isTruly' === operators[key] || '$isFalsy' === operators[key]) {
                if ('true' === value) return {
                    [key]: {
                        $isTruly: true
                    }
                };
                else if ('false' === value) return {
                    [key]: {
                        $isFalsy: true
                    }
                };
            } else if ('$dateBetween' === operators[key]) {
                if (Array.isArray(value)) {
                    for(const index in value)if (value[index]) {
                        if ('string' != typeof value[index] && !(value[index] instanceof Date)) value[index] = external_dayjs_default()(value[index]).toISOString();
                    }
                }
            }
            return {
                [key]: {
                    [operators[key] || operators[defKey] || '$eq']: value
                }
            };
        }).filter(Boolean)
    };
    return result;
};
const useAssociatedFields = ()=>{
    const { fields } = (0, external_collection_manager_index_js_namespaceObject.useCollection_deprecated)();
    return fields.filter((field)=>isAssocField(field)) || [];
};
const isAssocField = (field)=>[
        'o2o',
        'oho',
        'obo',
        'm2o',
        'createdBy',
        'updatedBy',
        'o2m',
        'm2m',
        'linkTo',
        'chinaRegion'
    ].includes(null == field ? void 0 : field.interface);
const isSameCollection = (c1, c2)=>c1.name === c2.name && c1.dataSource === c2.dataSource;
const useFilterAPI = ()=>{
    const fieldSchema = (0, schema_namespaceObject.useFieldSchema)();
    const { getDataBlocks } = (0, external_FilterProvider_js_namespaceObject.useFilterBlock)();
    const { targets, uid } = (0, index_js_namespaceObject.findFilterTargets)(fieldSchema);
    const dataBlocks = getDataBlocks();
    const [isConnected, setIsConnected] = (0, external_react_namespaceObject.useState)(()=>targets && targets.some((target)=>dataBlocks.some((dataBlock)=>dataBlock.uid === target.uid)));
    const targetsKeys = Object.keys(targets || {});
    (0, external_react_namespaceObject.useEffect)(()=>{
        setIsConnected(targets && targets.some((target)=>dataBlocks.some((dataBlock)=>dataBlock.uid === target.uid)));
    }, [
        targetsKeys.length,
        dataBlocks
    ]);
    const doFilter = (0, external_react_namespaceObject.useCallback)(function(value) {
        let field = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : 'id', operator = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : '$eq';
        dataBlocks.forEach((block)=>{
            var _block_service_params, _block_service_params_, _block_service_params1;
            const target = targets.find((target)=>target.uid === block.uid);
            if (!target) return;
            if (external_lodash_default().isFunction(field)) field = field(target);
            if (external_lodash_default().isFunction(operator)) operator = operator(target);
            const param = (null == (_block_service_params = block.service.params) ? void 0 : _block_service_params[0]) || {};
            const storedFilter = (null == (_block_service_params1 = block.service.params) ? void 0 : null == (_block_service_params_ = _block_service_params1[1]) ? void 0 : _block_service_params_.filters) || {};
            if (void 0 !== value) storedFilter[uid] = {
                $and: [
                    {
                        [field]: {
                            [operator]: value
                        }
                    }
                ]
            };
            else delete storedFilter[uid];
            const mergedFilter = mergeFilter([
                ...Object.values(storedFilter).map((filter)=>(0, external_schema_component_index_js_namespaceObject.removeNullCondition)(filter)),
                block.defaultFilter
            ]);
            block.doFilter({
                ...param,
                page: 1,
                filter: mergedFilter
            }, {
                filters: storedFilter
            });
        });
    }, [
        dataBlocks
    ]);
    return {
        isConnected,
        doFilter
    };
};
const isInFilterFormBlock = (fieldSchema)=>{
    while(fieldSchema){
        if (fieldSchema['x-filter-targets']) return 'FilterFormBlockProvider' === fieldSchema['x-decorator'];
        fieldSchema = fieldSchema.parent;
    }
    return false;
};
exports.FilterBlockType = __webpack_exports__.FilterBlockType;
exports.getSupportFieldsByAssociation = __webpack_exports__.getSupportFieldsByAssociation;
exports.getSupportFieldsByForeignKey = __webpack_exports__.getSupportFieldsByForeignKey;
exports.isAssocField = __webpack_exports__.isAssocField;
exports.isInFilterFormBlock = __webpack_exports__.isInFilterFormBlock;
exports.isSameCollection = __webpack_exports__.isSameCollection;
exports.mergeFilter = __webpack_exports__.mergeFilter;
exports.transformToFilter = __webpack_exports__.transformToFilter;
exports.useAssociatedFields = __webpack_exports__.useAssociatedFields;
exports.useFilterAPI = __webpack_exports__.useFilterAPI;
exports.useSupportedBlocks = __webpack_exports__.useSupportedBlocks;
for(var __webpack_i__ in __webpack_exports__)if (-1 === [
    "FilterBlockType",
    "getSupportFieldsByAssociation",
    "getSupportFieldsByForeignKey",
    "isAssocField",
    "isInFilterFormBlock",
    "isSameCollection",
    "mergeFilter",
    "transformToFilter",
    "useAssociatedFields",
    "useFilterAPI",
    "useSupportedBlocks"
].indexOf(__webpack_i__)) exports[__webpack_i__] = __webpack_exports__[__webpack_i__];
Object.defineProperty(exports, '__esModule', {
    value: true
});
