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__block_provider_TableSelectorProvider_mjs__ from "../../../block-provider/TableSelectorProvider.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__collection_manager_index_mjs__ from "../../../collection-manager/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__core_index_mjs__ from "../../core/index.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__preview_index_mjs__ from "../preview/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__useFieldNames_mjs__ from "./useFieldNames.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__util_mjs__ from "./util.mjs";
const RecordPickerContext = /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react__.createContext)(null);
RecordPickerContext.displayName = 'RecordPickerContext';
function flatData(data) {
    const newArr = [];
    for(let i = 0; i < data.length; i++){
        const children = data[i]['children'];
        if (Array.isArray(children)) newArr.push(...flatData(children));
        newArr.push({
            ...data[i]
        });
    }
    return newArr;
}
const useTableSelectorProps = ()=>{
    const field = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useField)();
    const { multiple, options = [], setSelectedRows, selectedRows: rcSelectRows = [], onChange } = (0, __WEBPACK_EXTERNAL_MODULE_react__.useContext)(RecordPickerContext);
    const { onRowSelectionChange, rowKey = 'id', ...others } = (0, __WEBPACK_EXTERNAL_MODULE__block_provider_TableSelectorProvider_mjs__.useTableSelectorProps)();
    const { setVisible } = (0, __WEBPACK_EXTERNAL_MODULE__action_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 = 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 usePickActionProps = ()=>{
    const { setVisible } = (0, __WEBPACK_EXTERNAL_MODULE__action_index_mjs__.useActionContext)();
    const { multiple, selectedRows, onChange, options, collectionField } = (0, __WEBPACK_EXTERNAL_MODULE_react__.useContext)(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);
        }
    };
};
const useAssociation = (props)=>{
    const fieldSchema = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useFieldSchema)();
    const { association } = props;
    const { getField } = (0, __WEBPACK_EXTERNAL_MODULE__collection_manager_index_mjs__.useCollection_deprecated)();
    if (association) return association;
    return getField(fieldSchema.name);
};
const InputRecordPicker = (props)=>{
    const { value, multiple, onChange, quickUpload, selectFile, ...others } = props;
    const fieldNames = (0, __WEBPACK_EXTERNAL_MODULE__useFieldNames_mjs__.useFieldNames)(props);
    const [visible, setVisible] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)(false);
    const fieldSchema = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useFieldSchema)();
    const collectionField = useAssociation(props);
    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 showFilePicker = isShowFilePicker(labelUiSchema);
    const [selectedRows, setSelectedRows] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)([]);
    const [options, setOptions] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)([]);
    (0, __WEBPACK_EXTERNAL_MODULE_react__.useEffect)(()=>{
        if (value) {
            const opts = (Array.isArray(value) ? value : value ? [
                value
            ] : []).map((option)=>{
                const label = option[fieldNames.label];
                return {
                    ...option,
                    [fieldNames.label]: (0, __WEBPACK_EXTERNAL_MODULE__util_mjs__.getLabelFormatValue)(labelUiSchema, compile(label))
                };
            });
            setOptions(opts);
        }
    }, [
        value,
        null == fieldNames ? void 0 : fieldNames.label
    ]);
    const getValue = ()=>{
        if (null == multiple) return null;
        return Array.isArray(value) ? null == value ? void 0 : value.map((v)=>v[fieldNames.value]) : null == value ? void 0 : value[fieldNames.value];
    };
    const handleSelect = ()=>{
        setVisible(true);
        setSelectedRows([]);
    };
    const handleRemove = (file)=>{
        const newOptions = options.filter((option)=>option.id !== file.id);
        setOptions(newOptions);
        if (0 === newOptions.length) return onChange(null);
        onChange(newOptions);
    };
    return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsxs)("div", {
        children: [
            showFilePicker ? /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__preview_index_mjs__.FileSelector, {
                value: options,
                multiple: multiple,
                quickUpload: quickUpload,
                selectFile: selectFile,
                action: "".concat(null == collectionField ? void 0 : collectionField.target, ":create"),
                onSelect: handleSelect,
                onRemove: handleRemove,
                onChange: (changed)=>{
                    if (changed.every((file)=>'uploading' !== file.status)) {
                        changed = changed.filter((file)=>'done' === file.status).map((file)=>file.response.data);
                        multiple ? onChange([
                            ...options,
                            ...changed
                        ]) : onChange(changed[0]);
                    }
                }
            }) : /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.Select, {
                ...others,
                mode: multiple ? 'multiple' : props.mode,
                fieldNames: fieldNames,
                popupMatchSelectWidth: false,
                onDropdownVisibleChange: (open)=>{
                    setVisible(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);
                        setOptions([]);
                    }
                },
                options: options,
                value: getValue(),
                open: false
            }),
            Drawer({
                multiple,
                onChange,
                selectedRows,
                setSelectedRows,
                collectionField,
                visible,
                setVisible,
                fieldSchema,
                options
            })
        ]
    });
};
const RecordPickerProvider = (props)=>{
    const { multiple, onChange, selectedRows, setSelectedRows, options, collectionField, ...other } = props;
    return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(RecordPickerContext.Provider, {
        value: {
            multiple,
            onChange,
            selectedRows,
            setSelectedRows,
            options,
            collectionField,
            ...other
        },
        children: props.children
    });
};
const Drawer = (param)=>{
    let { multiple, onChange, selectedRows, setSelectedRows, collectionField, visible, setVisible, fieldSchema, options } = param;
    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 recordPickerProps = {
        multiple,
        onChange,
        selectedRows,
        setSelectedRows,
        options,
        collectionField
    };
    return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(RecordPickerProvider, {
        ...recordPickerProps,
        children: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__collection_manager_index_mjs__.CollectionProvider_deprecated, {
            allowNull: true,
            name: null == collectionField ? void 0 : collectionField.target,
            children: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__action_index_mjs__.ActionContextProvider, {
                openMode: "drawer",
                visible: visible,
                setVisible: setVisible,
                children: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__core_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__core_index_mjs__.SchemaComponentOptions, {
                            scope: {
                                useTableSelectorProps,
                                usePickActionProps
                            },
                            children: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__tachybase_schema__.RecursionField, {
                                schema: fieldSchema,
                                onlyRenderProperties: true,
                                filterProperties: (s)=>'RecordPicker.Selector' === s['x-component']
                            })
                        })
                    })
                })
            })
        })
    });
};
function isShowFilePicker(labelUiSchema) {
    return (null == labelUiSchema ? void 0 : labelUiSchema['x-component']) === 'Preview';
}
export { InputRecordPicker, RecordPickerContext, RecordPickerProvider, isShowFilePicker };
