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__index_mjs__ from "../../index.mjs";
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__hooks_index_mjs__ from "../../hooks/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__action_index_mjs__ from "../action/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__input_index_mjs__ from "../input/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__preview_index_mjs__ from "../preview/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 InternalFileManager = (props)=>{
    var _fieldSchema_xcomponentprops, _fieldSchema_xcomponentprops1;
    const { value, multiple, onChange, ...others } = props;
    const fieldSchema = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useFieldSchema)();
    const [visibleSelector, setVisibleSelector] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)(false);
    const [selectedRows, setSelectedRows] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)([]);
    const insertSelector = (0, __WEBPACK_EXTERNAL_MODULE__hooks_mjs__.useInsertSchema)('Selector');
    const fieldNames = (0, __WEBPACK_EXTERNAL_MODULE__hooks_mjs__.useFieldNames)(props);
    const field = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useField)();
    const [options, setOptions] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)([]);
    const { getField } = (0, __WEBPACK_EXTERNAL_MODULE__collection_manager_index_mjs__.useCollection_deprecated)();
    const collectionField = getField(field.props.name);
    const labelUiSchema = (0, __WEBPACK_EXTERNAL_MODULE__util_mjs__.useLabelUiSchema)(null == collectionField ? void 0 : collectionField.target, (null == fieldNames ? void 0 : fieldNames.label) || 'label');
    const compile = (0, __WEBPACK_EXTERNAL_MODULE__hooks_index_mjs__.useCompile)();
    const { modalProps } = (0, __WEBPACK_EXTERNAL_MODULE__index_mjs__.useActionContext)();
    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 handleSelect = ()=>{
        insertSelector(__WEBPACK_EXTERNAL_MODULE__schema_mjs__["default"].Selector);
        setVisibleSelector(true);
        setSelectedRows([]);
    };
    (0, __WEBPACK_EXTERNAL_MODULE_react__.useEffect)(()=>{
        if (value && Object.keys(value).length > 0) {
            const opts = (Array.isArray(value) ? value : value ? [
                value
            ] : []).filter(Boolean).map((option)=>{
                const label = option[fieldNames.label];
                return {
                    ...option,
                    [fieldNames.label]: (0, __WEBPACK_EXTERNAL_MODULE__util_mjs__.getLabelFormatValue)(compile(labelUiSchema), compile(label))
                };
            });
            setOptions(opts);
        } else setOptions([]);
    }, [
        value,
        null == fieldNames ? void 0 : fieldNames.label
    ]);
    const handleRemove = (file)=>{
        const newOptions = options.filter((option)=>option.id !== file.id);
        setOptions(newOptions);
        if (0 === newOptions.length) return onChange(null);
        onChange(newOptions);
    };
    const pickerProps = {
        size: 'small',
        fieldNames,
        multiple: [
            'o2m',
            'm2m'
        ].includes(null == collectionField ? void 0 : collectionField.interface) && multiple,
        association: {
            target: null == collectionField ? void 0 : collectionField.target
        },
        options,
        onChange: null == props ? void 0 : props.onChange,
        selectedRows,
        setSelectedRows,
        collectionField
    };
    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);
            }
        };
    };
    return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsxs)("div", {
        style: {
            width: '100%',
            overflow: 'auto'
        },
        children: [
            /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__preview_index_mjs__.FileSelector, {
                value: options,
                multiple: multiple,
                quickUpload: (null === (_fieldSchema_xcomponentprops = fieldSchema['x-component-props']) || void 0 === _fieldSchema_xcomponentprops ? void 0 : _fieldSchema_xcomponentprops.quickUpload) !== false,
                selectFile: (null === (_fieldSchema_xcomponentprops1 = fieldSchema['x-component-props']) || void 0 === _fieldSchema_xcomponentprops1 ? void 0 : _fieldSchema_xcomponentprops1.selectFile) !== false,
                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__action_index_mjs__.ActionContextProvider, {
                value: {
                    openMode: 'drawer',
                    visible: visibleSelector,
                    setVisible: setVisibleSelector,
                    modalProps: {
                        getContainer: (null == others ? void 0 : others.getContainer) || (null == modalProps ? void 0 : modalProps.getContainer)
                    },
                    formValueChanged: false
                },
                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__collection_manager_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']
                                    })
                                })
                            })
                        })
                    })
                })
            })
        ]
    });
};
const FileManageReadPretty = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.connect)((props)=>{
    const fieldSchema = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useFieldSchema)();
    const { getField } = (0, __WEBPACK_EXTERNAL_MODULE__collection_manager_index_mjs__.useCollection_deprecated)();
    const { getCollectionJoinField } = (0, __WEBPACK_EXTERNAL_MODULE__collection_manager_index_mjs__.useCollectionManager_deprecated)();
    const collectionField = getField(fieldSchema.name) || getCollectionJoinField(fieldSchema['x-collection-field']);
    return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__input_index_mjs__.EllipsisWithTooltip, {
        ellipsis: true,
        children: collectionField ? /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__preview_index_mjs__.Preview, {
            ...props
        }) : null
    });
});
export { FileManageReadPretty, InternalFileManager };
