function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
    try {
        var info = gen[key](arg);
        var value = info.value;
    } catch (error) {
        reject(error);
        return;
    }
    if (info.done) {
        resolve(value);
    } else {
        Promise.resolve(value).then(_next, _throw);
    }
}
function _async_to_generator(fn) {
    return function() {
        var self = this, args = arguments;
        return new Promise(function(resolve, reject) {
            var gen = fn.apply(self, args);
            function _next(value) {
                asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
            }
            function _throw(err) {
                asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
            }
            _next(undefined);
        });
    };
}
function _ts_generator(thisArg, body) {
    var f, y, t, _ = {
        label: 0,
        sent: function() {
            if (t[0] & 1) throw t[1];
            return t[1];
        },
        trys: [],
        ops: []
    }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
    return d(g, "next", {
        value: verb(0)
    }), d(g, "throw", {
        value: verb(1)
    }), d(g, "return", {
        value: verb(2)
    }), typeof Symbol === "function" && d(g, Symbol.iterator, {
        value: function() {
            return this;
        }
    }), g;
    function verb(n) {
        return function(v) {
            return step([
                n,
                v
            ]);
        };
    }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while(g && (g = 0, op[0] && (_ = 0)), _)try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [
                op[0] & 2,
                t.value
            ];
            switch(op[0]){
                case 0:
                case 1:
                    t = op;
                    break;
                case 4:
                    _.label++;
                    return {
                        value: op[1],
                        done: false
                    };
                case 5:
                    _.label++;
                    y = op[1];
                    op = [
                        0
                    ];
                    continue;
                case 7:
                    op = _.ops.pop();
                    _.trys.pop();
                    continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
                        _ = 0;
                        continue;
                    }
                    if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
                        _.label = op[1];
                        break;
                    }
                    if (op[0] === 6 && _.label < t[1]) {
                        _.label = t[1];
                        t = op;
                        break;
                    }
                    if (t && _.label < t[2]) {
                        _.label = t[2];
                        _.ops.push(op);
                        break;
                    }
                    if (t[2]) _.ops.pop();
                    _.trys.pop();
                    continue;
            }
            op = body.call(thisArg, _);
        } catch (e) {
            op = [
                6,
                e
            ];
            y = 0;
        } finally{
            f = t = 0;
        }
        if (op[0] & 5) throw op[1];
        return {
            value: op[0] ? op[1] : void 0,
            done: true
        };
    }
}
import { HistoryOutlined } from "@ant-design/icons";
import { ConfigProvider, Popover } from "antd";
import classNames from "clsx";
import React, { memo, useContext, useMemo, useRef } from "react";
import useClickAway from "../Hooks/useClickAway";
import { ActionIconBox, I18nContext } from "../index";
import { HistoryEmpty, HistoryLoadMore, HistoryNewChat, HistorySearch, generateHistoryItems } from "./components";
import { useHistory } from "./hooks/useHistory";
import GroupMenu from "./menu";
import { useStyle } from "./style";
export * from "./components";
export * from "./hooks/useHistory";
export * from "./types";
export * from "./types/HistoryData";
export * from "./utils";
/**
 * History 组件 - 用于显示和管理聊天历史记录
 *
 * @component
 * @param {Object} props - 组件属性
 * @param {string} props.agentId - 代理ID，用于获取历史记录
 * @param {string} props.sessionId - 会话ID，变更时会触发数据重新获取
 * @param {Function} props.request - 请求函数，用于获取历史数据
 * @param {Function} [props.onInit] - 组件初始化时的回调函数
 * @param {Function} [props.onShow] - 组件显示时的回调函数
 * @param {Function} [props.onSelected] - (已废弃，请使用 onClick) 选择历史记录项时的回调函数
 * @param {Function} [props.onClick] - 点击历史记录项时的回调函数
 * @param {Function} [props.onDeleteItem] - 删除历史记录项时的回调函数
 * @param {Function} [props.customDateFormatter] - 日期格式化函数
 * @param {boolean} [props.standalone] - 是否以独立模式显示，为true时直接显示菜单，否则显示为下拉菜单
 * @param {Function} [props.emptyRender] - 空状态渲染函数，当历史记录为空时显示自定义内容
 * @param {Function} [props.loadMoreRender] - 加载更多渲染函数, 用于自定义加载更多按钮的显示内容
 * @param {boolean} [props.loading] - 加载状态，显示在 GroupMenu 区域
 *
 * @returns {React.ReactElement|null} 返回历史记录组件或null（当没有历史记录时）
 *
 * @description
 * 该组件提供两种显示模式：
 * 1. 独立模式 (standalone=true)：直接显示为菜单列表
 * 2. 下拉菜单模式 (standalone=false)：显示为一个可点击的图标，点击后显示下拉菜单
 *
 * 历史记录按日期分组显示，每组内按时间倒序排列。
 * 支持查看历史会话和删除历史记录。
 * 当历史记录为空时，可通过 emptyRender 自定义空状态显示。
 * 通过 loading 属性可以在 GroupMenu 区域显示加载动画。
 */ var HistoryComponent = function HistoryComponent(props) {
    var _props_agent, _props_agent1, _props_agent2;
    var getPrefixCls = useContext(ConfigProvider.ConfigContext).getPrefixCls;
    var menuPrefixCls = getPrefixCls('agentic-chat-history-menu');
    var locale = useContext(I18nContext).locale;
    var containerRef = useRef(null);
    // 注册样式
    var _useStyle = useStyle(menuPrefixCls), wrapSSR = _useStyle.wrapSSR, hashId = _useStyle.hashId;
    var _useHistory = useHistory(props), open = _useHistory.open, setOpen = _useHistory.setOpen, searchKeyword = _useHistory.searchKeyword, selectedIds = _useHistory.selectedIds, filteredList = _useHistory.filteredList, loadHistory = _useHistory.loadHistory, handleSelectionChange = _useHistory.handleSelectionChange, handleSearch = _useHistory.handleSearch, handleLoadMore = _useHistory.handleLoadMore, handleFavorite = _useHistory.handleFavorite, handleNewChat = _useHistory.handleNewChat;
    useClickAway(function() {
        setOpen(false);
    }, containerRef);
    var items = generateHistoryItems({
        filteredList: filteredList,
        selectedIds: selectedIds,
        onSelectionChange: handleSelectionChange,
        onClick: function onClick(sessionId, item) {
            var _props_onClick, _props_onSelected;
            (_props_onClick = props.onClick) === null || _props_onClick === void 0 ? void 0 : _props_onClick.call(props, sessionId, item);
            (_props_onSelected = props.onSelected) === null || _props_onSelected === void 0 ? void 0 : _props_onSelected.call(props, item);
            setOpen(false);
        },
        groupLabelRender: props.groupLabelRender,
        customOperationExtra: props.customOperationExtra || [],
        onDeleteItem: props.onDeleteItem ? function(sessionId) {
            return _async_to_generator(function() {
                var _props_onDeleteItem;
                return _ts_generator(this, function(_state) {
                    switch(_state.label){
                        case 0:
                            return [
                                4,
                                (_props_onDeleteItem = props.onDeleteItem) === null || _props_onDeleteItem === void 0 ? void 0 : _props_onDeleteItem.call(props, sessionId)
                            ];
                        case 1:
                            _state.sent();
                            loadHistory();
                            return [
                                2
                            ];
                    }
                });
            })();
        } : undefined,
        onFavorite: handleFavorite,
        agent: props.agent,
        extra: props.extra,
        customDateFormatter: props.customDateFormatter,
        itemDateFormatter: props.itemDateFormatter,
        groupBy: props.groupBy,
        sessionSort: props.sessionSort,
        type: props.type,
        runningId: (_props_agent = props.agent) === null || _props_agent === void 0 ? void 0 : _props_agent.runningId
    });
    // 使用 useMemo 优化空组件渲染
    // 注意：只有在 items 为空时才需要渲染空组件
    var shouldShowEmpty = (items === null || items === void 0 ? void 0 : items.length) === 0 && !props.loading;
    var EmptyComponent = useMemo(function() {
        if (!shouldShowEmpty) {
            return null;
        }
        if (searchKeyword) {
            return /*#__PURE__*/ React.createElement(HistoryEmpty, null);
        }
        if (props.emptyRender) {
            return props.emptyRender();
        }
        return null;
    }, [
        shouldShowEmpty,
        searchKeyword,
        props.emptyRender
    ]);
    // 使用 useMemo 优化加载更多组件渲染
    var LoadMoreComponent = useMemo(function() {
        var _props_agent, _props_agent1;
        if (props.loadMoreRender) {
            return props.loadMoreRender();
        }
        var shouldRender = ((_props_agent = props.agent) === null || _props_agent === void 0 ? void 0 : _props_agent.enabled) && !!((_props_agent1 = props.agent) === null || _props_agent1 === void 0 ? void 0 : _props_agent1.onLoadMore) && !props.loading;
        if (!shouldRender) {
            return null;
        }
        return /*#__PURE__*/ React.createElement(HistoryLoadMore, {
            onLoadMore: handleLoadMore,
            type: props.type,
            className: classNames("".concat(menuPrefixCls, "-load-more"), hashId, {
                chat: props.type !== 'task'
            })
        });
    }, [
        props.loadMoreRender,
        (_props_agent1 = props.agent) === null || _props_agent1 === void 0 ? void 0 : _props_agent1.enabled,
        (_props_agent2 = props.agent) === null || _props_agent2 === void 0 ? void 0 : _props_agent2.onLoadMore,
        props.loading,
        handleLoadMore,
        props.type,
        menuPrefixCls,
        hashId
    ]);
    if (props.standalone) {
        var _props_agent3, _props_agent4, _props_agent5, _props_agent6, _props_agent7, _props_slots_beforeHistoryList, _props_slots;
        return wrapSSR(/*#__PURE__*/ React.createElement("div", {
            "data-testid": "history-standalone",
            style: {
                display: 'flex',
                flexDirection: 'column',
                height: '100%'
            }
        }, ((_props_agent3 = props.agent) === null || _props_agent3 === void 0 ? void 0 : _props_agent3.enabled) && !!((_props_agent4 = props.agent) === null || _props_agent4 === void 0 ? void 0 : _props_agent4.onNewChat) && /*#__PURE__*/ React.createElement("div", {
            style: {
                flexShrink: 0,
                marginBottom: 12
            }
        }, /*#__PURE__*/ React.createElement(HistoryNewChat, {
            onNewChat: handleNewChat
        })), ((_props_agent5 = props.agent) === null || _props_agent5 === void 0 ? void 0 : _props_agent5.enabled) && !!((_props_agent6 = props.agent) === null || _props_agent6 === void 0 ? void 0 : _props_agent6.onSearch) && /*#__PURE__*/ React.createElement("div", {
            style: {
                flexShrink: 0
            }
        }, /*#__PURE__*/ React.createElement(HistorySearch, {
            searchKeyword: searchKeyword,
            onSearch: handleSearch,
            type: props.type,
            searchOptions: (_props_agent7 = props.agent) === null || _props_agent7 === void 0 ? void 0 : _props_agent7.searchOptions
        })), /*#__PURE__*/ React.createElement("div", {
            className: classNames("".concat(menuPrefixCls, "-scroll-container"), hashId),
            style: {
                flex: 1,
                overflow: 'auto',
                minHeight: 0
            }
        }, (_props_slots = props.slots) === null || _props_slots === void 0 ? void 0 : (_props_slots_beforeHistoryList = _props_slots.beforeHistoryList) === null || _props_slots_beforeHistoryList === void 0 ? void 0 : _props_slots_beforeHistoryList.call(_props_slots, filteredList), shouldShowEmpty ? EmptyComponent : /*#__PURE__*/ React.createElement(React.Fragment, null, /*#__PURE__*/ React.createElement(GroupMenu, {
            selectedKeys: [
                props.sessionId
            ],
            inlineIndent: 20,
            items: items,
            className: menuPrefixCls,
            loading: props.loading
        }), LoadMoreComponent))));
    }
    return /*#__PURE__*/ React.createElement(Popover, {
        open: open,
        onOpenChange: setOpen,
        trigger: "click",
        className: menuPrefixCls,
        style: {
            maxHeight: 'min(480px,100%)',
            overflow: 'auto',
            maxWidth: 'min(480px,100%)',
            borderRadius: 'inherit',
            border: '1px solid var(--color-gray-border-light)'
        },
        getPopupContainer: function getPopupContainer(p) {
            return p.parentElement || document.body;
        },
        content: /*#__PURE__*/ React.createElement(React.Fragment, null, shouldShowEmpty ? /*#__PURE__*/ React.createElement("div", {
            "data-testid": "empty-state-popover"
        }, EmptyComponent) : /*#__PURE__*/ React.createElement(GroupMenu, {
            selectedKeys: [
                props.sessionId
            ],
            inlineIndent: 20,
            items: items,
            className: menuPrefixCls,
            loading: props.loading
        }), LoadMoreComponent)
    }, /*#__PURE__*/ React.createElement("div", {
        ref: containerRef,
        style: {
            display: 'flex',
            alignItems: 'center',
            width: 'max-content',
            maxWidth: 'min(860px,100%)'
        },
        "data-testid": "history-button"
    }, /*#__PURE__*/ React.createElement(ActionIconBox, {
        key: "history",
        title: (locale === null || locale === void 0 ? void 0 : locale['chat.history']) || '历史记录'
    }, /*#__PURE__*/ React.createElement(HistoryOutlined, null))));
};
HistoryComponent.displayName = 'History';
// 使用 React.memo 优化性能，避免不必要的重新渲染
export var History = /*#__PURE__*/ memo(HistoryComponent);
