"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__, {
    ObservableItem: ()=>ObservableItem,
    InternalTabs: ()=>InternalTabs,
    InternalCollapse: ()=>InternalCollapse
});
const jsx_runtime_namespaceObject = require("react/jsx-runtime");
const external_react_namespaceObject = require("react");
const schema_namespaceObject = require("@tachybase/schema");
const client_namespaceObject = require("@tachybase/utils/client");
const icons_namespaceObject = require("@ant-design/icons");
const external_ahooks_namespaceObject = require("ahooks");
const external_antd_namespaceObject = require("antd");
const external_flat_namespaceObject = require("flat");
var external_flat_default = /*#__PURE__*/ __webpack_require__.n(external_flat_namespaceObject);
const external_react_i18next_namespaceObject = require("react-i18next");
const external_react_intersection_observer_namespaceObject = require("react-intersection-observer");
const index_js_namespaceObject = require("../../../../api-client/index.js");
const external_data_source_index_js_namespaceObject = require("../../../../data-source/index.js");
const isNewRecord_js_namespaceObject = require("../../../../data-source/collection-record/isNewRecord.js");
const external_hooks_js_namespaceObject = require("../hooks.js");
const external_hook_js_namespaceObject = require("./hook.js");
const external_styles_js_namespaceObject = require("./styles.js");
const ObservableItem = (param)=>{
    let { item, onChange, leftRef } = param;
    var _item_childrenItems;
    const { ref } = (0, external_react_intersection_observer_namespaceObject.useInView)({
        threshold: 0.1,
        onChange: (inView)=>{
            if (inView && leftRef.current) {
                const currentId = '#parent-item-' + item.id;
                leftRef.current.querySelector(currentId).scrollIntoView({
                    behavior: 'auto',
                    block: 'nearest',
                    inline: 'start'
                });
            }
        }
    });
    return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
        id: 'item-' + item.id,
        ref: ref,
        children: null == item ? void 0 : null === (_item_childrenItems = item.childrenItems) || void 0 === _item_childrenItems ? void 0 : _item_childrenItems.sort((a, b)=>null != a.sort ? a.sort - b.sort : a.id - b.id).map((childrenitem, index)=>/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(external_antd_namespaceObject.Button, {
                onClick: ()=>{
                    onChange(childrenitem);
                },
                icon: childrenitem.checked ? /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(icons_namespaceObject.CheckOutlined, {}) : null,
                children: childrenitem.label
            }, index))
    }, item.id);
};
const InternalTabs = (0, schema_namespaceObject.observer)((props)=>{
    var _fieldSchema_parent_xcomponentprops, _quickAddSchema_xcomponentprops_service, _quickAddSchema_xcomponentprops, _Object_values;
    const ref = (0, external_react_namespaceObject.useRef)();
    const { styles } = (0, external_styles_js_namespaceObject.useStyles)();
    const { fieldValue, setFieldValue } = props;
    const fieldSchema = (0, schema_namespaceObject.useFieldSchema)();
    const cm = (0, external_data_source_index_js_namespaceObject.useCollectionManager)();
    const api = (0, index_js_namespaceObject.useAPIClient)();
    const [filter, setFilter] = (0, external_react_namespaceObject.useState)('');
    const isQuickAdd = fieldSchema['parent']['x-component-props']['isQuickAdd'];
    const { value: quickAddField, fieldInterface } = (null === (_fieldSchema_parent_xcomponentprops = fieldSchema['parent']['x-component-props']) || void 0 === _fieldSchema_parent_xcomponentprops ? void 0 : _fieldSchema_parent_xcomponentprops['quickAddField']) || {};
    const quickAddParentField = fieldSchema['parent']['x-component-props']['quickAddParentCollection'];
    const [defOptions, setDefOptions] = (0, external_react_namespaceObject.useState)([]);
    const { field } = (0, external_hooks_js_namespaceObject.useAssociationFieldContext)();
    const { t } = (0, external_react_i18next_namespaceObject.useTranslation)();
    const [changeForm, setChangeForm] = (0, external_react_namespaceObject.useState)();
    const quickAddSchema = fieldSchema.reduceProperties((buf, schema)=>{
        const found = schema.reduceProperties((buf, schema)=>{
            if (schema.name === quickAddField) return schema;
            return buf;
        });
        if (found) return found;
        return buf;
    }, new schema_namespaceObject.Schema({}));
    const tabparams = null === (_quickAddSchema_xcomponentprops = quickAddSchema['x-component-props']) || void 0 === _quickAddSchema_xcomponentprops ? void 0 : null === (_quickAddSchema_xcomponentprops_service = _quickAddSchema_xcomponentprops['service']) || void 0 === _quickAddSchema_xcomponentprops_service ? void 0 : _quickAddSchema_xcomponentprops_service['params'];
    const [fieldServiceFilter] = (0, external_hook_js_namespaceObject.useFieldServiceFilter)(null == tabparams ? void 0 : tabparams.filter);
    const formFilter = external_flat_default()((null == tabparams ? void 0 : tabparams.filter) || {});
    const formFieldFilter = null === (_Object_values = Object.values(formFilter)) || void 0 === _Object_values ? void 0 : _Object_values.map((item)=>{
        const field = item;
        const match = field.match(/^{{\$nForm\.(.*?)\./);
        if (match) return match[1];
    }).filter(Boolean);
    (0, external_ahooks_namespaceObject.useAsyncEffect)(async ()=>{
        const itemParams = {};
        const optionsItem = [];
        if ((null == tabparams ? void 0 : tabparams.filter) && !fieldServiceFilter) return;
        if ((quickAddField || 'none' !== quickAddField || !isQuickAdd) && fieldSchema.properties) {
            const params = {
                pageSize: 99999,
                filter: JSON.stringify(fieldServiceFilter)
            };
            if (quickAddParentField && (null == quickAddParentField ? void 0 : quickAddParentField.value) !== 'none') {
                var _parentItem_data;
                params['appends'] = [
                    quickAddParentField.value
                ];
                const collection = cm.getCollection(quickAddParentField.collectionField);
                const parentItem = await api.request({
                    url: collection.name + ':list',
                    params: {
                        pageSize: 99999
                    }
                });
                itemParams['parentTitleField'] = collection.titleField;
                itemParams['parentOptions'] = null == parentItem ? void 0 : null === (_parentItem_data = parentItem.data) || void 0 === _parentItem_data ? void 0 : _parentItem_data.data;
            }
            if (quickAddSchema && 'm2o' === fieldInterface) {
                var _childrenItem_data, _itemParams_parentOptions, _itemParams_childrenOptions, _itemParams_childrenOptions1;
                itemParams['service'] = quickAddSchema['x-component-props'].service;
                itemParams['collectionName'] = cm.getCollection(quickAddSchema['x-collection-field']).name;
                const childrenItem = await api.request({
                    url: itemParams['collectionName'] + ':list',
                    params
                });
                itemParams['childrenTitleField'] = cm.getCollection(itemParams['collectionName']).titleField;
                itemParams['childrenOptions'] = null == childrenItem ? void 0 : null === (_childrenItem_data = childrenItem.data) || void 0 === _childrenItem_data ? void 0 : _childrenItem_data.data;
                if ((null === (_itemParams_parentOptions = itemParams['parentOptions']) || void 0 === _itemParams_parentOptions ? void 0 : _itemParams_parentOptions.length) && (null === (_itemParams_childrenOptions = itemParams['childrenOptions']) || void 0 === _itemParams_childrenOptions ? void 0 : _itemParams_childrenOptions.length) && (null == quickAddParentField ? void 0 : quickAddParentField.value) !== 'none') itemParams['parentOptions'].forEach((parentItem)=>{
                    const items = itemParams['childrenOptions'].map((item)=>{
                        var _item_quickAddParentField_value;
                        if ((null === (_item_quickAddParentField_value = item[null == quickAddParentField ? void 0 : quickAddParentField.value]) || void 0 === _item_quickAddParentField_value ? void 0 : _item_quickAddParentField_value.id) === parentItem.id) return {
                            ...item,
                            label: item[itemParams['childrenTitleField']],
                            keys: item.id,
                            value: item.id,
                            checked: false
                        };
                    }).filter(Boolean);
                    if (!items.length) return;
                    optionsItem.push({
                        ...parentItem,
                        value: null == parentItem ? void 0 : parentItem.id,
                        label: parentItem[itemParams['parentTitleField']],
                        key: parentItem.id,
                        childrenItems: items
                    });
                });
                else if ((null === (_itemParams_childrenOptions1 = itemParams['childrenOptions']) || void 0 === _itemParams_childrenOptions1 ? void 0 : _itemParams_childrenOptions1.length) && (!quickAddParentField || (null == quickAddParentField ? void 0 : quickAddParentField.value) === 'none')) itemParams['childrenOptions'].forEach((item)=>{
                    optionsItem.push({
                        ...item,
                        label: item[itemParams['childrenTitleField']],
                        value: null == item ? void 0 : item.id,
                        key: null == item ? void 0 : item.id,
                        checked: false
                    });
                });
                setDefOptions(optionsItem);
            } else if (quickAddSchema) {
                const fieldItem = cm.getCollectionField(quickAddSchema['x-collection-field']);
                if (!(null == fieldItem ? void 0 : fieldItem.uiSchema) || !(null == fieldItem ? void 0 : fieldItem.uiSchema.enum)) return;
                fieldItem.uiSchema.enum.forEach((item)=>{
                    optionsItem.push(item);
                });
                setDefOptions(optionsItem);
            }
        }
    }, [
        fieldServiceFilter,
        null == tabparams ? void 0 : tabparams.filter,
        changeForm,
        isQuickAdd,
        quickAddField,
        quickAddParentField
    ]);
    (0, external_ahooks_namespaceObject.useDeepCompareEffect)(()=>{
        if (!defOptions.length) return;
        const fieldTabs = field.value;
        if (quickAddParentField && (null == quickAddParentField ? void 0 : quickAddParentField.value) !== 'none') {
            const filterParantOptions = tabsParantFilterOptions(defOptions, fieldTabs, quickAddField);
            setDefOptions(filterParantOptions);
        } else {
            const filterDefOptions = tabsFilterOptions(defOptions, fieldTabs, quickAddField);
            setDefOptions(filterDefOptions);
        }
    }, [
        quickAddField,
        fieldValue
    ]);
    (0, schema_namespaceObject.useFormEffects)(()=>{
        (0, schema_namespaceObject.onFieldChange)(formFieldFilter, (field)=>{
            setChangeForm(field);
        });
    });
    let options = defOptions;
    if (quickAddParentField && 'none' !== quickAddParentField.value) {
        const filterOption = null == defOptions ? void 0 : defOptions.map((item)=>{
            var _item_childrenItems;
            const filterItem = null == item ? void 0 : null === (_item_childrenItems = item.childrenItems) || void 0 === _item_childrenItems ? void 0 : _item_childrenItems.filter((childrenItem)=>(0, client_namespaceObject.fuzzysearch)(filter, null == childrenItem ? void 0 : childrenItem.label));
            if ((0, client_namespaceObject.fuzzysearch)(filter, null == item ? void 0 : item.label) || (null == filterItem ? void 0 : filterItem.length)) return {
                ...item,
                childrenItems: (null == filterItem ? void 0 : filterItem.length) ? filterItem : item.childrenItems
            };
        }).filter(Boolean);
        options = filterOption;
    } else {
        const filterOption = defOptions.filter((item)=>(0, client_namespaceObject.fuzzysearch)(filter, null == item ? void 0 : item.label));
        options = filterOption;
    }
    const onChange = (item)=>{
        field.value = field.value || [];
        const addItem = {};
        addItem[quickAddField] = item;
        field.value.push((0, isNewRecord_js_namespaceObject.markRecordAsNew)(addItem));
        setFieldValue([
            ...field.value
        ]);
    };
    return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("div", {
        children: [
            /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(external_antd_namespaceObject.Input, {
                placeholder: t('Please enter search content'),
                prefix: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(icons_namespaceObject.SearchOutlined, {}),
                value: filter,
                onChange: (e)=>{
                    setFilter(e.target.value);
                }
            }),
            quickAddParentField && (null == quickAddParentField ? void 0 : quickAddParentField.value) !== 'none' ? /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("div", {
                className: styles.container,
                ref: ref,
                children: [
                    /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
                        className: "left-pane",
                        children: options.sort((a, b)=>null != a.sort ? a.sort - b.sort : a.id - b.id).map((item)=>/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
                                id: 'parent-item-' + item.id,
                                onClick: ()=>{
                                    var _ref_current;
                                    null === (_ref_current = ref.current) || void 0 === _ref_current || _ref_current.querySelector('#item-' + item.id).scrollIntoView({
                                        behavior: 'auto',
                                        block: 'nearest',
                                        inline: 'start'
                                    });
                                    const currentId = '#parent-item-' + item.id;
                                    ref.current.querySelector(currentId).scrollIntoView({
                                        behavior: 'auto',
                                        block: 'nearest',
                                        inline: 'start'
                                    });
                                    ref.current.querySelector(currentId).style.color = '#166cff';
                                    const allElements = ref.current.querySelectorAll('div:not(' + currentId + ')');
                                    null == allElements || allElements.forEach(function(element) {
                                        element.style.color = '#1e1e1e';
                                    });
                                },
                                children: item.label
                            }, item.id))
                    }),
                    /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
                        className: "right-pane",
                        children: options.sort((a, b)=>null != a.sort ? a.sort - b.sort : a.id - b.id).map((item)=>/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(ObservableItem, {
                                item: item,
                                onChange: onChange,
                                leftRef: ref
                            }, item.id))
                    })
                ]
            }) : /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(external_antd_namespaceObject.Space, {
                style: {
                    maxHeight: '30vh',
                    overflow: 'auto',
                    padding: '10px'
                },
                children: options.map((item, index)=>/*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(external_antd_namespaceObject.Button, {
                        onClick: ()=>{
                            onChange(item);
                        },
                        icon: item.checked ? /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(icons_namespaceObject.CheckOutlined, {}) : null,
                        children: item.label
                    }, index))
            })
        ]
    });
});
const tabsParantFilterOptions = (options, fieldTabs, arrayField)=>{
    const filterOptions = null == options ? void 0 : options.map((oItem)=>{
        const filterItem = oItem.childrenItems.map((childrenItem)=>{
            const fieldTabsValue = fieldTabs.find((item)=>{
                var _item_arrayField;
                return (null === (_item_arrayField = item[arrayField]) || void 0 === _item_arrayField ? void 0 : _item_arrayField.value) === childrenItem.value;
            });
            return {
                ...childrenItem,
                checked: !!fieldTabsValue || false
            };
        });
        return {
            ...oItem,
            childrenItems: filterItem
        };
    });
    return filterOptions;
};
const tabsFilterOptions = (optitons, filterTabs, arrayField)=>{
    const filterOptions = optitons.map((item)=>{
        const filterValue = filterTabs.find((filterTabsItem)=>{
            var _filterTabsItem_arrayField;
            return (null === (_filterTabsItem_arrayField = filterTabsItem[arrayField]) || void 0 === _filterTabsItem_arrayField ? void 0 : _filterTabsItem_arrayField.value) === item.value;
        });
        return {
            ...item,
            checked: !!filterValue || false
        };
    });
    return filterOptions;
};
const InternalCollapse = (0, schema_namespaceObject.observer)((props)=>{
    var _fieldSchema_parent_xcomponentprops;
    const { t } = (0, external_react_i18next_namespaceObject.useTranslation)();
    const fieldSchema = (0, schema_namespaceObject.useFieldSchema)();
    const isQuickAdd = fieldSchema['parent']['x-component-props']['isQuickAdd'];
    const { value: quickAddField } = (null === (_fieldSchema_parent_xcomponentprops = fieldSchema['parent']['x-component-props']) || void 0 === _fieldSchema_parent_xcomponentprops ? void 0 : _fieldSchema_parent_xcomponentprops['quickAddField']) || {};
    const items = [
        {
            key: '1',
            label: t('Quick create'),
            children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(InternalTabs, {
                ...props
            })
        }
    ];
    return isQuickAdd && quickAddField && 'none' !== quickAddField ? /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(external_antd_namespaceObject.Collapse, {
        items: items,
        defaultActiveKey: [
            '1'
        ]
    }) : null;
});
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
});
