"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__, {
    SearchCollections: ()=>SearchCollections,
    useMenuSearch: ()=>useMenuSearch,
    DataBlockInitializer: ()=>DataBlockInitializer
});
const jsx_runtime_namespaceObject = require("react/jsx-runtime");
const external_react_namespaceObject = require("react");
var external_react_default = /*#__PURE__*/ __webpack_require__.n(external_react_namespaceObject);
const icons_namespaceObject = require("@ant-design/icons");
const external_antd_namespaceObject = require("antd");
const external_react_i18next_namespaceObject = require("react-i18next");
const index_js_namespaceObject = require("../../application/index.js");
const external_icon_index_js_namespaceObject = require("../../icon/index.js");
const external_schema_component_index_js_namespaceObject = require("../../schema-component/index.js");
const external_schema_templates_index_js_namespaceObject = require("../../schema-templates/index.js");
const external_utils_js_namespaceObject = require("../utils.js");
const MENU_ITEM_HEIGHT = 40;
const STEP = 15;
const SearchCollections = (param)=>{
    let { value: outValue, onChange } = param;
    const { t } = (0, external_react_i18next_namespaceObject.useTranslation)();
    const [value, setValue] = (0, external_react_namespaceObject.useState)(outValue);
    const inputRef = external_react_default().useRef(null);
    (0, external_react_namespaceObject.useEffect)(()=>{
        setValue(outValue);
    }, [
        outValue
    ]);
    (0, external_react_namespaceObject.useEffect)(()=>{
        inputRef.current.input.focus();
        const observer = new IntersectionObserver((entries)=>{
            if (entries[0].isIntersecting) inputRef.current.input.focus();
        });
        observer.observe(inputRef.current.input);
        return ()=>{
            observer.disconnect();
        };
    }, []);
    return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsxs)("div", {
        style: {
            width: 210
        },
        onClick: (e)=>e.stopPropagation(),
        children: [
            /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(external_antd_namespaceObject.Input, {
                ref: inputRef,
                allowClear: true,
                style: {
                    padding: '0 4px 6px',
                    boxShadow: 'none'
                },
                bordered: false,
                placeholder: t('Search and select collection'),
                value: value,
                onClick: (e)=>{
                    e.stopPropagation();
                },
                onChange: (e)=>{
                    onChange(e.target.value);
                    setValue(e.target.value);
                }
            }),
            /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(external_antd_namespaceObject.Divider, {
                style: {
                    margin: 0
                }
            })
        ]
    });
};
const LoadingItem = (param)=>{
    let { loadMore, maxHeight } = param;
    const spinRef = (0, external_react_namespaceObject.useRef)(null);
    (0, external_react_namespaceObject.useEffect)(()=>{
        const el = spinRef.current;
        if (!el) return;
        let container = el.parentElement;
        while(container && 'UL' !== container.tagName)container = container.parentElement;
        const checkLoadMore = function() {
            if (!container) return;
            if (Math.abs(container.scrollHeight - container.scrollTop - container.clientHeight) <= MENU_ITEM_HEIGHT) loadMore();
        };
        if (container) {
            container.style.height = "".concat(maxHeight - MENU_ITEM_HEIGHT, "px");
            container.style.maxHeight = 'inherit';
            container.style.overflowY = 'scroll';
            container.addEventListener('scroll', checkLoadMore);
        }
        return ()=>{
            if (container) {
                container.removeEventListener('scroll', checkLoadMore);
                delete container.style.height;
            }
        };
    }, [
        loadMore,
        maxHeight
    ]);
    return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
        ref: spinRef,
        onClick: (e)=>e.stopPropagation(),
        children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(external_antd_namespaceObject.Spin, {
            size: "small",
            style: {
                width: '100%'
            }
        })
    });
};
function useMenuSearch(param) {
    let { data, openKeys, showType, hideSearch } = param;
    const [searchValue, setSearchValue] = (0, external_react_namespaceObject.useState)('');
    const [count, setCount] = (0, external_react_namespaceObject.useState)(STEP);
    const isMuliSource = (0, external_react_namespaceObject.useMemo)(()=>data.length > 1, [
        data
    ]);
    const openKey = (0, external_react_namespaceObject.useMemo)(()=>isMuliSource ? null == openKeys ? void 0 : openKeys[1] : (null == openKeys ? void 0 : openKeys.length) > 0, [
        openKeys
    ]);
    (0, external_react_namespaceObject.useEffect)(()=>{
        if (!openKey) setSearchValue('');
    }, [
        openKey
    ]);
    const currentItems = (0, external_react_namespaceObject.useMemo)(()=>{
        var _data_;
        if (isMuliSource) {
            var _data_find;
            if (!openKey) return [];
            return (null === (_data_find = data.find((item)=>(item.key || item.name) === openKey)) || void 0 === _data_find ? void 0 : _data_find.children) || [];
        }
        return (null === (_data_ = data[0]) || void 0 === _data_ ? void 0 : _data_.children) || [];
    }, [
        data,
        isMuliSource,
        openKey
    ]);
    const searchedItems = (0, external_react_namespaceObject.useMemo)(()=>{
        if (!searchValue) return currentItems;
        const lowerSearchValue = searchValue.toLocaleLowerCase();
        return currentItems.filter((item)=>(item.label || item.title) && String(item.label || item.title).toLocaleLowerCase().includes(lowerSearchValue));
    }, [
        searchValue,
        currentItems
    ]);
    const shouldLoadMore = (0, external_react_namespaceObject.useMemo)(()=>searchedItems.length > count, [
        count,
        searchedItems
    ]);
    const limitedSearchedItems = (0, external_react_namespaceObject.useMemo)(()=>searchedItems.slice(0, count), [
        searchedItems,
        count
    ]);
    const resultItems = (0, external_react_namespaceObject.useMemo)(()=>{
        const res = [];
        if (!hideSearch) res.push(Object.assign({
            key: 'search',
            label: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(SearchCollections, {
                value: searchValue,
                onChange: (val)=>{
                    setCount(STEP);
                    setSearchValue(val);
                }
            }),
            onClick (param) {
                let { domEvent } = param;
                domEvent.stopPropagation();
            }
        }, showType ? {
            isMenuType: true
        } : {}));
        if (limitedSearchedItems.length > 0) {
            res.push(...limitedSearchedItems);
            if (shouldLoadMore) res.push(Object.assign({
                key: 'load-more',
                label: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(LoadingItem, {
                    maxHeight: STEP * MENU_ITEM_HEIGHT,
                    loadMore: ()=>{
                        setCount((count)=>count + STEP);
                    }
                })
            }, showType ? {
                isMenuType: true
            } : {}));
        } else res.push(Object.assign({
            key: 'empty',
            style: {
                height: 150
            },
            label: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)("div", {
                onClick: (e)=>e.stopPropagation(),
                children: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(external_antd_namespaceObject.Empty, {
                    image: external_antd_namespaceObject.Empty.PRESENTED_IMAGE_SIMPLE
                })
            })
        }, showType ? {
            isMenuType: true
        } : {}));
        return res;
    }, [
        hideSearch,
        limitedSearchedItems,
        searchValue,
        shouldLoadMore,
        showType
    ]);
    const res = (0, external_react_namespaceObject.useMemo)(()=>{
        if (!isMuliSource) return resultItems;
        return data.map((item)=>{
            if (openKey && item.key === openKey) return {
                ...item,
                children: resultItems
            };
            return {
                ...item,
                children: []
            };
        });
    }, [
        data,
        isMuliSource,
        openKey,
        resultItems
    ]);
    return res;
}
const DataBlockInitializer = (props)=>{
    var _childItems__children;
    const { templateWrap, onCreateBlockSchema, componentType, icon = icons_namespaceObject.TableOutlined, name, title, filter, onlyCurrentDataSource, hideSearch, showAssociationFields, hideChildrenIfSingleCollection, filterDataSource, items: itemsFromProps, fromOthersInPopup, hideOtherRecordsInPopup } = props;
    const { insert, setVisible } = (0, index_js_namespaceObject.useSchemaInitializer)();
    const compile = (0, external_schema_component_index_js_namespaceObject.useCompile)();
    const { getTemplateSchemaByMode } = (0, external_schema_templates_index_js_namespaceObject.useSchemaTemplateManager)();
    const onClick = (0, external_react_namespaceObject.useCallback)(async (param)=>{
        let { item } = param;
        if (item.template) {
            const s = await getTemplateSchemaByMode(item);
            templateWrap ? insert(templateWrap(s, {
                item,
                fromOthersInPopup
            })) : insert(s);
        } else if (onCreateBlockSchema) onCreateBlockSchema({
            item,
            fromOthersInPopup
        });
        setVisible(false);
    }, [
        fromOthersInPopup,
        getTemplateSchemaByMode,
        insert,
        onCreateBlockSchema,
        setVisible,
        templateWrap
    ]);
    const items = itemsFromProps || (0, external_utils_js_namespaceObject.useCollectionDataSourceItems)({
        componentName: componentType,
        filter,
        filterDataSource,
        onlyCurrentDataSource,
        showAssociationFields,
        dataBlockInitializerProps: props,
        hideOtherRecordsInPopup
    });
    const getMenuItems = (0, index_js_namespaceObject.useGetSchemaInitializerMenuItems)(onClick);
    const childItems = (0, external_react_namespaceObject.useMemo)(()=>getMenuItems(items, name), [
        getMenuItems,
        items,
        name
    ]);
    const [openMenuKeys, setOpenMenuKeys] = (0, external_react_namespaceObject.useState)([]);
    const searchedChildren = useMenuSearch({
        data: childItems,
        openKeys: openMenuKeys,
        hideSearch
    });
    const compiledMenuItems = (0, external_react_namespaceObject.useMemo)(()=>{
        let children = searchedChildren.filter((item)=>'search' !== item.key && 'empty' !== item.key);
        children = hideChildrenIfSingleCollection && 1 === children.length ? children[0].children : searchedChildren;
        return [
            {
                key: name,
                label: compile(title),
                icon: 'string' == typeof icon ? /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(external_icon_index_js_namespaceObject.Icon, {
                    type: icon
                }) : icon,
                onClick: (info)=>{
                    if (info.key !== name) return;
                    onClick({
                        ...info,
                        item: props
                    });
                },
                children
            }
        ];
    }, [
        searchedChildren,
        hideChildrenIfSingleCollection,
        name,
        compile,
        title,
        icon,
        onClick,
        props
    ]);
    if (childItems.length > 1 || 1 === childItems.length && (null === (_childItems__children = childItems[0].children) || void 0 === _childItems__children ? void 0 : _childItems__children.length) > 0) return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(index_js_namespaceObject.SchemaInitializerMenu, {
        onOpenChange: (keys)=>{
            setOpenMenuKeys(keys);
        },
        items: compiledMenuItems
    });
    return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(index_js_namespaceObject.SchemaInitializerItem, {
        ...props,
        onClick: onClick
    });
};
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
});
