import * as __WEBPACK_EXTERNAL_MODULE__tachybase_schema__ from "@tachybase/schema";
import * as __WEBPACK_EXTERNAL_MODULE_flat__ from "flat";
import * as __WEBPACK_EXTERNAL_MODULE_lodash__ from "lodash";
import * as __WEBPACK_EXTERNAL_MODULE_react_i18next__ from "react-i18next";
import * as __WEBPACK_EXTERNAL_MODULE__block_provider_index_mjs__ from "../../../block-provider/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__collection_manager_index_mjs__ from "../../../collection-manager/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__filter_provider_utils_mjs__ from "../../../filter-provider/utils.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__modules_blocks_data_blocks_details_multi_setDataLoadingModeSettingsItem_mjs__ from "../../../modules/blocks/data-blocks/details-multi/setDataLoadingModeSettingsItem.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__utils_mjs__ from "./utils.mjs";
const useGetFilterOptions = ()=>{
    const { getCollectionFields } = (0, __WEBPACK_EXTERNAL_MODULE__collection_manager_index_mjs__.useCollectionManager_deprecated)();
    const getFilterFieldOptions = useGetFilterFieldOptions();
    return (collectionName, dataSource)=>{
        const fields = getCollectionFields(collectionName, dataSource);
        const options = getFilterFieldOptions(fields);
        return options;
    };
};
const useFilterOptions = (collectionName)=>{
    const { getCollectionFields } = (0, __WEBPACK_EXTERNAL_MODULE__collection_manager_index_mjs__.useCollectionManager_deprecated)();
    const fields = getCollectionFields(collectionName);
    const options = useFilterFieldOptions(fields);
    return options;
};
const useGetFilterFieldOptions = ()=>{
    var _fieldSchema_xcomponentprops;
    const fieldSchema = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useFieldSchema)();
    const nonfilterable = (null == fieldSchema ? void 0 : null === (_fieldSchema_xcomponentprops = fieldSchema['x-component-props']) || void 0 === _fieldSchema_xcomponentprops ? void 0 : _fieldSchema_xcomponentprops.nonfilterable) || [];
    const { getCollectionFields, getInterface } = (0, __WEBPACK_EXTERNAL_MODULE__collection_manager_index_mjs__.useCollectionManager_deprecated)();
    const field2option = (field, depth)=>{
        var _field_uiSchema, _operators_filter;
        if (nonfilterable.length && 1 === depth && nonfilterable.includes(field.name)) return;
        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,
            type: field.type,
            target: field.target,
            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,
            interface: field.interface,
            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))) || []
        };
        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;
    };
    return (fields)=>getOptions(fields, 1);
};
const useFilterFieldOptions = (fields)=>{
    var _fieldSchema_xcomponentprops;
    const fieldSchema = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useFieldSchema)();
    const nonfilterable = (null == fieldSchema ? void 0 : null === (_fieldSchema_xcomponentprops = fieldSchema['x-component-props']) || void 0 === _fieldSchema_xcomponentprops ? void 0 : _fieldSchema_xcomponentprops.nonfilterable) || [];
    const { getCollectionFields, getInterface } = (0, __WEBPACK_EXTERNAL_MODULE__collection_manager_index_mjs__.useCollectionManager_deprecated)();
    const field2option = (field, depth)=>{
        var _field_uiSchema, _operators_filter;
        if (nonfilterable.length && 1 === depth && nonfilterable.includes(field.name)) return;
        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,
            type: field.type,
            target: field.target,
            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))) || []
        };
        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;
    };
    return getOptions(fields, 1);
};
const isEmpty = (obj)=>Array.isArray(obj) && 0 === obj.length || obj && 0 === Object.keys(obj).length && Object.getPrototypeOf(obj) === Object.prototype;
const getCustomCondition = function(filter, fieldSchema) {
    let customFlat = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : __WEBPACK_EXTERNAL_MODULE_flat__["default"];
    var _filterSchema_$and, _filterSchema_$or;
    const filterSchema = fieldSchema ? fieldSchema['x-filter-rules'] : '';
    const filterSchemaItem = customFlat(filterSchema || '');
    const items = customFlat(filter || {});
    const isCustomFilter = (null == filterSchema ? void 0 : null === (_filterSchema_$and = filterSchema.$and) || void 0 === _filterSchema_$and ? void 0 : _filterSchema_$and.length) || (null == filterSchema ? void 0 : null === (_filterSchema_$or = filterSchema.$or) || void 0 === _filterSchema_$or ? void 0 : _filterSchema_$or.length);
    const isFilterCustom = !!isCustomFilter && (0, __WEBPACK_EXTERNAL_MODULE__utils_mjs__.hasDuplicateKeys)(items, filterSchemaItem);
    if (isFilterCustom) return customFlat.unflatten(items);
    if (!isCustomFilter) return customFlat.unflatten({});
    {
        var _flatFieldSchema_$and, _flatFieldSchema_$or;
        for(const filterKey in filterSchemaItem){
            var _filterSchemaItem_filterKey;
            const match = null === (_filterSchemaItem_filterKey = filterSchemaItem[filterKey]) || void 0 === _filterSchemaItem_filterKey ? void 0 : _filterSchemaItem_filterKey.slice(11, -2);
            const collection = null == match ? void 0 : match.split('.')[0];
            const filterItems = Object.keys(items).filter((item)=>item.includes(collection));
            if (filterItems.length > 1) filterSchemaItem[filterKey] = filterItems.map((key)=>items[key]);
            else filterSchemaItem[filterKey] = items[filterItems[0]];
        }
        for(const item in filterSchemaItem)if (!filterSchemaItem[item] || filterSchemaItem[item].includes('$nFilter')) delete filterSchemaItem[item];
        const flatFieldSchema = customFlat.unflatten(filterSchemaItem);
        flatFieldSchema['$and'] = null == flatFieldSchema ? void 0 : null === (_flatFieldSchema_$and = flatFieldSchema['$and']) || void 0 === _flatFieldSchema_$and ? void 0 : _flatFieldSchema_$and.filter(Boolean);
        flatFieldSchema['$or'] = null == flatFieldSchema ? void 0 : null === (_flatFieldSchema_$or = flatFieldSchema['$or']) || void 0 === _flatFieldSchema_$or ? void 0 : _flatFieldSchema_$or.filter(Boolean);
        return flatFieldSchema;
    }
};
const removeNullCondition = function(filter) {
    let customFlat = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : __WEBPACK_EXTERNAL_MODULE_flat__["default"];
    const items = customFlat(filter || {});
    const values = {};
    for(const key in items){
        const value = items[key];
        if (null != value && !isEmpty(value)) values[key] = value;
    }
    return customFlat.unflatten(values);
};
const useFilterActionProps = ()=>{
    const { name } = (0, __WEBPACK_EXTERNAL_MODULE__collection_manager_index_mjs__.useCollection_deprecated)();
    const options = useFilterOptions(name);
    const { service, props } = (0, __WEBPACK_EXTERNAL_MODULE__block_provider_index_mjs__.useBlockRequestContext)();
    return useFilterFieldProps({
        options,
        service,
        params: null == props ? void 0 : props.params
    });
};
const useFilterFieldProps = (param)=>{
    let { options, service, params } = param;
    const { t } = (0, __WEBPACK_EXTERNAL_MODULE_react_i18next__.useTranslation)();
    const field = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useField)();
    const dataLoadingMode = (0, __WEBPACK_EXTERNAL_MODULE__modules_blocks_data_blocks_details_multi_setDataLoadingModeSettingsItem_mjs__.useDataLoadingMode)();
    return {
        options,
        onSubmit (values) {
            var _service_params_, _service_params, _service_params1;
            const defaultFilter = params.filter;
            const filter = removeNullCondition(null == values ? void 0 : values.filter);
            if ('manual' === dataLoadingMode && __WEBPACK_EXTERNAL_MODULE_lodash__["default"].isEmpty(filter)) return service.mutate(void 0);
            const filters = (null === (_service_params = service.params) || void 0 === _service_params ? void 0 : null === (_service_params_ = _service_params[1]) || void 0 === _service_params_ ? void 0 : _service_params_.filters) || {};
            filters["filterAction"] = filter;
            service.run({
                ...null === (_service_params1 = service.params) || void 0 === _service_params1 ? void 0 : _service_params1[0],
                page: 1,
                filter: (0, __WEBPACK_EXTERNAL_MODULE__filter_provider_utils_mjs__.mergeFilter)([
                    ...Object.values(filters),
                    defaultFilter
                ])
            }, {
                filters
            });
            const items = (null == filter ? void 0 : filter.$and) || (null == filter ? void 0 : filter.$or);
            if (null == items ? void 0 : items.length) field.title = t('{{count}} filter items', {
                count: (null == items ? void 0 : items.length) || 0
            });
            else field.title = t('Filter');
        },
        onReset () {
            var _service_params_, _service_params, _service_params1;
            const filter = params.filter;
            const filters = (null === (_service_params = service.params) || void 0 === _service_params ? void 0 : null === (_service_params_ = _service_params[1]) || void 0 === _service_params_ ? void 0 : _service_params_.filters) || {};
            delete filters["filterAction"];
            const newParams = [
                {
                    ...null === (_service_params1 = service.params) || void 0 === _service_params1 ? void 0 : _service_params1[0],
                    filter: (0, __WEBPACK_EXTERNAL_MODULE__filter_provider_utils_mjs__.mergeFilter)([
                        ...Object.values(filters),
                        filter
                    ]),
                    page: 1
                },
                {
                    filters
                }
            ];
            field.title = t('Filter');
            if ('manual' === dataLoadingMode) {
                service.params = newParams;
                return service.mutate(void 0);
            }
            service.run(...newParams);
        }
    };
};
export { getCustomCondition, removeNullCondition, useFilterActionProps, useFilterFieldOptions, useFilterFieldProps, useFilterOptions, useGetFilterFieldOptions, useGetFilterOptions };
