import $i18n from '../../locales/i18n.js';
import React from 'react';
import { CnSender } from '../../cn-sender';
import { useInsertFieldTag } from '../../hooks/use-insert-field-tag.js';
import { FieldTagPopupWrapper } from '../../field-tag-popup-wrapper/FieldTagPopupWrapper';
import { submitPrompt, queryResponse } from '../services/ai-agent-service';
import { getAgentUserIdForRequest, getAgentUserIdForStorageKey } from '../utils/user-utils';
import { usePersistedAgentVisibility } from '../hooks/use-persisted-agent-visibility';
import { buildAgentVisibilityStorageKey, readAgentVisibilityFromStorage, writeAgentVisibilityToStorage, } from '../utils/agent-visibility-storage';
import { usePollResponse } from '../hooks/use-poll-response';
import { initHostDomainOnce } from '../../service/domain-service.js';
import { MessageItem } from './components/message-item';
import { FollowOrderCard } from './components/follow-order-card';
import { formatSelectedData } from '../utils/format-selected-data';
import { formatColumnDefinitions } from '../utils/format-column-definitions';
import { formatRelatedData } from '../utils/format-related-data';
import { event as eventBus } from '@ice/stark-data';
import { CnAiListEventProvider, useCnAiListEventNames, useCnAiListInstanceKey, } from '../context/cn-ai-list-event-context';
import { CN_AI_LIST_INSTANCE_KEY_DATA_ATTR } from '../constants/event-constants';
import { useAgentVisibilityWithFilter } from '../hooks/use-agent-visibility-with-filter';
import { useTableSelectionForAgent } from '../hooks/use-table-selection-for-agent';
import { useFormattedTableData } from '../../hooks/use-formatted-table-data.js';
import { useColumnDefinitions } from '../../hooks/use-column-definitions.js';
import { POLLING_INTERVAL, MAX_POLLING_COUNT } from '../constants/polling-constants';
import { armsHottagLog } from '../../utils/arms/arms-hot-tag-log.js';
import { isEditor } from '../../utils/env/index.js';
import { useBrandAssets } from '../../theme/context.js';
import './cn-ai-agent.scss';
/**
 * AI助理组件（内层：须在 CnAiListEventProvider 内以解析事件命名空间）
 */
const CnAiAgentView = React.memo((props) => {
    const eventNames = useCnAiListEventNames();
    const listInstanceKey = useCnAiListInstanceKey();
    const { className, selectedCell: selectedCellProp, onClearSelectedCell, schema, userId, id, formattedTableData: formattedTableDataProp, columnDefinitions: columnDefinitionsProp, agentVisible, onAgentVisibleChange, defaultAgentVisible, persistAgentVisibility, bizRequestConfig, ...restProps } = props;
    const tableId = id;
    const isUncontrolled = agentVisible === undefined;
    const enableInternalPersistence = isUncontrolled && persistAgentVisibility !== false && !!id && String(id).trim() !== '';
    const [persistedVisible, setPersistedVisible] = usePersistedAgentVisibility({
        tableId: id,
        userId,
        defaultVisible: defaultAgentVisible !== null && defaultAgentVisible !== void 0 ? defaultAgentVisible : true,
        enablePersistence: enableInternalPersistence,
    });
    const persistControlled = !isUncontrolled && persistAgentVisibility === true && !!id && String(id).trim() !== '';
    const effectiveVisible = isUncontrolled ? persistedVisible : agentVisible;
    const handleAgentVisibleChange = React.useCallback((next) => {
        if (isUncontrolled) {
            setPersistedVisible(next);
        }
        else {
            onAgentVisibleChange === null || onAgentVisibleChange === void 0 ? void 0 : onAgentVisibleChange(next);
        }
    }, [isUncontrolled, setPersistedVisible, onAgentVisibleChange]);
    const lastControlledHydrateKeyRef = React.useRef(null);
    React.useLayoutEffect(() => {
        if (!persistControlled) {
            lastControlledHydrateKeyRef.current = null;
            return;
        }
        if (!id)
            return;
        const uid = getAgentUserIdForStorageKey(userId);
        if (uid == null) {
            lastControlledHydrateKeyRef.current = null;
            return;
        }
        const storageKey = buildAgentVisibilityStorageKey(uid, String(id).trim());
        if (lastControlledHydrateKeyRef.current === storageKey)
            return;
        lastControlledHydrateKeyRef.current = storageKey;
        const stored = readAgentVisibilityFromStorage(storageKey);
        if (stored !== null && stored !== agentVisible) {
            onAgentVisibleChange === null || onAgentVisibleChange === void 0 ? void 0 : onAgentVisibleChange(stored);
        }
    }, [persistControlled, id, userId, agentVisible, onAgentVisibleChange]);
    React.useEffect(() => {
        if (!persistControlled)
            return;
        if (!id)
            return;
        const uid = getAgentUserIdForStorageKey(userId);
        if (uid == null)
            return;
        const storageKey = buildAgentVisibilityStorageKey(uid, String(id).trim());
        writeAgentVisibilityToStorage(storageKey, agentVisible);
    }, [persistControlled, agentVisible, id, userId]);
    const onAgentVisibleChangeRef = React.useRef(onAgentVisibleChange);
    onAgentVisibleChangeRef.current = onAgentVisibleChange;
    React.useLayoutEffect(() => {
        var _a;
        if (!isUncontrolled)
            return;
        (_a = onAgentVisibleChangeRef.current) === null || _a === void 0 ? void 0 : _a.call(onAgentVisibleChangeRef, persistedVisible);
    }, [isUncontrolled, persistedVisible]);
    const { selectedCell: internalSelectedCell, setSelectedCell: setInternalSelectedCell } = useTableSelectionForAgent();
    const effectiveSelectedCell = selectedCellProp !== undefined ? selectedCellProp : internalSelectedCell;
    const hookFormattedTableData = useFormattedTableData();
    const hookColumnDefinitions = useColumnDefinitions();
    const effectiveFormattedTableData = formattedTableDataProp !== undefined ? formattedTableDataProp : hookFormattedTableData;
    const effectiveColumnDefinitions = columnDefinitionsProp !== undefined ? columnDefinitionsProp : hookColumnDefinitions;
    const handleClearSelectedCellCombined = React.useCallback(() => {
        if (selectedCellProp === undefined) {
            setInternalSelectedCell(null);
        }
        eventBus.emit(eventNames.AGENT_CLEAR_SELECTION);
        onClearSelectedCell === null || onClearSelectedCell === void 0 ? void 0 : onClearSelectedCell();
    }, [selectedCellProp, onClearSelectedCell, setInternalSelectedCell, eventNames]);
    const brandAssets = useBrandAssets();
    // 构建选中数据的格式化版本（用于提交给 AI 接口）
    const finalSelectedData = React.useMemo(() => formatSelectedData(effectiveSelectedCell, effectiveFormattedTableData), [effectiveSelectedCell, effectiveFormattedTableData]);
    // 构建列定义的格式化版本（用于提交给 AI 接口）
    const finalColumnDefinitions = React.useMemo(() => formatColumnDefinitions(effectiveColumnDefinitions), [effectiveColumnDefinitions]);
    // 构建相关数据的格式化版本（用于提交给 AI 接口）
    // relatedData 包含完整的表格数据
    const finalRelatedData = React.useMemo(() => formatRelatedData(effectiveFormattedTableData), [effectiveFormattedTableData]);
    // ==================== 用户信息 ====================
    /**
     * 与显隐解析同源：props.userId → `getAliWorkNo()` → `getOperator()`
     */
    const currentUserId = getAgentUserIdForRequest(userId);
    // ==================== 动态域名预热 ====================
    React.useEffect(() => {
        initHostDomainOnce();
    }, []);
    const { panelHidden } = useAgentVisibilityWithFilter({
        agentVisible: effectiveVisible,
        onAgentVisibleChange: handleAgentVisibleChange,
    });
    // ==================== Refs ====================
    /**
     * 输入框组件引用
     * 用于调用输入框的方法（如插入字段标签）
     */
    const senderRef = React.useRef(null);
    /**
     * 聊天内容区域引用
     * 用于控制滚动位置，实现自动滚动到底部
     */
    const contentRef = React.useRef(null);
    /**
     * 轮询定时器引用
     * 存储 setTimeout 返回的定时器 ID，用于清除定时器
     */
    const pollingTimerRef = React.useRef(null);
    /**
     * 滚动进度（0-1），用于头像切换动画
     * 当用户向下滚动聊天区域时，大头像向上移动并缩小到75×32
     */
    const [scrollProgress, setScrollProgress] = React.useState(0);
    const SCROLL_THRESHOLD = 180; // 滚动阈値180px
    /**
     * 是否正在滚动（用于控制滚动条显示）
     */
    const [isScrolling, setIsScrolling] = React.useState(false);
    const scrollTimerRef = React.useRef(null);
    /**
     * 程序自动滚动标记
     * 用于区分用户手动滚动和程序自动滚动，避免自动滚动触发头像切换
     */
    const isProgrammaticScrollRef = React.useRef(false);
    /**
     * 组件挂载状态引用
     * 用于判断组件是否已卸载，避免在卸载后更新状态
     */
    const isMountedRef = React.useRef(true);
    /**
     * 会话 ID 引用
     * - 首次会话：初始值为 null，提交 prompt 时传入 null
     * - 提交成功后：保存返回的 conversationId
     * - 后续会话：使用保存的 conversationId 继续对话
     */
    const conversationIdRef = React.useRef(null);
    /**
     * 轮询计数引用（用于超时控制）
     * key: pollKey (格式: ${conversationId}-${messageId})
     * value: 该消息的轮询次数
     */
    const pollingCountRef = React.useRef({});
    // ==================== State ====================
    /**
     * 消息列表
     * 包含用户消息和 AI 助手消息
     */
    const [messages, setMessages] = React.useState([]);
    /**
     * 是否正在轮询
     * 用于控制中断按钮的显示
     * true: 正在轮询查询 AI 响应
     * false: 未在轮询
     */
    const [isPolling, setIsPolling] = React.useState(false);
    /**
     * 正在生成的消息 ID
     * 用于标识当前正在生成的消息，启用逐字显示效果
     * null: 没有正在生成的消息
     */
    const [generatingMessageId, setGeneratingMessageId] = React.useState(null);
    /**
     * 跟单任务（queryFollowOrderTaskByJobId.do）轮询状态
     * null：未收到过事件，不展示跟单区块；true：轮询中，展示 loading；false：轮询结束，展示 finishedCount
     */
    const [followOrderLoading, setFollowOrderLoading] = React.useState(null);
    /**
     * 跟单任务需要跟单的数量，来自 queryFollowOrderTaskByJobId.do 返回的累积 tasks
     */
    const [followOrderFinishedCount, setFollowOrderFinishedCount] = React.useState(0);
    /**
     * submitOrderFollowRequests.do 返回的 conversationId、respMessageId，用于 queryResponse（queryResponse.do）
     */
    const [followOrderConversationId, setFollowOrderConversationId] = React.useState(null);
    const [followOrderRespMessageId, setFollowOrderRespMessageId] = React.useState(null);
    /**
     * queryResponse 轮询返回的总结文案，与 use-poll-response 一致：每次 response 都更新 content，轮询中为「正在生成回复...」，结束后为正式正文，超时/错误为提示文案
     */
    const [followOrderSummaryText, setFollowOrderSummaryText] = React.useState(null);
    /** 跟单总结是否在轮询中，用于 MessageItem 的 isGenerating（逐字效果），与 use-poll-response 的 generatingMessageId 一致 */
    const [followOrderSummaryGenerating, setFollowOrderSummaryGenerating] = React.useState(false);
    /** 已为此 conversationId 请求过 queryResponse，避免重复请求 */
    const requestedFollowSummaryRef = React.useRef(null);
    /** 跟单总结 queryResponse 轮询的定时器与次数（逻辑参考 use-poll-response） */
    const followSummaryPollingTimerRef = React.useRef(null);
    const followSummaryPollCountRef = React.useRef(0);
    // ==================== Hooks ====================
    /**
     * 轮询查询响应的 Hook
     * 返回 pollResponse 函数，用于轮询查询 AI 响应
     */
    const { pollResponse } = usePollResponse();
    /**
     * 插入字段标签的 Hook
     * 当用户在输入框中输入 "/" 时，弹出字段选择弹窗
     * 选择字段后，将字段标签插入到输入框中
     */
    const insertFieldTag = useInsertFieldTag(senderRef, '/', // 触发键
    (value, onValueChange, renderProps, item, formMapRef, onFormMapUpdate) => {
        return (React.createElement(FieldTagPopupWrapper, { value: value, onValueChange: onValueChange, renderProps: renderProps, item: item, formMapRef: formMapRef, onFormMapUpdate: onFormMapUpdate }));
    });
    // ==================== 事件处理 ====================
    /**
     * 处理发送按钮点击事件
     * @param value - 用户输入的消息内容
     */
    const handleSubmit = React.useCallback(
    // eslint-disable-next-line @typescript-eslint/no-unused-vars -- 与 CnSender onSubmit 签名一致，后三参未使用
    async (value, _slotConfig, _skill, _formValue) => {
        var _a;
        // 1. 验证输入
        if (!value)
            return;
        armsHottagLog({
            hottag: 'cn-ai-agent.submit',
            name: $i18n.get({ id: 'SubmitMessage', dm: '提交消息' }),
            c6: value,
        });
        // 2. 添加用户消息到消息列表
        const userMessage = {
            role: 'user',
            content: value,
            id: `user-${Date.now()}`,
        };
        setMessages((prev) => [...prev, userMessage]);
        // 2.1 清空输入框
        (_a = senderRef.current) === null || _a === void 0 ? void 0 : _a.clear();
        // 3. 清理之前的轮询状态
        // 清除之前的轮询定时器（AI助理自己的轮询）
        if (pollingTimerRef.current) {
            clearTimeout(pollingTimerRef.current);
            pollingTimerRef.current = null;
        }
        // 重置轮询计数
        pollingCountRef.current = {};
        // 重置轮询状态
        setIsPolling(false);
        // 3.1 中断智能跟单的轮询（queryResponse.do）
        // 用户主动提问后不再展示/继续跟单总结轮询：清定时器 + 置空 requestedFollowSummaryRef，使进行中的 poll 返回后不再更新状态、不再续轮询
        if (followSummaryPollingTimerRef.current) {
            clearTimeout(followSummaryPollingTimerRef.current);
            followSummaryPollingTimerRef.current = null;
        }
        followSummaryPollCountRef.current = 0;
        requestedFollowSummaryRef.current = null;
        setFollowOrderSummaryGenerating(false);
        // 4. 添加 AI 助手消息占位符
        // 显示"正在生成..."提示，后续会被实际内容替换
        const placeholderMessageId = `assistant-${Date.now()}`;
        const placeholderMessage = {
            role: 'assistant',
            content: $i18n.get({ id: 'GeneratingReplies', dm: '正在生成回复...' }),
            id: placeholderMessageId,
        };
        setMessages((prev) => [...prev, placeholderMessage]);
        try {
            // 5. 准备提交数据
            // 使用已构建好的 finalSelectedData（在组件顶层通过 useMemo 计算，基于当前选中的单元格和格式化后的表格数据）
            // 6. 调用提交 prompt 接口
            // 首次会话：conversationId 为 null
            // 后续会话：使用保存的 conversationId 继续对话
            const submitResult = await submitPrompt({
                selectedData: finalSelectedData,
                relatedData: finalRelatedData,
                userPrompt: value,
                userId: currentUserId,
                tableId: tableId !== null && tableId !== void 0 ? tableId : '',
                conversationId: conversationIdRef.current,
                columnDefinitions: finalColumnDefinitions,
            }, bizRequestConfig);
            if (!submitResult) {
                throw new Error($i18n.get({ id: 'FailedToSubmitPrompt', dm: '提交 prompt 失败' }));
            }
            // 6.1 清空输入框（提交成功后清空）
            // 使用 setTimeout 确保在下一个事件循环中执行，避免与状态更新冲突
            setTimeout(() => {
                var _a;
                (_a = senderRef.current) === null || _a === void 0 ? void 0 : _a.clear();
            }, 0);
            // 7. 保存会话 ID
            // 首次会话：返回新生成的 conversationId
            // 后续会话：返回相同的 conversationId（与传入的相同）
            const nextConversationId = submitResult.conversationId;
            conversationIdRef.current = nextConversationId;
            // 8. 开始轮询查询响应
            // 轮询会持续查询 AI 响应，直到收到完整回复或超时
            if (isMountedRef.current) {
                setIsPolling(true); // 设置轮询状态
                setGeneratingMessageId(placeholderMessageId); // 标记正在生成的消息，启用逐字显示
                pollResponse({
                    conversationId: nextConversationId,
                    messageId: submitResult.respMessageId,
                    placeholderMessageId,
                    setMessages,
                    setIsPolling,
                    pollingTimerRef,
                    pollingCountRef,
                    isMountedRef,
                    setGeneratingMessageId,
                    bizRequestConfig,
                });
            }
        }
        catch (error) {
            // 9. 错误处理
            // 更新占位符消息为错误信息
            setMessages((prev) => {
                const errorIndex = prev.findIndex((msg) => msg.id === placeholderMessageId);
                if (errorIndex >= 0) {
                    const newMessages = [...prev];
                    newMessages[errorIndex] = {
                        role: 'assistant',
                        content: $i18n.get({
                            id: 'SorryThereWasAnErrorGeneratingTh_1903890869',
                            dm: '抱歉，生成回复时出现错误，请稍后重试。',
                        }),
                        id: placeholderMessageId,
                    };
                    return newMessages;
                }
                return prev;
            });
            // 清除生成状态
            setGeneratingMessageId(null);
            setIsPolling(false);
        }
    }, [
        currentUserId,
        tableId,
        pollResponse,
        finalSelectedData,
        finalColumnDefinitions,
        finalRelatedData,
        bizRequestConfig,
    ]);
    /**
     * 更新滚动进度
     * 根据当前滚动位置计算头像切换进度
     */
    const updateScrollProgress = React.useCallback(() => {
        if (contentRef.current) {
            const { scrollTop } = contentRef.current;
            const progress = Math.min(scrollTop / SCROLL_THRESHOLD, 1);
            setScrollProgress(progress);
        }
    }, []);
    /**
     * 处理聊天区域滚动事件
     * 只响应用户手动滚动，程序自动滚动不触发头像切换
     */
    const handleContentScroll = React.useCallback((e) => {
        // 程序自动滚动时不处理
        if (isProgrammaticScrollRef.current) {
            return;
        }
        // 计算滚动进度: 0(顶部) -> 1(滚动超过180px)
        const { scrollTop } = e.currentTarget;
        const progress = Math.min(scrollTop / SCROLL_THRESHOLD, 1);
        setScrollProgress(progress);
        // 设置滚动中状态，显示滚动条
        setIsScrolling(true);
        if (scrollTimerRef.current) {
            clearTimeout(scrollTimerRef.current);
        }
        // 停止滚动 1s 后隐藏滚动条
        scrollTimerRef.current = setTimeout(() => {
            setIsScrolling(false);
        }, 1000);
    }, []);
    /**
     * 停止轮询
     * 用户点击停止按钮时调用，中断当前的轮询过程
     */
    const handleStopPolling = React.useCallback(() => {
        armsHottagLog({
            hottag: 'cn-ai-agent.stopPolling',
            name: $i18n.get({ id: 'StopBuild', dm: '停止生成' }),
        });
        // 清除轮询定时器
        if (pollingTimerRef.current) {
            clearTimeout(pollingTimerRef.current);
            pollingTimerRef.current = null;
        }
        // 重置轮询计数
        pollingCountRef.current = {};
        // 重置轮询状态
        setIsPolling(false);
        // 更新消息列表：将"正在生成回复..."的消息移除
        setMessages((prev) => {
            // 找到并移除占位符消息（"正在生成回复..."）
            return prev.filter((msg) => {
                // 移除占位符消息（内容为"正在生成回复..."的助手消息）
                if (msg.role === 'assistant' && msg.content === '正在生成回复...') {
                    return false;
                }
                return true;
            });
        });
        // 清除正在生成的消息 ID（停止逐字显示效果）
        setGeneratingMessageId(null);
    }, []);
    // ==================== 副作用处理 ====================
    /**
     * 组件挂载/卸载时的清理工作
     * - 挂载时：标记组件已挂载
     * - 卸载时：清除轮询定时器，避免内存泄漏
     */
    React.useEffect(() => {
        isMountedRef.current = true;
        return () => {
            isMountedRef.current = false; // 标记组件已卸载
            if (pollingTimerRef.current) {
                clearTimeout(pollingTimerRef.current); // 清除定时器
                pollingTimerRef.current = null;
            }
        };
    }, []);
    /**
     * 自动滚动到底部
     * 当消息列表更新时，自动滚动到最新消息
     */
    React.useEffect(() => {
        if (contentRef.current) {
            // 标记为程序自动滚动，避免触发头像切换
            isProgrammaticScrollRef.current = true;
            contentRef.current.scrollTop = contentRef.current.scrollHeight;
            // 延迟重置标记，确保滚动事件已处理完毕
            requestAnimationFrame(() => {
                isProgrammaticScrollRef.current = false;
                // 更新滚动进度，确保头像状态正确
                updateScrollProgress();
            });
        }
    }, [messages, updateScrollProgress]);
    /**
     * 监听跟单任务（queryFollowOrderTaskByJobId.do）轮询状态及 submitOrderFollowRequests 返回的 conversationId / respMessageId
     * 由 TableView 的 useSmartFollow 通过事件同步
     */
    React.useEffect(() => {
        const handleFollowOrderUpdate = (payload) => {
            var _a, _b;
            if (!isMountedRef.current)
                return;
            setFollowOrderLoading(payload.loading);
            setFollowOrderFinishedCount(payload.finishedCount);
            setFollowOrderConversationId((_a = payload.conversationId) !== null && _a !== void 0 ? _a : null);
            setFollowOrderRespMessageId((_b = payload.respMessageId) !== null && _b !== void 0 ? _b : null);
        };
        eventBus.on(eventNames.FOLLOW_ORDER_TASKS_UPDATE, handleFollowOrderUpdate);
        return () => {
            eventBus.off(eventNames.FOLLOW_ORDER_TASKS_UPDATE, handleFollowOrderUpdate);
        };
    }, [eventNames]);
    /**
     * followOrderLoading 为 false 时，用 submitOrderFollowRequests 返回的 conversationId、respMessageId 轮询 queryResponse
     * 轮询与渲染逻辑与 use-poll-response 一致：每次 response 都更新展示 content，onGoing 则继续轮询，超时/错误则更新为提示文案并停止
     */
    React.useEffect(() => {
        if (followOrderLoading !== false || !followOrderConversationId || !followOrderRespMessageId) {
            return;
        }
        if (requestedFollowSummaryRef.current === followOrderConversationId)
            return;
        requestedFollowSummaryRef.current = followOrderConversationId;
        followSummaryPollCountRef.current = 0;
        // 与 use-poll-response 一致：先展示占位「正在生成回复...」，再开始轮询
        setFollowOrderSummaryText($i18n.get({ id: 'GeneratingReplies', dm: '正在生成回复...' }));
        setFollowOrderSummaryGenerating(true);
        const cId = followOrderConversationId;
        const mId = followOrderRespMessageId;
        const poll = async () => {
            var _a;
            followSummaryPollCountRef.current += 1;
            const count = followSummaryPollCountRef.current;
            if (count > MAX_POLLING_COUNT) {
                followSummaryPollingTimerRef.current = null;
                if (isMountedRef.current && requestedFollowSummaryRef.current === cId) {
                    setFollowOrderSummaryText($i18n.get({ id: 'QueryTimedOutPleaseTryAgainLater', dm: '查询超时，请稍后重试。' }));
                    setFollowOrderSummaryGenerating(false);
                }
                return;
            }
            try {
                const res = await queryResponse({ conversationId: cId, messageId: mId }, bizRequestConfig);
                if (!isMountedRef.current)
                    return;
                if (requestedFollowSummaryRef.current !== cId)
                    return;
                // 与 use-poll-response 一致：每次轮询到结果都更新展示 content（含 onGoing 时的「正在生成回复...」）
                // 只有当内容变化时才更新状态，避免不必要的重新渲染
                const newText = (_a = res === null || res === void 0 ? void 0 : res.text) !== null && _a !== void 0 ? _a : '';
                setFollowOrderSummaryText((prev) => (prev === newText ? prev : newText));
                if (res === null || res === void 0 ? void 0 : res.onGoing) {
                    followSummaryPollingTimerRef.current = setTimeout(poll, POLLING_INTERVAL);
                }
                else {
                    followSummaryPollingTimerRef.current = null;
                    setFollowOrderSummaryGenerating(false);
                }
            }
            catch {
                followSummaryPollingTimerRef.current = null;
                if (isMountedRef.current && requestedFollowSummaryRef.current === cId) {
                    setFollowOrderSummaryText($i18n.get({
                        id: 'SorryThereWasAnErrorInTheQuery',
                        dm: '抱歉，查询回复时出现错误，请稍后重试。',
                    }));
                    setFollowOrderSummaryGenerating(false);
                }
            }
        };
        poll();
        return () => {
            if (followSummaryPollingTimerRef.current) {
                clearTimeout(followSummaryPollingTimerRef.current);
                followSummaryPollingTimerRef.current = null;
            }
        };
    }, [followOrderLoading, followOrderConversationId, followOrderRespMessageId, bizRequestConfig]);
    // ==================== 渲染辅助函数 ====================
    /**
     * 渲染输入框头部
     * 显示选中的单元格/行/列信息，并提供清除按钮
     * @returns 输入框头部 JSX 或 null
     */
    const renderInputHeader = React.useMemo(() => {
        if (!effectiveSelectedCell) {
            return null;
        }
        const { type, columnName, value, selectedRowKeys, selectedColumnName, columnId } = effectiveSelectedCell;
        let displayText = '';
        // 根据选中类型显示不同的文本
        if (type === 'cell') {
            // 选中单元格：优先用 finalSelectedData 中的当前值（随单元格编辑同步），否则用选中时的 value
            let displayValue = value != null ? String(value) : '';
            if ((finalSelectedData === null || finalSelectedData === void 0 ? void 0 : finalSelectedData.length) === 1 &&
                columnId &&
                finalSelectedData[0].rowData[columnId] != null) {
                displayValue = String(finalSelectedData[0].rowData[columnId]);
            }
            const selectedFieldLabel = $i18n.get({ id: 'SelectedFields', dm: '选中字段' });
            displayText = `${columnName || selectedFieldLabel}: ${displayValue}`;
        }
        else if (type === 'row') {
            // 选中行：显示选中行数
            const count = (selectedRowKeys === null || selectedRowKeys === void 0 ? void 0 : selectedRowKeys.length) || 0;
            displayText = $i18n.get({
                id: 'CountRowsSelected',
                dm: '已选中 {count} 行',
            }, { count });
        }
        else if (type === 'column') {
            // 选中列：显示列名
            const columnSelectedLabel = $i18n.get({ id: 'SelectedColumn', dm: '已选中列' });
            const unknownColumnLabel = $i18n.get({ id: 'UnknownColumn', dm: '未知列' });
            displayText = `${columnSelectedLabel}: ${selectedColumnName || unknownColumnLabel}`;
        }
        return (React.createElement("div", { className: "cn-ai-agent__input-header" },
            React.createElement("span", { className: "cn-ai-agent__deadline" }, displayText),
            React.createElement("button", { className: "cn-ai-agent__close-btn", type: "button", onClick: () => {
                    armsHottagLog({
                        hottag: 'cn-ai-agent.clearSelectedCell',
                        name: $i18n.get({ id: 'ClearSelected', dm: '清除选中' }),
                    });
                    handleClearSelectedCellCombined();
                } }, "\u00D7")));
    }, [effectiveSelectedCell, finalSelectedData, handleClearSelectedCellCombined]);
    // ==================== 渲染 ====================
    return (React.createElement("div", { className: `cn-ai-agent ${className || ''}${panelHidden ? ' cn-ai-agent--panel-hidden' : ''}`, ...restProps, id: id, [CN_AI_LIST_INSTANCE_KEY_DATA_ATTR]: listInstanceKey },
        React.createElement("div", { className: "cn-ai-agent__header" },
            React.createElement("div", { className: "cn-ai-agent__avatar cn-ai-agent__avatar--small", style: {
                    opacity: scrollProgress,
                } },
                React.createElement("img", { className: "cn-ai-agent__avatar-img", src: brandAssets.agent.avatarUrl, alt: "avatar" }),
                React.createElement("img", { className: "cn-ai-agent__avatar-badge", src: brandAssets.agent.avatarBadgeUrl, alt: "badge" }))),
        React.createElement("div", { className: `cn-ai-agent__scroll-container${isScrolling ? ' is-scrolling' : ''}`, ref: contentRef, onScroll: handleContentScroll },
            React.createElement("div", { className: "cn-ai-agent__hero" },
                React.createElement("img", { className: "cn-ai-agent__hero-img", src: brandAssets.agent.heroUrl, alt: "AI Assistant", style: {
                        transform: `scale(${1 - scrollProgress * 0.76})`,
                        transformOrigin: 'bottom center',
                    } })),
            React.createElement("div", { className: "cn-ai-agent__content" },
                followOrderLoading !== null && (React.createElement(React.Fragment, null,
                    React.createElement(FollowOrderCard, { count: followOrderFinishedCount, loading: followOrderLoading, onClick: () => eventBus.emit(eventNames.SWITCH_TO_SMART_FOLLOW) }),
                    followOrderSummaryText && (React.createElement(MessageItem, { message: {
                            role: 'assistant',
                            content: followOrderSummaryText,
                            id: 'follow-order-summary',
                        }, isGenerating: followOrderSummaryGenerating })))),
                messages.length === 0 && followOrderLoading === null && (React.createElement("div", { className: "cn-ai-agent__empty" }, $i18n.get({
                    id: 'StartAConversationWithAnAIAssist_1381840577',
                    dm: '开始与 AI 助理对话吧',
                }))),
                messages.map((msg) => (React.createElement(MessageItem, { key: msg.id, message: msg, 
                    // 判断是否正在生成：只有当前正在生成的消息才启用逐字显示
                    isGenerating: msg.role === 'assistant' && msg.id === generatingMessageId }))))),
        React.createElement("div", { className: "cn-ai-agent__input-area" },
            React.createElement(CnSender, { ref: senderRef, className: "cn-ai-agent-sender", placeholder: $i18n.get({ id: 'TellMeWhatYouWantToDo', dm: '告诉我你想做什么' }), header: renderInputHeader || undefined, suffix: false, footer: (actionNode) => {
                    // footer 函数接收 actionNode（包含录音和发送/加载按钮）
                    return React.createElement("div", { className: "cn-ai-agent__footer" }, actionNode);
                }, loading: isPolling, onCancel: handleStopPolling, allowRecord // 允许录音输入
                : true, schema: schema, popupTriggerKey: "/" // 按 "/" 触发字段选择弹窗
                , onSubmit: handleSubmit, customPopupProps: {
                    // 字段选择回调：插入字段标签到输入框
                    onFieldSelect: ({ fieldKey, fieldConfig }) => {
                        armsHottagLog({
                            hottag: 'cn-ai-agent.selectField',
                            name: $i18n.get({ id: 'SelectField', dm: '选择字段' }),
                            c6: fieldKey,
                        });
                        insertFieldTag(fieldKey, fieldConfig);
                    },
                    asyncSelectProps: {
                        placeholder: $i18n.get({
                            id: 'SelectTheFieldsThatNeedToBeIntro_2004559010',
                            dm: '选择需要引入的字段',
                        }),
                    },
                }, onPasteFile: () => {
                    // 处理文件上传
                    // TODO: 实现文件上传逻辑
                }, autoSize: { minRows: 1, maxRows: 8 }, sendButtonProps: isEditor ? { disabled: true } : undefined }))));
});
CnAiAgentView.displayName = 'CnAiAgent';
/**
 * AI助理组件：按 `id` 隔离与表格/筛选的事件总线频道（同页多实例时须与 CnAiTable/CnAiFilter 的 `id` 一致）
 */
export const CnAiAgent = React.memo((props) => (React.createElement(CnAiListEventProvider, { instanceId: props.id },
    React.createElement(CnAiAgentView, { ...props }))));
CnAiAgent.displayName = 'CnAiAgent';
