"use strict";
var __webpack_require__ = {};
(()=>{
    __webpack_require__.n = function(module) {
        var getter = module && module.__esModule ? function() {
            return module['default'];
        } : function() {
            return module;
        };
        __webpack_require__.d(getter, {
            a: getter
        });
        return getter;
    };
})();
(()=>{
    __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__, {
    InternalPicker: ()=>InternalPicker,
    useTableSelectorProps: ()=>useTableSelectorProps
});
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 external_index_js_namespaceObject = require("../../index.js");
const external_index_js_namespaceObject_1 = require("../../../index.js");
const TableSelectorProvider_js_namespaceObject = require("../../../block-provider/TableSelectorProvider.js");
const index_js_namespaceObject = require("../../hooks/index.js");
const external_action_index_js_namespaceObject = require("../action/index.js");
const external_hooks_js_namespaceObject = require("./hooks.js");
const external_schema_js_namespaceObject = require("./schema.js");
var external_schema_js_default = /*#__PURE__*/ __webpack_require__.n(external_schema_js_namespaceObject);
const external_util_js_namespaceObject = require("./util.js");
const useTableSelectorProps = ()=>{
    const field = (0, schema_namespaceObject.useField)();
    const { multiple, options = [], setSelectedRows, selectedRows: rcSelectRows = [], onChange } = (0, external_react_namespaceObject.useContext)(external_index_js_namespaceObject.RecordPickerContext);
    const { onRowSelectionChange, rowKey = 'id', ...others } = (0, TableSelectorProvider_js_namespaceObject.useTableSelectorProps)();
    const { setVisible } = (0, external_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 = (0, external_util_js_namespaceObject.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 InternalPicker = (0, schema_namespaceObject.observer)((props)=>{
    var _fieldSchema_xcomponentprops;
    const { value, multiple, openSize, onChange, quickUpload, selectFile, shouldMountElement, ...others } = props;
    const field = (0, schema_namespaceObject.useField)();
    const fieldNames = (0, external_hooks_js_namespaceObject.useFieldNames)(props);
    const [visibleSelector, setVisibleSelector] = (0, external_react_namespaceObject.useState)(false);
    const fieldSchema = (0, schema_namespaceObject.useFieldSchema)();
    const insertSelector = (0, external_hooks_js_namespaceObject.useInsertSchema)('Selector');
    const { options: collectionField } = (0, external_hooks_js_namespaceObject.useAssociationFieldContext)();
    const { collectionName } = (0, external_index_js_namespaceObject_1.useFormBlockContext)();
    const compile = (0, index_js_namespaceObject.useCompile)();
    const labelUiSchema = (0, external_util_js_namespaceObject.useLabelUiSchema)(collectionField, (null == fieldNames ? void 0 : fieldNames.label) || 'label');
    const isAllowAddNew = fieldSchema['x-add-new'];
    const [selectedRows, setSelectedRows] = (0, external_react_namespaceObject.useState)([]);
    const recordData = (0, external_index_js_namespaceObject_1.useCollectionRecordData)();
    const options = (0, external_react_namespaceObject.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, external_util_js_namespaceObject.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, external_index_js_namespaceObject.useActionContext)();
        const { multiple, selectedRows, onChange, options, collectionField } = (0, external_react_namespaceObject.useContext)(external_index_js_namespaceObject.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);
            },
            style: {
                display: false !== multiple && [
                    'o2m',
                    'm2m'
                ].includes(null == collectionField ? void 0 : collectionField.interface) ? 'block' : 'none'
            }
        };
    };
    return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)(jsx_runtime_namespaceObject.Fragment, {
        children: [
            /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)(external_antd_namespaceObject.Space.Compact, {
                style: {
                    display: 'flex',
                    lineHeight: '32px'
                },
                children: [
                    /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
                        style: {
                            width: '100%'
                        },
                        children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(external_antd_namespaceObject.Select, {
                            role: "button",
                            "data-testid": "select-data-picker",
                            style: {
                                width: '100%'
                            },
                            popupMatchSelectWidth: false,
                            ...others,
                            mode: multiple ? 'multiple' : props.mode,
                            fieldNames: fieldNames,
                            onDropdownVisibleChange: (open)=>{
                                insertSelector(external_schema_js_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, jsx_runtime_namespaceObject.jsx)(external_index_js_namespaceObject_1.RecordProvider, {
                        isNew: true,
                        record: null,
                        parent: recordData,
                        children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(schema_namespaceObject.RecursionField, {
                            onlyRenderProperties: true,
                            basePath: field.address,
                            schema: fieldSchema,
                            filterProperties: (s)=>'Action' === s['x-component']
                        })
                    })
                ]
            }),
            /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(external_action_index_js_namespaceObject.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, jsx_runtime_namespaceObject.jsx)(external_index_js_namespaceObject.RecordPickerProvider, {
                    ...pickerProps,
                    children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(external_index_js_namespaceObject_1.CollectionProvider_deprecated, {
                        name: null == collectionField ? void 0 : collectionField.target,
                        children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(external_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_index_js_namespaceObject.SchemaComponentOptions, {
                                    scope: {
                                        usePickActionProps,
                                        useTableSelectorProps
                                    },
                                    children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(schema_namespaceObject.RecursionField, {
                                        onlyRenderProperties: true,
                                        basePath: field.address,
                                        schema: fieldSchema,
                                        filterProperties: (s)=>'AssociationField.Selector' === s['x-component']
                                    })
                                })
                            })
                        })
                    })
                })
            })
        ]
    });
}, {
    displayName: 'InternalPicker'
});
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
});
