import * as __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__ from "react/jsx-runtime";
import * as __WEBPACK_EXTERNAL_MODULE_react__ from "react";
import * as __WEBPACK_EXTERNAL_MODULE__tachybase_schema__ from "@tachybase/schema";
import * as __WEBPACK_EXTERNAL_MODULE_lodash__ from "lodash";
import * as __WEBPACK_EXTERNAL_MODULE__application_hoc_withDynamicSchemaProps_mjs__ from "../application/hoc/withDynamicSchemaProps.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__collection_manager_index_mjs__ from "../collection-manager/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__data_source_collection_record_CollectionRecordProvider_mjs__ from "../data-source/collection-record/CollectionRecordProvider.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__filter_provider_index_mjs__ from "../filter-provider/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__filter_provider_utils_mjs__ from "../filter-provider/utils.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__record_provider_index_mjs__ from "../record-provider/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__schema_component_index_mjs__ from "../schema-component/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__BlockProvider_mjs__ from "./BlockProvider.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__hooks_index_mjs__ from "./hooks/index.mjs";
const TableSelectorContext = /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react__.createContext)({});
TableSelectorContext.displayName = 'TableSelectorContext';
const TableSelectorParamsContext = /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react__.createContext)({});
TableSelectorParamsContext.displayName = 'TableSelectorParamsContext';
const useTableSelectorParams = ()=>(0, __WEBPACK_EXTERNAL_MODULE_react__.useContext)(TableSelectorParamsContext);
const TableSelectorParamsProvider = (param)=>{
    let { params, children } = param;
    const parentParams = useTableSelectorParams();
    try {
        params.filter = (0, __WEBPACK_EXTERNAL_MODULE__filter_provider_utils_mjs__.mergeFilter)([
            parentParams.filter,
            params.filter
        ]);
        params = {
            ...parentParams,
            ...params
        };
    } catch (err) {
        console.error(err);
    }
    return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(TableSelectorParamsContext.Provider, {
        value: params,
        children: children
    });
};
const InternalTableSelectorProvider = (props)=>{
    const { params, rowKey, extraFilter } = props;
    const field = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useField)();
    const { resource, service } = (0, __WEBPACK_EXTERNAL_MODULE__BlockProvider_mjs__.useBlockRequestContext)();
    const [expandFlag, setExpandFlag] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)(false);
    const parentRecordData = (0, __WEBPACK_EXTERNAL_MODULE__data_source_collection_record_CollectionRecordProvider_mjs__.useCollectionParentRecordData)();
    return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__record_provider_index_mjs__.RecordProvider, {
        record: {},
        parent: parentRecordData,
        children: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(TableSelectorContext.Provider, {
            value: {
                field,
                service,
                resource,
                params,
                extraFilter,
                rowKey,
                expandFlag,
                setExpandFlag: ()=>{
                    setExpandFlag(!expandFlag);
                }
            },
            children: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__BlockProvider_mjs__.RenderChildrenWithAssociationFilter, {
                ...props
            })
        })
    });
};
const recursiveParent = (schema, component)=>schema['x-component'] === component ? schema : schema.parent ? recursiveParent(schema.parent, component) : null;
const useAssociationNames = (collection)=>{
    const { getCollectionFields } = (0, __WEBPACK_EXTERNAL_MODULE__collection_manager_index_mjs__.useCollectionManager_deprecated)();
    const collectionFields = getCollectionFields(collection);
    const associationFields = new Set();
    for (const collectionField of collectionFields)if (collectionField.target) {
        associationFields.add(collectionField.name);
        const fields = getCollectionFields(collectionField.target);
        for (const field of fields)if (field.target) associationFields.add("".concat(collectionField.name, ".").concat(field.name));
    }
    const fieldSchema = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useFieldSchema)();
    const tableSchema = fieldSchema.reduceProperties((buf, schema)=>{
        if ('TableV2.Selector' === schema['x-component']) return schema;
        return buf;
    }, new __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.Schema({}));
    return (0, __WEBPACK_EXTERNAL_MODULE_lodash__.uniq)(tableSchema.reduceProperties((buf, schema)=>{
        if ('TableV2.Column' === schema['x-component']) {
            const s = schema.reduceProperties((buf, s)=>{
                const [name] = s.name.split('.');
                if (s['x-collection-field'] && associationFields.has(name)) return s;
                return buf;
            }, null);
            if (s) {
                const [firstName] = s.name.split('.');
                if (associationFields.has(s.name)) buf.push(s.name);
                else if (associationFields.has(firstName)) buf.push(firstName);
            }
        }
        return buf;
    }, []));
};
const TableSelectorProvider = (0, __WEBPACK_EXTERNAL_MODULE__application_hoc_withDynamicSchemaProps_mjs__.withDynamicSchemaProps)((props)=>{
    const parentParams = useTableSelectorParams();
    const fieldSchema = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useFieldSchema)();
    const { getCollectionJoinField, getCollectionFields } = (0, __WEBPACK_EXTERNAL_MODULE__collection_manager_index_mjs__.useCollectionManager_deprecated)();
    const record = (0, __WEBPACK_EXTERNAL_MODULE__record_provider_index_mjs__.useRecord)();
    const { getCollection } = (0, __WEBPACK_EXTERNAL_MODULE__collection_manager_index_mjs__.useCollectionManager_deprecated)();
    const { treeTable } = (null == fieldSchema ? void 0 : fieldSchema['x-decorator-props']) || {};
    const collectionFieldSchema = recursiveParent(fieldSchema, 'CollectionField');
    const collectionField = getCollectionJoinField(null == collectionFieldSchema ? void 0 : collectionFieldSchema['x-collection-field']);
    const collection = getCollection(null == collectionField ? void 0 : collectionField.collectionName);
    const primaryKey = null == collection ? void 0 : collection.getPrimaryKey();
    const appends = useAssociationNames(props.collection);
    let params = {
        ...props.params
    };
    if (props.dragSort) params['sort'] = [
        'sort'
    ];
    if ((null == collectionField ? void 0 : collectionField.target) === (null == collectionField ? void 0 : collectionField.collectionName) && (null == collection ? void 0 : collection.tree) && false !== treeTable) {
        params['tree'] = true;
        if ('parent' === collectionFieldSchema.name) {
            var _params_filter;
            params.filter = {
                ...null !== (_params_filter = params.filter) && void 0 !== _params_filter ? _params_filter : {},
                id: record[primaryKey] && {
                    $ne: record[primaryKey]
                }
            };
        }
    }
    if (!Object.keys(params).includes('appends')) params['appends'] = appends;
    let extraFilter;
    if (collectionField) {
        if ([
            'oho',
            'o2m'
        ].includes(collectionField.interface) && !(0, __WEBPACK_EXTERNAL_MODULE__filter_provider_index_mjs__.isInFilterFormBlock)(fieldSchema)) extraFilter = (null == record ? void 0 : record[collectionField.sourceKey]) ? {
            $or: [
                {
                    [collectionField.foreignKey]: {
                        $is: null
                    }
                },
                {
                    [collectionField.foreignKey]: {
                        $eq: null == record ? void 0 : record[collectionField.sourceKey]
                    }
                }
            ]
        } : {
            [collectionField.foreignKey]: {
                $is: null
            }
        };
        if ([
            'obo'
        ].includes(collectionField.interface) && !(0, __WEBPACK_EXTERNAL_MODULE__filter_provider_index_mjs__.isInFilterFormBlock)(fieldSchema)) {
            const fields = getCollectionFields(collectionField.target);
            const targetField = fields.find((f)=>f.foreignKey && f.foreignKey === collectionField.foreignKey);
            if (targetField) extraFilter = (null == record ? void 0 : record[collectionField.foreignKey]) ? {
                $or: [
                    {
                        ["".concat(targetField.name, ".").concat(targetField.foreignKey)]: {
                            $is: null
                        }
                    },
                    {
                        ["".concat(targetField.name, ".").concat(targetField.foreignKey)]: {
                            $eq: null == record ? void 0 : record[collectionField.foreignKey]
                        }
                    }
                ]
            } : {
                ["".concat(targetField.name, ".").concat(targetField.foreignKey)]: {
                    $is: null
                }
            };
        }
    }
    if (extraFilter) {
        if (null == params ? void 0 : params.filter) params['filter'] = {
            $and: [
                extraFilter,
                params['filter']
            ]
        };
        else params['filter'] = extraFilter;
    }
    try {
        params.filter = (0, __WEBPACK_EXTERNAL_MODULE__filter_provider_utils_mjs__.mergeFilter)([
            parentParams.filter,
            params.filter
        ]);
        params = {
            ...parentParams,
            ...params
        };
    } catch (err) {
        console.error(err);
    }
    const { filter: parsedFilter } = (0, __WEBPACK_EXTERNAL_MODULE__hooks_index_mjs__.useParsedFilter)({
        filterOption: null == params ? void 0 : params.filter
    });
    if (!__WEBPACK_EXTERNAL_MODULE_lodash__["default"].isEmpty(null == params ? void 0 : params.filter) && __WEBPACK_EXTERNAL_MODULE_lodash__["default"].isEmpty(parsedFilter)) return null;
    if (null == params ? void 0 : params.filter) params.filter = parsedFilter;
    return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__schema_component_index_mjs__.SchemaComponentOptions, {
        scope: {
            treeTable
        },
        children: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__BlockProvider_mjs__.BlockProvider, {
            name: "table-selector",
            ...props,
            params: params,
            children: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(InternalTableSelectorProvider, {
                ...props,
                params: params,
                extraFilter: extraFilter
            })
        })
    });
});
const useTableSelectorContext = ()=>(0, __WEBPACK_EXTERNAL_MODULE_react__.useContext)(TableSelectorContext);
const useTableSelectorProps = ()=>{
    var _ctx_field_data, _ctx_field, _ctx_service_data, _ctx_service, _ctx_service_data_meta, _ctx_service_data1, _ctx_service1, _ctx_service_data_meta1, _ctx_service_data2, _ctx_service2, _ctx_service_data_meta2, _ctx_service_data3, _ctx_service3, _ctx_service4, _ctx_service5, _ctx_params, _ctx_params1, _ctx_params2;
    const field = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useField)();
    const ctx = useTableSelectorContext();
    const fieldSchema = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useFieldSchema)();
    const { getCollectionJoinField } = (0, __WEBPACK_EXTERNAL_MODULE__collection_manager_index_mjs__.useCollectionManager_deprecated)();
    const collectionFieldSchema = recursiveParent(fieldSchema, 'CollectionField');
    const collectionField = getCollectionJoinField(null == collectionFieldSchema ? void 0 : collectionFieldSchema['x-collection-field']);
    (0, __WEBPACK_EXTERNAL_MODULE_react__.useEffect)(()=>{
        var _ctx_service;
        if (!(null == ctx ? void 0 : null === (_ctx_service = ctx.service) || void 0 === _ctx_service ? void 0 : _ctx_service.loading)) {
            var _ctx_service_data, _ctx_service1, _field_setInitialValue, _ctx_field_data, _ctx_field, _ctx_service_data_meta, _ctx_service_data1, _ctx_service2, _ctx_service_data_meta1, _ctx_service_data2, _ctx_service3, _ctx_service_data_meta2, _ctx_service_data3, _ctx_service4;
            const data = null == ctx ? void 0 : null === (_ctx_service1 = ctx.service) || void 0 === _ctx_service1 ? void 0 : null === (_ctx_service_data = _ctx_service1.data) || void 0 === _ctx_service_data ? void 0 : _ctx_service_data.data.map((v)=>__WEBPACK_EXTERNAL_MODULE_lodash__["default"].omit(v, null == collectionField ? void 0 : collectionField.foreignKey));
            field.value = data;
            null == field || null === (_field_setInitialValue = field.setInitialValue) || void 0 === _field_setInitialValue || _field_setInitialValue.call(field, data);
            field.data = field.data || {};
            field.data.selectedRowKeys = null == ctx ? void 0 : null === (_ctx_field = ctx.field) || void 0 === _ctx_field ? void 0 : null === (_ctx_field_data = _ctx_field.data) || void 0 === _ctx_field_data ? void 0 : _ctx_field_data.selectedRowKeys;
            field.componentProps.pagination = field.componentProps.pagination || {};
            field.componentProps.pagination.pageSize = null == ctx ? void 0 : null === (_ctx_service2 = ctx.service) || void 0 === _ctx_service2 ? void 0 : null === (_ctx_service_data1 = _ctx_service2.data) || void 0 === _ctx_service_data1 ? void 0 : null === (_ctx_service_data_meta = _ctx_service_data1.meta) || void 0 === _ctx_service_data_meta ? void 0 : _ctx_service_data_meta.pageSize;
            field.componentProps.pagination.total = null == ctx ? void 0 : null === (_ctx_service3 = ctx.service) || void 0 === _ctx_service3 ? void 0 : null === (_ctx_service_data2 = _ctx_service3.data) || void 0 === _ctx_service_data2 ? void 0 : null === (_ctx_service_data_meta1 = _ctx_service_data2.meta) || void 0 === _ctx_service_data_meta1 ? void 0 : _ctx_service_data_meta1.count;
            field.componentProps.pagination.current = null == ctx ? void 0 : null === (_ctx_service4 = ctx.service) || void 0 === _ctx_service4 ? void 0 : null === (_ctx_service_data3 = _ctx_service4.data) || void 0 === _ctx_service_data3 ? void 0 : null === (_ctx_service_data_meta2 = _ctx_service_data3.meta) || void 0 === _ctx_service_data_meta2 ? void 0 : _ctx_service_data_meta2.page;
        }
    }, [
        null == collectionField ? void 0 : collectionField.foreignKey,
        null == ctx ? void 0 : null === (_ctx_field = ctx.field) || void 0 === _ctx_field ? void 0 : null === (_ctx_field_data = _ctx_field.data) || void 0 === _ctx_field_data ? void 0 : _ctx_field_data.selectedRowKeys,
        null == ctx ? void 0 : null === (_ctx_service = ctx.service) || void 0 === _ctx_service ? void 0 : null === (_ctx_service_data = _ctx_service.data) || void 0 === _ctx_service_data ? void 0 : _ctx_service_data.data,
        null == ctx ? void 0 : null === (_ctx_service1 = ctx.service) || void 0 === _ctx_service1 ? void 0 : null === (_ctx_service_data1 = _ctx_service1.data) || void 0 === _ctx_service_data1 ? void 0 : null === (_ctx_service_data_meta = _ctx_service_data1.meta) || void 0 === _ctx_service_data_meta ? void 0 : _ctx_service_data_meta.count,
        null == ctx ? void 0 : null === (_ctx_service2 = ctx.service) || void 0 === _ctx_service2 ? void 0 : null === (_ctx_service_data2 = _ctx_service2.data) || void 0 === _ctx_service_data2 ? void 0 : null === (_ctx_service_data_meta1 = _ctx_service_data2.meta) || void 0 === _ctx_service_data_meta1 ? void 0 : _ctx_service_data_meta1.page,
        null == ctx ? void 0 : null === (_ctx_service3 = ctx.service) || void 0 === _ctx_service3 ? void 0 : null === (_ctx_service_data3 = _ctx_service3.data) || void 0 === _ctx_service_data3 ? void 0 : null === (_ctx_service_data_meta2 = _ctx_service_data3.meta) || void 0 === _ctx_service_data_meta2 ? void 0 : _ctx_service_data_meta2.pageSize,
        null == ctx ? void 0 : null === (_ctx_service4 = ctx.service) || void 0 === _ctx_service4 ? void 0 : _ctx_service4.loading,
        field
    ]);
    return {
        loading: null == ctx ? void 0 : null === (_ctx_service5 = ctx.service) || void 0 === _ctx_service5 ? void 0 : _ctx_service5.loading,
        showIndex: false,
        dragSort: false,
        rowKey: ctx.rowKey || 'id',
        pagination: (null == ctx ? void 0 : null === (_ctx_params = ctx.params) || void 0 === _ctx_params ? void 0 : _ctx_params.paginate) !== false && {
            defaultCurrent: (null == ctx ? void 0 : null === (_ctx_params1 = ctx.params) || void 0 === _ctx_params1 ? void 0 : _ctx_params1.page) || 1,
            defaultPageSize: null == ctx ? void 0 : null === (_ctx_params2 = ctx.params) || void 0 === _ctx_params2 ? void 0 : _ctx_params2.pageSize
        },
        onRowSelectionChange (selectedRowKeys, selectedRows) {
            var _ctx_field;
            ctx.field.data = (null == ctx ? void 0 : null === (_ctx_field = ctx.field) || void 0 === _ctx_field ? void 0 : _ctx_field.data) || {};
            ctx.field.data.selectedRowKeys = selectedRowKeys;
        },
        async onRowDragEnd (param) {
            let { from, to } = param;
            await ctx.resource.move({
                sourceId: from[ctx.rowKey || 'id'],
                targetId: to[ctx.rowKey || 'id']
            });
            ctx.service.refresh();
        },
        onChange (param) {
            let { current, pageSize } = param;
            var _ctx_service_params;
            ctx.service.run({
                ...null === (_ctx_service_params = ctx.service.params) || void 0 === _ctx_service_params ? void 0 : _ctx_service_params[0],
                page: current,
                pageSize
            });
        }
    };
};
export { TableSelectorContext, TableSelectorParamsProvider, TableSelectorProvider, recursiveParent, useTableSelectorContext, useTableSelectorProps };
