"use strict";
var __webpack_require__ = {};
(()=>{
    __webpack_require__.d = (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 = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
})();
(()=>{
    __webpack_require__.r = (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__, {
    AppendsTreeSelect: ()=>AppendsTreeSelect
});
const jsx_runtime_namespaceObject = require("react/jsx-runtime");
const external_react_namespaceObject = require("react");
const icons_namespaceObject = require("@ant-design/icons");
const external_antd_namespaceObject = require("antd");
const external_react_i18next_namespaceObject = require("react-i18next");
const external_index_js_namespaceObject = require("../../../index.js");
function usePropsCollection(param) {
    let { collection } = param;
    return collection;
}
function loadChildren(option) {
    const result = getCollectionFieldOptions.call(this, option.field.target, option);
    if (result.length) {
        if (!result.some((item)=>isAssociation(item.field))) option.isLeaf = true;
    } else option.isLeaf = true;
    return result;
}
function isAssociation(field) {
    return field.target && field.interface;
}
function trueFilter(field) {
    return true;
}
function getCollectionFieldOptions(collection, parentNode) {
    let options = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : {
        needLeaf: false
    };
    const { needLeaf } = options;
    const [dataSourceName, collectionName] = (0, external_index_js_namespaceObject.parseCollectionName)(collection);
    const rawFields = this.getCollectionFields(collectionName, dataSourceName);
    const fields = needLeaf ? rawFields : rawFields.filter(isAssociation);
    const boundLoadChildren = loadChildren.bind(this);
    return fields.filter(this.filter).map((field)=>{
        var _field_uiSchema;
        const key = parentNode ? "".concat(parentNode.value ? "".concat(parentNode.value, ".") : '').concat(field.name) : field.name;
        var _this_compile;
        const fieldTitle = null != (_this_compile = this.compile(null == (_field_uiSchema = field.uiSchema) ? void 0 : _field_uiSchema.title)) ? _this_compile : field.name;
        const isLeaf = !this.getCollectionFields(field.target).filter(isAssociation).filter(this.filter).length;
        var _parentNode_key;
        return {
            pId: null != (_parentNode_key = null == parentNode ? void 0 : parentNode.key) ? _parentNode_key : null,
            id: key,
            key,
            value: key,
            title: fieldTitle,
            isLeaf,
            loadChildren: isLeaf ? null : boundLoadChildren,
            field,
            fullTitle: parentNode ? [
                ...parentNode.fullTitle,
                fieldTitle
            ] : [
                fieldTitle
            ]
        };
    });
}
const AppendsTreeSelect = (props)=>{
    const { title, value: propsValue, onChange, collection, useCollection = usePropsCollection, filter = trueFilter, rootOption, loadData: propsLoadData, needLeaf = false, ...restProps } = props;
    const compile = (0, external_index_js_namespaceObject.useCompile)();
    const { t } = (0, external_react_i18next_namespaceObject.useTranslation)();
    const [optionsMap, setOptionsMap] = (0, external_react_namespaceObject.useState)({});
    const collectionString = useCollection({
        collection
    });
    const [dataSourceName, collectionName] = (0, external_index_js_namespaceObject.parseCollectionName)(collectionString);
    const { getCollectionFields } = (0, external_index_js_namespaceObject.useCollectionManager_deprecated)(dataSourceName);
    const treeData = Object.values(optionsMap);
    const value = (0, external_react_namespaceObject.useMemo)(()=>{
        if (props.multiple) return (propsValue || []).map((v)=>optionsMap[v]).filter(Boolean);
        return propsValue;
    }, [
        propsValue,
        props.multiple,
        optionsMap
    ]);
    const loadData = (0, external_react_namespaceObject.useCallback)(async (option)=>{
        if (null != propsLoadData) return propsLoadData(option);
        if (!option.isLeaf && option.loadChildren) {
            const children = option.loadChildren(option);
            setOptionsMap((prev)=>children.reduce((result, item)=>Object.assign(result, {
                        [item.value]: item
                    }), {
                    ...prev
                }));
        }
    }, [
        propsLoadData
    ]);
    (0, external_react_namespaceObject.useEffect)(()=>{
        const parentNode = rootOption ? {
            ...rootOption,
            id: rootOption.value,
            key: rootOption.value,
            title: rootOption.label,
            fullTitle: rootOption.label,
            isLeaf: false
        } : null;
        const tData = null === propsLoadData ? [] : getCollectionFieldOptions.call({
            compile,
            getCollectionFields,
            filter
        }, collectionString, parentNode, {
            needLeaf
        });
        const map = tData.reduce((result, item)=>Object.assign(result, {
                [item.value]: item
            }), {});
        if (parentNode) map[parentNode.value] = parentNode;
        setOptionsMap(map);
    }, [
        collectionString,
        rootOption,
        filter,
        propsLoadData
    ]);
    (0, external_react_namespaceObject.useEffect)(()=>{
        const arr = props.multiple ? propsValue : propsValue ? [
            propsValue
        ] : [];
        if (!(null == arr ? void 0 : arr.length) || arr.every((v)=>Boolean(optionsMap[v]))) return;
        const loaded = [];
        arr.forEach((v)=>{
            const paths = v.split('.');
            let option = optionsMap[paths[0]];
            for(let i = 1; i < paths.length; i++){
                if (!option) break;
                const next = paths.slice(0, i + 1).join('.');
                if (optionsMap[next]) {
                    option = optionsMap[next];
                    break;
                }
                if (!option.isLeaf && option.loadChildren) {
                    const children = option.loadChildren(option);
                    if (null == children ? void 0 : children.length) {
                        loaded.push(...children);
                        option = children.find((item)=>item.value === paths.slice(0, i + 1).join('.'));
                    }
                }
            }
        });
        setOptionsMap((prev)=>loaded.reduce((result, item)=>Object.assign(result, {
                    [item.value]: item
                }), {
                ...prev
            }));
    }, [
        propsValue,
        treeData.length,
        props.multiple
    ]);
    const handleChange = (0, external_react_namespaceObject.useCallback)((next)=>{
        if (!props.multiple) return void onChange(next);
        const newValue = next.map((i)=>i.value).filter(Boolean);
        const valueSet = new Set(newValue);
        const delValue = value.find((i)=>!valueSet.has(i.value));
        if (delValue) {
            const prefix = "".concat(delValue.value, ".");
            Object.keys(optionsMap).forEach((key)=>{
                if (key.startsWith(prefix)) valueSet.delete(key);
            });
        } else newValue.forEach((v)=>{
            const paths = v.split('.');
            if (paths.length) for(let i = 1; i <= paths.length; i++)valueSet.add(paths.slice(0, i).join('.'));
        });
        onChange(Array.from(valueSet));
    }, [
        props.multiple,
        value,
        onChange,
        optionsMap
    ]);
    const TreeTag = (0, external_react_namespaceObject.useCallback)((props)=>{
        const { value, onClose, disabled, closable } = props;
        if (!value) return null;
        var _optionsMap_value;
        const { fullTitle } = null != (_optionsMap_value = optionsMap[value]) ? _optionsMap_value : {};
        return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(external_antd_namespaceObject.Tag, {
            closable: closable && !disabled,
            onClose: onClose,
            children: null == fullTitle ? void 0 : fullTitle.join(' / ')
        });
    }, [
        optionsMap
    ]);
    const filteredValue = Array.isArray(value) ? value.filter((i)=>i.value in optionsMap) : value;
    const valueKeys = props.multiple ? propsValue : null != propsValue ? [
        propsValue
    ] : [];
    return /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(external_antd_namespaceObject.TreeSelect, {
        role: "button",
        "data-testid": "select-field".concat(title ? "-".concat(title) : ''),
        value: filteredValue,
        placeholder: t('Select field'),
        showCheckedStrategy: external_antd_namespaceObject.TreeSelect.SHOW_ALL,
        treeDefaultExpandedKeys: valueKeys,
        allowClear: {
            clearIcon: /*#__PURE__*/ (0, jsx_runtime_namespaceObject.jsx)(icons_namespaceObject.CloseCircleFilled, {
                role: "button",
                "aria-label": "icon-close"
            })
        },
        treeCheckStrictly: props.multiple,
        treeCheckable: props.multiple,
        tagRender: TreeTag,
        onChange: handleChange,
        treeDataSimpleMode: true,
        treeData: treeData,
        loadData: loadData,
        ...restProps
    });
};
exports.AppendsTreeSelect = __webpack_exports__.AppendsTreeSelect;
for(var __webpack_i__ in __webpack_exports__)if (-1 === [
    "AppendsTreeSelect"
].indexOf(__webpack_i__)) exports[__webpack_i__] = __webpack_exports__[__webpack_i__];
Object.defineProperty(exports, '__esModule', {
    value: true
});
