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 _array_without_holes(arr) {
    if (Array.isArray(arr)) return _array_like_to_array(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(iter) {
    if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
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 _non_iterable_spread() {
    throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
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 _to_consumable_array(arr) {
    return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
}
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 { ChevronUp } from "@sofa-design/icons";
import { ConfigProvider } from "antd";
import classNames from "clsx";
import { useMergedState } from "rc-util";
import React, { memo, useCallback, useContext, useEffect, useMemo, useState } from "react";
import { ActionIconBox } from "../Components/ActionIconBox";
import { TextSwap } from "../Components/TextSwap";
import { useRefFunction } from "../Hooks/useRefFunction";
import { I18nContext } from "../I18n";
import { StatusIcon } from "./components/StatusIcon";
import { TaskListItem } from "./components/TaskListItem";
import { getArrowRotation } from "./constants";
import { useStyle } from "./style";
var SIMPLE_COLLAPSE_DURATION_MS = 350;
var getDefaultExpandedKeys = function getDefaultExpandedKeys(items, isControlled) {
    return isControlled ? [] : items.map(function(item) {
        return item.key;
    });
};
export var TaskList = /*#__PURE__*/ memo(function(param) {
    var items = param.items, className = param.className, expandedKeys = param.expandedKeys, onExpandedKeysChange = param.onExpandedKeysChange, _param_variant = param.variant, variant = _param_variant === void 0 ? 'default' : _param_variant, open = param.open, onOpenChange = param.onOpenChange, taskCompleteText = param.taskCompleteText;
    var getPrefixCls = useContext(ConfigProvider.ConfigContext).getPrefixCls;
    var prefixCls = getPrefixCls('task-list');
    var _useStyle = useStyle(prefixCls), wrapSSR = _useStyle.wrapSSR, hashId = _useStyle.hashId;
    var locale = useContext(I18nContext).locale;
    var isControlled = expandedKeys !== undefined;
    var _useMergedState = _sliced_to_array(useMergedState(getDefaultExpandedKeys(items, isControlled), {
        value: expandedKeys,
        onChange: onExpandedKeysChange
    }), 2), internalExpandedKeys = _useMergedState[0], setInternalExpandedKeys = _useMergedState[1];
    var handleToggle = useRefFunction(function(key) {
        var currentExpanded = isControlled ? expandedKeys : internalExpandedKeys;
        var newExpandedKeys = currentExpanded.includes(key) ? currentExpanded.filter(function(k) {
            return k !== key;
        }) : _to_consumable_array(currentExpanded).concat([
            key
        ]);
        setInternalExpandedKeys(newExpandedKeys);
    });
    var _useMergedState1 = _sliced_to_array(useMergedState(false, {
        value: open,
        onChange: function onChange(val) {
            return onOpenChange === null || onOpenChange === void 0 ? void 0 : onOpenChange(val);
        }
    }), 2), simpleExpanded = _useMergedState1[0], setSimpleExpanded = _useMergedState1[1];
    var _useState = _sliced_to_array(useState(true), 2), shouldRenderContent = _useState[0], setShouldRenderContent = _useState[1];
    var handleSimpleToggle = useRefFunction(function() {
        setSimpleExpanded(function(prev) {
            return !prev;
        });
    });
    useEffect(function() {
        if (simpleExpanded) {
            setShouldRenderContent(true);
            return;
        }
        var timer = window.setTimeout(function() {
            setShouldRenderContent(false);
        }, SIMPLE_COLLAPSE_DURATION_MS);
        return function() {
            window.clearTimeout(timer);
        };
    }, [
        simpleExpanded
    ]);
    var _useMemo = useMemo(function() {
        var completedCount = items.filter(function(i) {
            return i.status === 'success';
        }).length;
        var loadingItem = items.find(function(i) {
            return i.status === 'loading';
        });
        var errorExists = items.some(function(i) {
            return i.status === 'error';
        });
        var allDone = completedCount === items.length && items.length > 0;
        var status = 'pending';
        var text = (locale === null || locale === void 0 ? void 0 : locale['taskList.taskList']) || '任务列表';
        var swapKey = "idle:".concat(items.map(function(i) {
            return "".concat(i.key, ":").concat(i.status);
        }).join('|'));
        if (allDone) {
            var _ref;
            status = 'success';
            var customCompleteText = typeof taskCompleteText === 'function' ? taskCompleteText({
                items: items
            }) : taskCompleteText;
            text = (_ref = customCompleteText !== null && customCompleteText !== void 0 ? customCompleteText : locale === null || locale === void 0 ? void 0 : locale['taskList.taskComplete']) !== null && _ref !== void 0 ? _ref : '任务完成';
            swapKey = "done:".concat(items.map(function(i) {
                return i.key;
            }).join(','));
        } else if (loadingItem === null || loadingItem === void 0 ? void 0 : loadingItem.title) {
            status = 'loading';
            var tpl = (locale === null || locale === void 0 ? void 0 : locale['taskList.taskInProgress']) || '正在进行${taskName}任务';
            var title = loadingItem.title;
            var taskName = typeof title === 'string' || typeof title === 'number' ? String(title) : '';
            text = tpl.replace('${taskName}', taskName);
            swapKey = "loading:".concat(loadingItem.key, ":").concat(taskName);
        } else if (errorExists) {
            status = 'error';
            var tpl1 = (locale === null || locale === void 0 ? void 0 : locale['taskList.taskInProgress']) || '正在进行任务';
            text = tpl1.replace('${taskName}', '');
            swapKey = 'error';
        }
        return {
            summaryStatus: status,
            summaryText: text,
            summarySwapKey: swapKey,
            hasError: errorExists,
            lastItem: items[items.length - 1]
        };
    }, [
        items,
        locale,
        taskCompleteText
    ]), summaryStatus = _useMemo.summaryStatus, summaryText = _useMemo.summaryText, summarySwapKey = _useMemo.summarySwapKey, hasError = _useMemo.hasError, lastItem = _useMemo.lastItem;
    // 注意：此处必须用 useCallback 而非 useRefFunction。
    // renderItems 在父组件渲染期被同步调用（`{renderItems(items)}`），
    // 而 useRefFunction 通过 useLayoutEffect 在 commit 阶段才刷新 ref，
    // 渲染期调用会拿到上一帧的闭包，导致 internalExpandedKeys 等状态用旧值。
    var renderItems = useCallback(function(visibleItems) {
        return visibleItems.map(function(item, index) {
            return /*#__PURE__*/ React.createElement(TaskListItem, {
                key: item.key,
                item: item,
                isLast: index === visibleItems.length - 1,
                prefixCls: prefixCls,
                hashId: hashId,
                expandedKeys: internalExpandedKeys,
                onToggle: handleToggle
            });
        });
    }, [
        prefixCls,
        hashId,
        internalExpandedKeys,
        handleToggle
    ]);
    if (variant !== 'simple') {
        return wrapSSR(/*#__PURE__*/ React.createElement("div", {
            className: className,
            "data-testid": prefixCls
        }, renderItems(items)));
    }
    var simpleCls = "".concat(prefixCls, "-simple");
    var simpleArrowTitle = simpleExpanded ? (locale === null || locale === void 0 ? void 0 : locale['taskList.collapse']) || '收起' : (locale === null || locale === void 0 ? void 0 : locale['taskList.expand']) || '展开';
    var visibleItems = simpleExpanded ? hasError ? items.slice(-1) : items : lastItem ? [
        lastItem
    ] : [];
    return wrapSSR(/*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(simpleCls, "-wrapper"), hashId, className),
        "data-testid": "task-list-simple-wrapper"
    }, /*#__PURE__*/ React.createElement("div", {
        className: classNames(simpleCls, hashId),
        onClick: handleSimpleToggle,
        role: "button",
        tabIndex: 0,
        "aria-expanded": simpleExpanded,
        "aria-label": simpleArrowTitle,
        "data-testid": "task-list-simple-bar"
    }, /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(simpleCls, "-status"), hashId)
    }, /*#__PURE__*/ React.createElement(StatusIcon, {
        status: summaryStatus,
        prefixCls: prefixCls,
        hashId: hashId
    })), /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(simpleCls, "-text"), hashId)
    }, /*#__PURE__*/ React.createElement(TextSwap, {
        swapKey: summarySwapKey
    }, summaryText)), /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(simpleCls, "-arrow"), hashId)
    }, /*#__PURE__*/ React.createElement(ActionIconBox, {
        title: simpleArrowTitle,
        iconStyle: getArrowRotation(!simpleExpanded),
        loading: false,
        onClick: function onClick(e) {
            e.stopPropagation();
            handleSimpleToggle();
        }
    }, /*#__PURE__*/ React.createElement(ChevronUp, {
        "data-testid": "task-list-simple-arrow"
    })))), /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(simpleCls, "-content"), hashId, _define_property({}, "".concat(simpleCls, "-content-expanded"), simpleExpanded))
    }, shouldRenderContent ? /*#__PURE__*/ React.createElement("div", {
        className: classNames("".concat(simpleCls, "-list"), hashId)
    }, renderItems(visibleItems)) : null)));
});
TaskList.displayName = 'TaskList';
