"use strict";
var __webpack_require__ = {};
(()=>{
    __webpack_require__.d = function(exports1, definition) {
        for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
            enumerable: true,
            get: definition[key]
        });
    };
})();
(()=>{
    __webpack_require__.o = function(obj, prop) {
        return Object.prototype.hasOwnProperty.call(obj, prop);
    };
})();
(()=>{
    __webpack_require__.r = function(exports1) {
        if ('undefined' != typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
            value: 'Module'
        });
        Object.defineProperty(exports1, '__esModule', {
            value: true
        });
    };
})();
var __webpack_exports__ = {};
__webpack_require__.r(__webpack_exports__);
__webpack_require__.d(__webpack_exports__, {
    RecordPickerContext: ()=>RecordPickerContext,
    RecordPickerProvider: ()=>RecordPickerProvider,
    isShowFilePicker: ()=>isShowFilePicker,
    InputRecordPicker: ()=>InputRecordPicker
});
const jsx_runtime_namespaceObject = require("react/jsx-runtime");
const external_react_namespaceObject = require("react");
const schema_namespaceObject = require("@tachybase/schema");
const external_antd_namespaceObject = require("antd");
const external_lodash_namespaceObject = require("lodash");
const TableSelectorProvider_js_namespaceObject = require("../../../block-provider/TableSelectorProvider.js");
const index_js_namespaceObject = require("../../../collection-manager/index.js");
const external_core_index_js_namespaceObject = require("../../core/index.js");
const external_hooks_index_js_namespaceObject = require("../../hooks/index.js");
const external_action_index_js_namespaceObject = require("../action/index.js");
const external_preview_index_js_namespaceObject = require("../preview/index.js");
const external_useFieldNames_js_namespaceObject = require("./useFieldNames.js");
const external_util_js_namespaceObject = require("./util.js");
const RecordPickerContext = /*#__PURE__*/ (0, external_react_namespaceObject.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, schema_namespaceObject.useField)();
    const { multiple, options = [], setSelectedRows, selectedRows: rcSelectRows = [], onChange } = (0, external_react_namespaceObject.useContext)(RecordPickerContext);
    const { onRowSelectionChange, rowKey = 'id', ...others } = (0, TableSelectorProvider_js_namespaceObject.useTableSelectorProps)();
    const { setVisible } = (0, external_action_index_js_namespaceObject.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, external_lodash_namespaceObject.differenceBy)(allSelectedRows, scopeRows, rowKey);
                const unionSelectedRows = (0, external_lodash_namespaceObject.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, external_action_index_js_namespaceObject.useActionContext)();
    const { multiple, selectedRows, onChange, options, collectionField } = (0, external_react_namespaceObject.useContext)(RecordPickerContext);
    return {
        onClick () {
            multiple ? onChange((0, external_lodash_namespaceObject.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, schema_namespaceObject.useFieldSchema)();
    const { association } = props;
    const { getField } = (0, index_js_namespaceObject.useCollection_deprecated)();
    if (association) return association;
    return getField(fieldSchema.name);
};
const InputRecordPicker = (props)=>{
    const { value, multiple, onChange, quickUpload, selectFile, ...others } = props;
    const fieldNames = (0, external_useFieldNames_js_namespaceObject.useFieldNames)(props);
    const [visible, setVisible] = (0, external_react_namespaceObject.useState)(false);
    const fieldSchema = (0, schema_namespaceObject.useFieldSchema)();
    const collectionField = useAssociation(props);
    const compile = (0, external_hooks_index_js_namespaceObject.useCompile)();
    const labelUiSchema = (0, external_util_js_namespaceObject.useLabelUiSchema)(collectionField, (null == fieldNames ? void 0 : fieldNames.label) || 'label');
    const showFilePicker = isShowFilePicker(labelUiSchema);
    const [selectedRows, setSelectedRows] = (0, external_react_namespaceObject.useState)([]);
    const [options, setOptions] = (0, external_react_namespaceObject.useState)([]);
    (0, external_react_namespaceObject.useEffect)(()=>{
        if (value) {
            const opts = (Array.isArray(value) ? value : value ? [
                value
            ] : []).map((option)=>{
                const label = option[fieldNames.label];
                return {
                    ...option,
                    [fieldNames.label]: (0, external_util_js_namespaceObject.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, jsx_runtime_namespaceObject.jsxs)("div", {
        children: [
            showFilePicker ? /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(external_preview_index_js_namespaceObject.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, jsx_runtime_namespaceObject.jsx)(external_antd_namespaceObject.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, jsx_runtime_namespaceObject.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, jsx_runtime_namespaceObject.jsx)(RecordPickerProvider, {
        ...recordPickerProps,
        children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(index_js_namespaceObject.CollectionProvider_deprecated, {
            allowNull: true,
            name: null == collectionField ? void 0 : collectionField.target,
            children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(external_action_index_js_namespaceObject.ActionContextProvider, {
                openMode: "drawer",
                visible: visible,
                setVisible: setVisible,
                children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(external_core_index_js_namespaceObject.FormProvider, {
                    children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(TableSelectorProvider_js_namespaceObject.TableSelectorParamsProvider, {
                        params: {
                            filter: getFilter()
                        },
                        children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(external_core_index_js_namespaceObject.SchemaComponentOptions, {
                            scope: {
                                useTableSelectorProps,
                                usePickActionProps
                            },
                            children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(schema_namespaceObject.RecursionField, {
                                schema: fieldSchema,
                                onlyRenderProperties: true,
                                filterProperties: (s)=>'RecordPicker.Selector' === s['x-component']
                            })
                        })
                    })
                })
            })
        })
    });
};
function isShowFilePicker(labelUiSchema) {
    return (null == labelUiSchema ? void 0 : labelUiSchema['x-component']) === 'Preview';
}
var __webpack_export_target__ = exports;
for(var __webpack_i__ in __webpack_exports__)__webpack_export_target__[__webpack_i__] = __webpack_exports__[__webpack_i__];
if (__webpack_exports__.__esModule) Object.defineProperty(__webpack_export_target__, '__esModule', {
    value: true
});
