import * as __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__ from "react/jsx-runtime";
import * as __WEBPACK_EXTERNAL_MODULE_react__ from "react";
import * as __WEBPACK_EXTERNAL_MODULE__ant_design_icons__ from "@ant-design/icons";
import * as __WEBPACK_EXTERNAL_MODULE_antd__ from "antd";
import * as __WEBPACK_EXTERNAL_MODULE_react_i18next__ from "react-i18next";
import * as __WEBPACK_EXTERNAL_MODULE__index_mjs__ from "../../../index.mjs";
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, __WEBPACK_EXTERNAL_MODULE__index_mjs__.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 ? void 0 : _field_uiSchema.title)) && void 0 !== _this_compile ? _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) && 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 AppendsTreeSelectV2 = (props)=>{
    const { title, value: propsValue, onChange, collection, useCollection = usePropsCollection, filter = trueFilter, rootOption, loadData: propsLoadData, needLeaf = false, ...restProps } = props;
    const compile = (0, __WEBPACK_EXTERNAL_MODULE__index_mjs__.useCompile)();
    const { t } = (0, __WEBPACK_EXTERNAL_MODULE_react_i18next__.useTranslation)();
    const [optionsMap, setOptionsMap] = (0, __WEBPACK_EXTERNAL_MODULE_react__.useState)({});
    const collectionString = useCollection({
        collection
    });
    const [dataSourceName, collectionName] = (0, __WEBPACK_EXTERNAL_MODULE__index_mjs__.parseCollectionName)(collectionString);
    const { getCollectionFields } = (0, __WEBPACK_EXTERNAL_MODULE__index_mjs__.useCollectionManager_deprecated)(dataSourceName);
    const treeData = Object.values(optionsMap);
    const value = (0, __WEBPACK_EXTERNAL_MODULE_react__.useMemo)(()=>{
        if (props.multiple) return (propsValue || []).map((v)=>optionsMap[v]).filter(Boolean);
        return propsValue;
    }, [
        propsValue,
        props.multiple,
        optionsMap
    ]);
    const loadData = (0, __WEBPACK_EXTERNAL_MODULE_react__.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, __WEBPACK_EXTERNAL_MODULE_react__.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, __WEBPACK_EXTERNAL_MODULE_react__.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, __WEBPACK_EXTERNAL_MODULE_react__.useCallback)((next)=>{
        if (!props.multiple) {
            onChange(next);
            return;
        }
        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, __WEBPACK_EXTERNAL_MODULE_react__.useCallback)((props)=>{
        const { value, onClose, disabled, closable } = props;
        if (!value) return null;
        var _optionsMap_value;
        const { fullTitle } = null !== (_optionsMap_value = optionsMap[value]) && void 0 !== _optionsMap_value ? _optionsMap_value : {};
        return /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.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, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE_antd__.TreeSelect, {
        "data-testid": "select-field".concat(title ? "-".concat(title) : ''),
        value: filteredValue,
        placeholder: t('Select field'),
        showCheckedStrategy: __WEBPACK_EXTERNAL_MODULE_antd__.TreeSelect.SHOW_ALL,
        treeDefaultExpandedKeys: valueKeys,
        allowClear: {
            clearIcon: /*#__PURE__*/ (0, __WEBPACK_EXTERNAL_MODULE_react_jsx_runtime__.jsx)(__WEBPACK_EXTERNAL_MODULE__ant_design_icons__.CloseCircleFilled, {
                role: "button",
                "aria-label": "icon-close"
            })
        },
        treeCheckStrictly: props.multiple,
        treeCheckable: props.multiple,
        tagRender: TreeTag,
        onChange: handleChange,
        treeDataSimpleMode: true,
        treeData: treeData,
        loadData: loadData,
        ...restProps
    });
};
export { AppendsTreeSelectV2 };
