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_antd__ from "antd";
import * as __WEBPACK_EXTERNAL_MODULE_lodash__ from "lodash";
import * as __WEBPACK_EXTERNAL_MODULE__index_mjs__ from "../../index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__index_mjs__ from "../../../index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__block_provider_TableSelectorProvider_mjs__ from "../../../block-provider/TableSelectorProvider.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__hooks_index_mjs__ from "../../hooks/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__action_index_mjs__ from "../action/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__hooks_mjs__ from "./hooks.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__schema_mjs__ from "./schema.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__util_mjs__ from "./util.mjs";
const useTableSelectorProps = ()=>{
    const field = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useField)();
    const { multiple, options = [], setSelectedRows, selectedRows: rcSelectRows = [], onChange } = (0, __WEBPACK_EXTERNAL_MODULE_react__.useContext)(__WEBPACK_EXTERNAL_MODULE__index_mjs__.RecordPickerContext);
    const { onRowSelectionChange, rowKey = 'id', ...others } = (0, __WEBPACK_EXTERNAL_MODULE__block_provider_TableSelectorProvider_mjs__.useTableSelectorProps)();
    const { setVisible } = (0, __WEBPACK_EXTERNAL_MODULE__index_mjs__.useActionContext)();
    return {
        ...others,
        rowKey,
        rowSelection: {
            type: multiple ? 'checkbox' : 'radio',
            selectedRowKeys: null == rcSelectRows ? void 0 : rcSelectRows.filter((item)=>options.every((row)=>row[rowKey] !== item[rowKey])).map((item)=>item[rowKey])
        },
        onRowSelectionChange (selectedRowKeys, selectedRows) {
            if (multiple) {
                const scopeRows = (0, __WEBPACK_EXTERNAL_MODULE__util_mjs__.flatData)(field.value) || [];
                const allSelectedRows = rcSelectRows || [];
                const otherRows = (0, __WEBPACK_EXTERNAL_MODULE_lodash__.differenceBy)(allSelectedRows, scopeRows, rowKey);
                const unionSelectedRows = (0, __WEBPACK_EXTERNAL_MODULE_lodash__.unionBy)(otherRows, selectedRows, rowKey);
                const unionSelectedRowKeys = unionSelectedRows.map((item)=>item[rowKey]);
                null == setSelectedRows || setSelectedRows(unionSelectedRows);
                null == onRowSelectionChange || onRowSelectionChange(unionSelectedRowKeys, unionSelectedRows);
            } else {
                null == setSelectedRows || setSelectedRows(selectedRows);
                null == onRowSelectionChange || onRowSelectionChange(selectedRowKeys, selectedRows);
                onChange((null == selectedRows ? void 0 : selectedRows[0]) || null);
                setVisible(false);
            }
        }
    };
};
const InternalPicker = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.observer)((props)=>{
    var _fieldSchema_xcomponentprops;
    const { value, multiple, openSize, onChange, quickUpload, selectFile, shouldMountElement, ...others } = props;
    const field = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useField)();
    const fieldNames = (0, __WEBPACK_EXTERNAL_MODULE__hooks_mjs__.useFieldNames)(props);
    const [visibleSelector, setVisibleSelector] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)(false);
    const fieldSchema = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useFieldSchema)();
    const insertSelector = (0, __WEBPACK_EXTERNAL_MODULE__hooks_mjs__.useInsertSchema)('Selector');
    const { options: collectionField } = (0, __WEBPACK_EXTERNAL_MODULE__hooks_mjs__.useAssociationFieldContext)();
    const { collectionName } = (0, __WEBPACK_EXTERNAL_MODULE__index_mjs__.useFormBlockContext)();
    const compile = (0, __WEBPACK_EXTERNAL_MODULE__hooks_index_mjs__.useCompile)();
    const labelUiSchema = (0, __WEBPACK_EXTERNAL_MODULE__util_mjs__.useLabelUiSchema)(collectionField, (null == fieldNames ? void 0 : fieldNames.label) || 'label');
    const isAllowAddNew = fieldSchema['x-add-new'];
    const [selectedRows, setSelectedRows] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)([]);
    const recordData = (0, __WEBPACK_EXTERNAL_MODULE__index_mjs__.useCollectionRecordData)();
    const options = (0, __WEBPACK_EXTERNAL_MODULE_react__.useMemo)(()=>{
        if (value && Object.keys(value).length > 0) {
            const opts = (Array.isArray(value) ? value : value ? [
                value
            ] : []).filter(Boolean).map((option)=>{
                const label = null == option ? void 0 : option[fieldNames.label];
                return {
                    ...option,
                    [fieldNames.label]: (0, __WEBPACK_EXTERNAL_MODULE__util_mjs__.getLabelFormatValue)(compile(labelUiSchema), compile(label))
                };
            });
            return opts;
        }
        return [];
    }, [
        value,
        null == fieldNames ? void 0 : fieldNames.label
    ]);
    const pickerProps = {
        size: 'small',
        fieldNames,
        multiple: false !== multiple && [
            'o2m',
            'm2m'
        ].includes(null == collectionField ? void 0 : collectionField.interface),
        association: {
            target: null == collectionField ? void 0 : collectionField.target
        },
        options,
        onChange: null == props ? void 0 : props.onChange,
        selectedRows,
        setSelectedRows,
        collectionField,
        currentFormCollection: collectionName
    };
    const getValue = ()=>{
        var _value_filter;
        if (null == multiple) return null;
        return Array.isArray(value) ? null === (_value_filter = value.filter(Boolean)) || void 0 === _value_filter ? void 0 : _value_filter.map((v)=>null == v ? void 0 : v[fieldNames.value]) : null == value ? void 0 : value[fieldNames.value];
    };
    const getFilter = ()=>{
        const targetKey = (null == collectionField ? void 0 : collectionField.targetKey) || 'id';
        const list = options.map((option)=>option[targetKey]).filter(Boolean);
        const filter = list.length ? {
            $and: [
                {
                    ["".concat(targetKey, ".$ne")]: list
                }
            ]
        } : {};
        return filter;
    };
    const usePickActionProps = ()=>{
        const { setVisible } = (0, __WEBPACK_EXTERNAL_MODULE__index_mjs__.useActionContext)();
        const { multiple, selectedRows, onChange, options, collectionField } = (0, __WEBPACK_EXTERNAL_MODULE_react__.useContext)(__WEBPACK_EXTERNAL_MODULE__index_mjs__.RecordPickerContext);
        return {
            onClick () {
                multiple ? onChange((0, __WEBPACK_EXTERNAL_MODULE_lodash__.unionBy)(selectedRows, options, (null == collectionField ? void 0 : collectionField.targetKey) || 'id')) : onChange((null == selectedRows ? void 0 : selectedRows[0]) || null);
                setVisible(false);
            },
            style: {
                display: false !== multiple && [
                    'o2m',
                    'm2m'
                ].includes(null == collectionField ? void 0 : collectionField.interface) ? 'block' : 'none'
            }
        };
    };
    return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsxs)(__WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.Fragment, {
        children: [
            /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsxs)(__WEBPACK_EXTERNAL_MODULE_antd__.Space.Compact, {
                style: {
                    display: 'flex',
                    lineHeight: '32px'
                },
                children: [
                    /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)("div", {
                        style: {
                            width: '100%'
                        },
                        children: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Select, {
                            role: "button",
                            "data-testid": "select-data-picker",
                            style: {
                                width: '100%'
                            },
                            popupMatchSelectWidth: false,
                            ...others,
                            mode: multiple ? 'multiple' : props.mode,
                            fieldNames: fieldNames,
                            onDropdownVisibleChange: (open)=>{
                                insertSelector(__WEBPACK_EXTERNAL_MODULE__schema_mjs__["default"].Selector);
                                setVisibleSelector(true);
                            },
                            allowClear: true,
                            onChange: (changed)=>{
                                if (changed) {
                                    if (Array.isArray(changed)) {
                                        if (!changed.length) {
                                            onChange([]);
                                            setSelectedRows([]);
                                            return;
                                        }
                                        const values = null == options ? void 0 : options.filter((option)=>changed.includes(option[fieldNames.value]));
                                        onChange(values);
                                        setSelectedRows(values);
                                    }
                                } else {
                                    const value = multiple ? [] : null;
                                    onChange(value);
                                    setSelectedRows(value);
                                }
                            },
                            options: options,
                            value: getValue(),
                            open: false
                        })
                    }),
                    isAllowAddNew && /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__index_mjs__.RecordProvider, {
                        isNew: true,
                        record: null,
                        parent: recordData,
                        children: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__tachybase_schema__.RecursionField, {
                            onlyRenderProperties: true,
                            basePath: field.address,
                            schema: fieldSchema,
                            filterProperties: (s)=>'Action' === s['x-component']
                        })
                    })
                ]
            }),
            /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__action_index_mjs__.ActionContextProvider, {
                value: {
                    openSize: (null === (_fieldSchema_xcomponentprops = fieldSchema['x-component-props']) || void 0 === _fieldSchema_xcomponentprops ? void 0 : _fieldSchema_xcomponentprops['openSize']) || openSize,
                    openMode: 'drawer',
                    visible: visibleSelector,
                    setVisible: setVisibleSelector
                },
                children: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__index_mjs__.RecordPickerProvider, {
                    ...pickerProps,
                    children: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__index_mjs__.CollectionProvider_deprecated, {
                        name: null == collectionField ? void 0 : collectionField.target,
                        children: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__index_mjs__.FormProvider, {
                            children: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__block_provider_TableSelectorProvider_mjs__.TableSelectorParamsProvider, {
                                params: {
                                    filter: getFilter()
                                },
                                children: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__index_mjs__.SchemaComponentOptions, {
                                    scope: {
                                        usePickActionProps,
                                        useTableSelectorProps
                                    },
                                    children: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__tachybase_schema__.RecursionField, {
                                        onlyRenderProperties: true,
                                        basePath: field.address,
                                        schema: fieldSchema,
                                        filterProperties: (s)=>'AssociationField.Selector' === s['x-component']
                                    })
                                })
                            })
                        })
                    })
                })
            })
        ]
    });
}, {
    displayName: 'InternalPicker'
});
export { InternalPicker, useTableSelectorProps };
