function _array_like_to_array(arr, len) {
    if (len == null || len > arr.length) len = arr.length;
    for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
    return arr2;
}
function _array_with_holes(arr) {
    if (Array.isArray(arr)) return arr;
}
function _define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}
function _iterable_to_array_limit(arr, i) {
    var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
    if (_i == null) return;
    var _arr = [];
    var _n = true;
    var _d = false;
    var _s, _e;
    try {
        for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
            _arr.push(_s.value);
            if (i && _arr.length === i) break;
        }
    } catch (err) {
        _d = true;
        _e = err;
    } finally{
        try {
            if (!_n && _i["return"] != null) _i["return"]();
        } finally{
            if (_d) throw _e;
        }
    }
    return _arr;
}
function _non_iterable_rest() {
    throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _object_spread(target) {
    for(var i = 1; i < arguments.length; i++){
        var source = arguments[i] != null ? arguments[i] : {};
        var ownKeys = Object.keys(source);
        if (typeof Object.getOwnPropertySymbols === "function") {
            ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
                return Object.getOwnPropertyDescriptor(source, sym).enumerable;
            }));
        }
        ownKeys.forEach(function(key) {
            _define_property(target, key, source[key]);
        });
    }
    return target;
}
function ownKeys(object, enumerableOnly) {
    var keys = Object.keys(object);
    if (Object.getOwnPropertySymbols) {
        var symbols = Object.getOwnPropertySymbols(object);
        if (enumerableOnly) {
            symbols = symbols.filter(function(sym) {
                return Object.getOwnPropertyDescriptor(object, sym).enumerable;
            });
        }
        keys.push.apply(keys, symbols);
    }
    return keys;
}
function _object_spread_props(target, source) {
    source = source != null ? source : {};
    if (Object.getOwnPropertyDescriptors) {
        Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
    } else {
        ownKeys(Object(source)).forEach(function(key) {
            Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
        });
    }
    return target;
}
function _sliced_to_array(arr, i) {
    return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
}
function _unsupported_iterable_to_array(o, minLen) {
    if (!o) return;
    if (typeof o === "string") return _array_like_to_array(o, minLen);
    var n = Object.prototype.toString.call(o).slice(8, -1);
    if (n === "Object" && o.constructor) n = o.constructor.name;
    if (n === "Map" || n === "Set") return Array.from(n);
    if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
}
import { FileFolders } from "@sofa-design/icons";
import { ConfigProvider, Empty, Tree } from "antd";
import classNames from "clsx";
import React, { useCallback, useContext, useEffect, useMemo, useState } from "react";
import { useRefFunction } from "../../../Hooks/useRefFunction";
import { I18nContext } from "../../../I18n";
import { getFileType } from "../../types";
import { getFileTypeIcon } from "../utils";
import { useFileTreeStyle } from "./style";
var walkAndIndex = function walkAndIndex1(nodes, map) {
    var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
    try {
        for(var _iterator = nodes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
            var n = _step.value;
            var _n_children;
            map.set(n.key, n);
            if ((_n_children = n.children) === null || _n_children === void 0 ? void 0 : _n_children.length) {
                walkAndIndex(n.children, map);
            }
        }
    } catch (err) {
        _didIteratorError = true;
        _iteratorError = err;
    } finally{
        try {
            if (!_iteratorNormalCompletion && _iterator.return != null) {
                _iterator.return();
            }
        } finally{
            if (_didIteratorError) {
                throw _iteratorError;
            }
        }
    }
};
var toDataNode = function toDataNode1(node) {
    var key = node.key, name = node.name, isLeaf = node.isLeaf, disabled = node.disabled, children = node.children;
    var hasChildren = Boolean(children && children.length > 0);
    // `isLeaf: false` = 目录；未传时：有子节点 = 目录，无子节点 = 视为文件（与懒加载目录需显式 `isLeaf: false` 一致）
    var resolvedIsLeaf = isLeaf !== null && isLeaf !== void 0 ? isLeaf : !hasChildren;
    if (resolvedIsLeaf) {
        return {
            key: key,
            title: name,
            isLeaf: true,
            disabled: disabled
        };
    }
    return {
        key: key,
        title: name,
        isLeaf: false,
        disabled: disabled,
        children: hasChildren ? children.map(toDataNode) : []
    };
};
var replaceNodeChildren = function replaceNodeChildren1(nodes, key, newChildren) {
    return nodes.map(function(n) {
        var _n_children;
        if (n.key === key) {
            return _object_spread_props(_object_spread({}, n), {
                children: newChildren
            });
        }
        if ((_n_children = n.children) === null || _n_children === void 0 ? void 0 : _n_children.length) {
            return _object_spread_props(_object_spread({}, n), {
                children: replaceNodeChildren(n.children, key, newChildren)
            });
        }
        return n;
    });
};
var buildMap = function buildMap(nodes) {
    var m = new Map();
    walkAndIndex(nodes, m);
    return m;
};
var FileTreeComponent = function FileTreeComponent(param) {
    var _tab = param.tab, className = param.className, style = param.style, treeData = param.treeData, onLoadChildren = param.onLoadChildren, onSelect = param.onSelect, _param_showLine = param.showLine, showLine = _param_showLine === void 0 ? true : _param_showLine, _resetKey = param.resetKey, emptyRender = param.emptyRender, _param_blockNode = param.blockNode, blockNode = _param_blockNode === void 0 ? true : _param_blockNode;
    var _ref;
    var getPrefixCls = useContext(ConfigProvider.ConfigContext).getPrefixCls;
    var locale = useContext(I18nContext).locale;
    var prefixCls = getPrefixCls('workspace-file-tree');
    var _useFileTreeStyle = useFileTreeStyle(prefixCls), wrapSSR = _useFileTreeStyle.wrapSSR, hashId = _useFileTreeStyle.hashId;
    var _useState = _sliced_to_array(useState(treeData), 2), innerTree = _useState[0], setInnerTree = _useState[1];
    var nodeMap = useMemo(function() {
        return buildMap(innerTree);
    }, [
        innerTree
    ]);
    var onLoadChildrenRef = useRefFunction(onLoadChildren);
    useEffect(function() {
        setInnerTree(treeData);
    }, [
        treeData
    ]);
    var dataNodes = useMemo(function() {
        return innerTree.map(toDataNode);
    }, [
        innerTree
    ]);
    var handleLoadData = useCallback(function(treeNode) {
        var k = String(treeNode.key);
        var source = nodeMap.get(k);
        if (!source) {
            return Promise.resolve();
        }
        if (source.isLeaf === true) {
            return Promise.resolve();
        }
        if (source.isLeaf === undefined && (!source.children || source.children.length === 0)) {
            return Promise.resolve();
        }
        if (source.children && source.children.length > 0) {
            return Promise.resolve();
        }
        // 须让 `Promise` 在失败时 reject，以便 rc-tree 不将 key 记为已加载，从而可再次展开重试
        return Promise.resolve(onLoadChildrenRef(source)).then(function(loaded) {
            var children = loaded !== null && loaded !== void 0 ? loaded : [];
            setInnerTree(function(prev) {
                return replaceNodeChildren(prev, k, children);
            });
        }).catch(function(error) {
            console.error('Failed to load tree children:', error);
            // 返回 reject 以便 rc-tree 不将 key 记为已加载，允许重试
            throw error;
        });
    }, [
        onLoadChildrenRef,
        nodeMap
    ]);
    var handleSelect = useCallback(function(_keys, info) {
        if (!onSelect) return;
        if (!info.selected) return;
        var k = String(info.node.key);
        var n = nodeMap.get(k);
        if (n) onSelect(n);
    }, [
        nodeMap,
        onSelect
    ]);
    var handleTreeIcon = useCallback(function(iconProps) {
        var k = String(iconProps.eventKey);
        var n = nodeMap.get(k);
        if (n === null || n === void 0 ? void 0 : n.icon) {
            return /*#__PURE__*/ React.createElement("span", {
                className: classNames("".concat(prefixCls, "-icon"), hashId)
            }, n.icon);
        }
        if (iconProps.isLeaf) {
            var _ref;
            var fileName = (_ref = n === null || n === void 0 ? void 0 : n.name) !== null && _ref !== void 0 ? _ref : '';
            var fileType = getFileType(fileName);
            return /*#__PURE__*/ React.createElement("span", {
                className: classNames("".concat(prefixCls, "-icon"), hashId),
                "aria-hidden": true
            }, getFileTypeIcon(fileType, undefined, fileName));
        }
        return /*#__PURE__*/ React.createElement("span", {
            className: classNames("".concat(prefixCls, "-icon"), "".concat(prefixCls, "-icon--folder"), hashId),
            "aria-hidden": true
        }, /*#__PURE__*/ React.createElement(FileFolders, null));
    }, [
        hashId,
        nodeMap,
        prefixCls
    ]);
    var showEmpty = innerTree.length === 0;
    var emptyNode = typeof emptyRender === 'function' ? emptyRender() : emptyRender;
    var defaultEmpty = /*#__PURE__*/ React.createElement(Empty, {
        image: Empty.PRESENTED_IMAGE_SIMPLE,
        description: (_ref = locale === null || locale === void 0 ? void 0 : locale['workspace.empty']) !== null && _ref !== void 0 ? _ref : '暂无数据'
    });
    return wrapSSR(/*#__PURE__*/ React.createElement("div", {
        className: classNames(prefixCls, hashId, className),
        style: style,
        "data-testid": "workspace-file-tree"
    }, showEmpty ? emptyNode !== null && emptyNode !== void 0 ? emptyNode : defaultEmpty : /*#__PURE__*/ React.createElement(Tree, {
        className: classNames("".concat(prefixCls, "-tree"), hashId),
        showLine: showLine,
        showIcon: true,
        blockNode: blockNode,
        loadData: handleLoadData,
        onSelect: handleSelect,
        treeData: dataNodes,
        icon: handleTreeIcon
    })));
};
FileTreeComponent.displayName = 'FileTree';
export { FileTreeComponent as FileTree };
