<template>
  <div class="chat-container" @click="handleContainerClick">
    <!-- 最左侧边栏 -->
    <Sidebar />

    <!-- 中间历史记录区域 -->
    <div class="history-sidebar">
      <div class="new-chat-container">
        <button class="new-chat-btn-full" @click="createNewChat" :disabled="isSending">
          <span class="plus-icon">+</span>
          新建任务
        </button>
      </div>

      <div class="history-header">
        <span class="section-title">历史记录</span>
      </div>
      
      <div class="history-list">
        <!-- 历史记录加载状态 -->
        <div v-if="isLoadingHistory" class="history-loading">
          <div class="loading-spinner"></div>
          <div class="loading-text">正在加载历史记录...</div>
        </div>
        
        <!-- 有历史记录时显示 -->
        <div 
          v-else-if="historyTotal > 0"
          v-for="(item, index) in historyData" 
          :key="index"
          :class="['history-item', { active: item.isActive }]"
          @click="item.isActive ? null : (isSending ? null : handleHistoryItem(item))"
          :style="{ 
            cursor: item.isActive ? 'default' : (isSending ? 'not-allowed' : 'pointer')
          }"
        >
          <div class="history-content">
            <div class="history-title">{{ item.title }}</div>
            <div class="history-time">{{ item.time }}</div>
          </div>
          <div 
            class="delete-btn" 
            @click.stop="deleteHistoryItem(item, index)"
            :class="{ 'always-visible': item.isActive }"
          >
            <img src="/src/assets/AIWriting/8.png" alt="删除" class="delete-icon" />
          </div>
        </div>
        
        <!-- 无历史记录时显示空状态 -->
        <div v-else class="empty-history">
          <img :src="emptyIcon" alt="暂无数据" class="empty-icon">
          <div class="empty-text">暂无数据</div>
        </div>
      </div>
    </div>

    <!-- 右侧AI问答区域 -->
    <div class="main-chat" :class="{ 'sidebar-open': webSearchSidebarVisible }">
      <!-- 聊天头部 -->
      <div class="chat-header">
        <div class="question-title-card" v-if="currentQuestion">
          <h2>{{ currentQuestion }}</h2>
        </div>
        <h2 v-else class="default-title">AI问答</h2>
      </div>

      <!-- 考试工坊内容区域 -->
      <div v-if="currentMode === 'exam-workshop'" class="exam-workshop-wrapper">
        <ExamWorkshop :hideSidebar="true" />
      </div>

      <!-- 聊天内容区域 -->
      <div v-else class="chat-content">
        <!-- 初始状态：AI助手介绍和功能卡片 -->
        <div v-if="!showChat" class="initial-content">
          <!-- AI助手介绍 -->
          <div class="ai-intro">
            <div class="ai-avatar">
              <img :src="aiAvatarIcon" alt="AI头像" class="ai-avatar-img">
            </div>
            <div class="ai-greeting">
              <h3>我是蜀道安全管理AI智能助手，您的得力帮手</h3>
              <p>我可以帮您处理这些事情</p>
            </div>
          </div>

          <!-- 功能卡片 -->
          <div class="function-cards">
            <div 
              v-for="(card, index) in functionCards" 
              :key="card.id || index"
              class="function-card" 
              @click="handleFunctionCard(card.function_title)"
            >
              <div class="card-header">
                <div class="card-icon">
                  <img :src="getFunctionCardIcon(card.function_title)" :alt="card.function_title" class="card-icon-img">
                </div>
                <h4>{{ card.function_title }}</h4>
              </div>
              <div class="card-description">
                <p>{{ card.function_content }}</p>
              </div>
            </div>
            
            <!-- 如果没有数据，显示默认卡片 -->
            <div v-if="functionCards.length === 0" class="function-card" @click="handleFunctionCard('桥梁结构设计问题')">
              <div class="card-header">
                <div class="card-icon">
                  <img :src="bridgeIcon" alt="桥梁结构设计问题" class="card-icon-img">
                </div>
                <h4>桥梁结构设计问题</h4>
              </div>
              <div class="card-description">
                <p>各类桥梁结构设计，计算与分析</p>
              </div>
            </div>
            <div v-if="functionCards.length === 0" class="function-card" @click="handleFunctionCard('桥梁施工技术咨询')">
              <div class="card-header">
                <div class="card-icon">
                  <img :src="constructionIcon" alt="施工技术咨询" class="card-icon-img">
                </div>
                <h4>施工技术咨询</h4>
              </div>
              <div class="card-description">
                <p>桥梁施工方法，工艺与技术要点</p>
              </div>
            </div>
            <div v-if="functionCards.length === 0" class="function-card" @click="handleFunctionCard('材料与力学问题')">
              <div class="card-header">
                <div class="card-icon">
                  <img :src="materialIcon" alt="材料与力学问题" class="card-icon-img">
                </div>
                <h4>材料与力学问题</h4>
              </div>
              <div class="card-description">
                <p>建筑材料性能与结构力学分析</p>
              </div>
            </div>
            <div v-if="functionCards.length === 0" class="function-card" @click="handleFunctionCard('规范标准查询')">
              <div class="card-header">
                <div class="card-icon">
                  <img :src="standardIcon" alt="规范标准查询" class="card-icon-img">
                </div>
                <h4>规范标准查询</h4>
              </div>
              <div class="card-description">
                <p>行业规范，标准解读与应用</p>
              </div>
            </div>
          </div>
        </div>

        <!-- 聊天对话区域 -->
        <div v-else class="chat-messages">
          <div 
            v-for="(message, index) in chatMessages" 
            :key="index"
            :class="['message-item', message.type]"
          >
            <!-- 用户消息 -->
            <div v-if="message.type === 'user'" class="user-message">
              <div class="message-content">
                <!-- 文件显示 -->
                <div v-if="message.file" class="message-file">
                  <div class="file-display">
                    <div class="file-icon">
                <img v-if="message.file.icon !== '📎'" :src="message.file.icon" alt="文件图标" class="file-icon-img">
                <span v-else>{{ message.file.icon }}</span>
              </div>
                    <div class="file-details">
                      <div class="file-name">{{ message.file.name }}</div>
                      <div class="file-size">{{ formatFileSize(message.file.size) }}</div>
                    </div>
                  </div>
                </div>
                <!-- 文本内容 -->
                <div v-if="message.content" class="message-text">{{ message.content }}</div>
              </div>
              <div class="message-actions">
                <button class="action-btn copy-btn" @click="copyUserMessage(message)">
                  <img :src="copyIcon" alt="复制" class="action-icon">
                  复制
                </button>
                <button class="action-btn edit-btn" @click="editUserMessage(message)">
                  <img :src="editIcon" alt="编辑" class="action-icon">
                  编辑
                </button>
              </div>
            </div>
            
            <!-- AI消息 -->
            <div v-else-if="message.type === 'ai'" class="ai-message">
              <!-- 网络搜索胶囊 - 在输出框上方 -->
              <div v-if="message.webSearchRaw && message.webSearchRaw.total > 0" class="web-search-capsule-outer">
                <WebSearchCapsule
                  :total="message.webSearchRaw.total"
                  :results="message.webSearchRaw.results"
                  :isExpanded="webSearchSidebarVisible"
                  @toggle="handleWebSearchToggle(index)"
                />
              </div>
              
              <div class="ai-message-main">
                <div class="ai-avatar-small">
                  <img :src="aiAvatarIcon" alt="AI" class="ai-icon">
                  </div>
                <div class="message-content" :data-message-index="index" :ref="el => messageContentRefs[index] = el">
                  <!-- 完整的AI回复内容 -->
                  <div class="ai-response-content">
                    <!-- 状态统计卡片 - 优先显示（不等待后端数据） -->
                    <div v-if="message.showStats" 
                         class="files-stats-white"
                         :class="{ 'sticky': messageScrollStates[index]?.isSticky && messageScrollStates[index]?.initialized && !messageScrollStates[index]?.isInitializing }"
                         :style="(messageScrollStates[index]?.isSticky && messageScrollStates[index]?.initialized && !messageScrollStates[index]?.isInitializing && messageScrollStates[index]?.initialLeft > 0 && messageScrollStates[index]?.initialWidth > 0) ? {
                           position: 'fixed',
                           top: '56px',
                           left: messageScrollStates[index].initialLeft + 'px',
                           width: messageScrollStates[index].initialWidth + 'px',
                           zIndex: 999
                         } : {}"
                         :data-message-index="index">
                      <div class="stats-left">
                        <StatusAvatar 
                          :status="getAvatarStatus(message.currentStatus, message.progress)" 
                          :size="36"
                          class="stats-avatar"
                        />
                        <span v-html="message.statusMessage"></span>
                      </div>
                      
                      <!-- 进度条胶囊 - 在白色卡片内 -->
                      <div v-if="message.progress < 100" class="progress-capsule-inline">
                        <div class="progress-bar-mini">
                          <div class="progress-fill" :style="{ width: message.progress + '%' }"></div>
                          <div class="progress-dot" :style="{ left: message.progress + '%' }"></div>
                        </div>
                        <span class="progress-percentage">{{ message.progress }}%</span>
                      </div>
                      
                      <div v-if="message.progress === 100 && message.reports && message.reports.length > 0" class="stats-right">
                        <ExportButton
                          :reports="message.reports.filter(r => r.status === 'completed' && r.type !== 'category_title')"
                          :disabled="false"
                          :title="exportTitle"
                        />
                    </div>
                    </div>
                    
                    <!-- 问题总结 -->
                    <div v-if="message.summary" class="question-summary">
                      <StreamMarkdown :content="message.summary" :streaming="false" />
                </div>
                    
                    <!-- 报告生成中的Loading动画 - 当还没有报告时显示 -->
                    <div v-if="message.isTyping && (!message.reports || message.reports.length === 0) && message.progress < 100" class="report-loading">
                      <span class="loading-text">AI正在思考中...</span>
                      <div class="thinking-animation">
                        <span class="dot"></span>
                        <span class="dot"></span>
                        <span class="dot"></span>
                      </div>
                </div>
              
                    <!-- 报告列表 -->
                    <div v-if="message.reports && message.reports.length > 0" class="reports-list">
                      <template v-for="(report, rIndex) in message.reports" :key="`${report.source_file}-${report.file_index}-${rIndex}`">
                        <!-- 类别标题 -->
                        <CategoryTitle
                          v-if="report.type === 'category_title'"
                          :category="report.category"
                          :number="report.number"
                          :count="report.count"
                          @toggle="(data) => handleCategoryToggle(index, data)"
                        />
                        <!-- 文件报告 -->
                        <FileReportCard
                          v-else-if="!report.type || report.type !== 'category_title'"
                          v-show="isCategoryExpanded(index, report.metadata?._displayCategory || report.metadata?.primary_category)"
                          :report="report"
                          @preview-file="handleFilePreview"
                        />
                      </template>
                      
                      <!-- 分类下的Loading动画 - 当有分类但还在等待报告时 -->
                      <div v-if="message.isTyping && message.progress < 100 && hasOnlyCategoryTitles(message.reports)" class="report-loading">
                        <span class="loading-text">AI正在思考中...</span>
                      <div class="thinking-animation">
                        <span class="dot"></span>
                        <span class="dot"></span>
                        <span class="dot"></span>
                      </div>
                    </div>
                    </div>
                    
                    <!-- 网络搜索总结 -->
                    <div v-if="message.hasWebSearchResults && message.webSearchSummary">
                      <WebSearchSummary :summary="message.webSearchSummary" />
                    </div>
                    
                    <!-- 安全培训文档卡片 -->
                    <div v-if="message.isDocument" class="safety-doc-card" @click="handleSafetyDocClick(message)">
                      <div class="doc-icon-wrapper">
                        <img src="../assets/Chat/26.png" alt="文档" class="doc-icon">
                      </div>
                      <div class="doc-info">
                        <div class="doc-title">{{ currentQuestion || '安全培训文档' }}</div>
                        <div class="doc-time">刚刚生成</div>
                      </div>
                      <div class="doc-action">
                        查看详情 >
                      </div>
                    </div>

                    <!-- 原有的AI文本内容（如果没有报告数据时显示） -->
                    <div v-if="!message.reports || message.reports.length === 0" class="ai-text">
                    <div v-if="message.displayContent && message.displayContent.length > 0 && !message.isDocument" class="ai-markdown-content">
                      <div v-html="message.displayContent"></div>
                    </div>
                  </div>
                  </div>
                  
                  <div v-show="!message.isTyping && ((message.displayContent && message.displayContent.length > 0) || message.summary)" class="divider"></div>
                  <div v-show="!message.isTyping && ((message.displayContent && message.displayContent.length > 0) || message.summary)" class="message-actions">
                    <div class="left-actions">
                      <button class="action-btn copy-btn" @click="copyAIMessage(message)">
                        <img :src="copyIcon" alt="复制" class="action-icon">
                        复制
                      </button>
                      <button class="action-btn regenerate-btn" @click="regenerateResponse(index)" :disabled="hasTypingMessage">
                        <img :src="regenerateIcon" alt="重新生成" class="action-icon">
                        重新生成
                      </button>
                      <!-- 删除按钮 -->
                      <button class="action-btn delete-btn" @click="handleDeleteClick(index)">
                        <img src="../assets/AIWriting/8.png" alt="删除" class="action-icon">
                        删除
                      </button>
                      <button class="action-btn voice-btn" @click="handleVoiceRead(message)" :class="{ speaking: isSpeaking(message.id) }">
                        <img :src="voiceIcon" alt="语音朗读" class="action-icon">
                        {{ isSpeaking(message.id) ? '停止朗读' : '语音朗读' }}
                      </button>
                    </div>
                    <div class="right-actions">
                      <button 
                        class="action-btn thumbs-up-btn" 
                        :class="{ active: message.userFeedback === 'like' }"
                        @click="handleThumbsUp(message)"
                        :title="message.userFeedback === 'like' ? '取消点赞' : '点赞'"
                      >
                        <img :src="likeIcon" alt="点赞" class="action-icon">
                      </button>
                      <button 
                        class="action-btn thumbs-down-btn"
                        :class="{ active: message.userFeedback === 'dislike' }"
                        @click="handleThumbsDown(message)"
                        :title="message.userFeedback === 'dislike' ? '取消点踩' : '点踩'"
                      >
                        <img :src="dislikeIcon" alt="踩" class="action-icon">
                      </button>
                    </div>
                  </div>
                </div>
              </div>
              
              <!-- 搜索来源（仅在没有联网搜索结果时显示） -->
              <div v-show="!message.isTyping && ((message.displayContent && message.displayContent.length > 0) || message.summary) && message.searchSources && message.searchSources.length > 0 && !onlineSearchResults[message.id]" class="search-sources">
                <div class="search-sources-header" @click="toggleSearchSources(message.id)">
                  <span>基于{{ message.searchSources?.length || 0 }}个搜索来源</span>
                  <div class="expand-icon" :class="{ expanded: expandedSearchSources[message.id] }">
                    <svg width="12" height="12" viewBox="0 0 12 12" fill="none">
                      <path d="M3 4.5L6 7.5L9 4.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
                    </svg>
                  </div>
                </div>
                <div v-show="expandedSearchSources[message.id]" class="search-sources-content">
                  <div class="sources-section">
                    <!-- <div class="section-header">
                      <div class="section-icon">🔍</div>
                      <span class="section-title">找到{{ message.searchSources?.length || 0 }}个搜索来源</span>
                    </div> -->
                    <div class="sources-grid">
                      <div class="source-card" v-for="(source, index) in (message.searchSources || [])" :key="index" @click="openSearchSource(source.url)">
                        <div class="source-title">{{ source.title }}</div>
                        <div class="source-description">{{ source.content }}</div>
                        <div class="source-badge">{{ index + 1 }}</div>
                      </div>
                    </div>
                  </div>
                  </div>
                </div>
                
                <!-- 推荐问题Loading -->
                <div v-show="!message.isTyping && ((message.displayContent && message.displayContent.length > 0) || message.summary) && isGettingRelatedQuestions && (relatedQuestionsMessageId === message.id || relatedQuestionsMessageId === message.ai_message_id) && aiRelatedQuestions.length === 0" class="related-questions-loading">
                  <div class="thinking-animation">
                    <span class="dot"></span>
                    <span class="dot"></span>
                    <span class="dot"></span>
                  </div>
                </div>
                
                <!-- 提问联想 -->
                <div v-show="!message.isTyping && ((message.displayContent && message.displayContent.length > 0) || message.summary) && (relatedQuestionsMessageId === message.id || relatedQuestionsMessageId === message.ai_message_id) && aiRelatedQuestions.length > 0" class="related-questions">
                  <div 
                    v-for="(question, index) in aiRelatedQuestions" 
                    :key="index"
                    class="related-question-item" 
                    @click="handleRelatedQuestion(question)"
                  >
                    <span>{{ question }}</span>
                    <svg class="arrow-icon" viewBox="0 0 16 16" fill="none">
                      <path d="M6 4L10 8L6 12" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
                    </svg>
                  </div>
                </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 底部输入区域 -->
      <div class="chat-input-section">
        <!-- 推荐问题 (移至输入框上方) -->
        <div v-if="!showChat && !selectedFile" class="recommended-questions">
          <div 
            v-for="(question, index) in hotQuestions" 
            :key="question.id || index"
            class="question-tag" 
            @click="handleRecommendedQuestion(question.question)"
          >
            <img :src="getQuestionIcon(question.question)" alt="问题" class="question-icon">
            {{ question.question }}
          </div>
          
          <!-- 如果没有数据，显示默认问题 -->
          <div v-if="hotQuestions.length === 0" class="question-tag" @click="handleRecommendedQuestion('施工安全生产责任的规定')">
            <img :src="questionIcon1" alt="问题" class="question-icon">
            施工安全生产责任的规定
          </div>
          <div v-if="hotQuestions.length === 0" class="question-tag" @click="handleRecommendedQuestion('工程建设质量的要求')">
            <img :src="questionIcon2" alt="问题" class="question-icon">
            工程建设质量的要求
          </div>
          <div v-if="hotQuestions.length === 0" class="question-tag" @click="handleRecommendedQuestion('公路桥梁加固设计规范')">
            <img :src="questionIcon3" alt="文档" class="question-icon">
            公路桥梁加固设计规范
          </div>
        </div>

        <!-- 用户推荐问题区域 -->
        <div v-if="userRecommendQuestions.length > 0" class="user-recommend-questions" @click.stop>
          <div class="recommend-list">
            <div 
              v-for="(question, index) in userRecommendQuestions" 
              :key="index"
              class="recommend-item" 
              @click="handleUserRecommendQuestion(question)"
            >
              {{ question }}
            </div>
          </div>
        </div>

        <div class="input-container">
          <!-- 文件预览区域 -->
          <div v-if="selectedFile" class="file-preview-section">
            <div class="file-preview">
              <div class="file-icon">
                <img v-if="selectedFile.icon !== '📎'" :src="selectedFile.icon" alt="文件图标" class="file-icon-img">
                <span v-else>{{ selectedFile.icon }}</span>
              </div>
              <div class="file-info">
                <div class="file-name">{{ selectedFile.name }}</div>
                <div class="file-size">{{ formatFileSize(selectedFile.size) }}</div>

              </div>
              <button class="remove-file-btn" @click="removeSelectedFile">
                <span class="remove-icon">×</span>
              </button>
            </div>
          </div>
          
          <div class="input-box">
            <!-- 上半部分：输入区 -->
            <textarea 
              placeholder="给AI智能助手发消息(按Enter进行发送)"
              class="message-input"
              v-model="messageText"
              @keyup.enter.exact="handleSendMessage"
              @input="handleInput"
              :disabled="hasTypingMessage"
              maxlength="2000"
              rows="3"
            ></textarea>

            <!-- 下半部分：工具栏 -->
            <div class="input-toolbar">
              <div class="toolbar-left">
                <!-- 语音输入 -->
                <button class="voice-btn" @click="handleVoiceClick" :disabled="hasTypingMessage" :class="{ 'recording': isListening }">
                  <div class="icon-container">
                    <img :src="voiceInputIcon" alt="语音" class="action-icon">
                    <div v-if="isListening" class="recording-indicator"></div>
                  </div>
                </button>

                <!-- 模式标签组 -->
                <div class="mode-chips">
                  <div 
                    v-if="currentMode === 'ai-qa' || currentMode === 'ai-writing'"
                    class="mode-chip" 
                    :class="{ active: currentMode === 'ai-writing' }"
                    @click="setMode('ai-writing')"
                  >
                    <img src="../assets/chat/13.png" alt="AI写作" class="chip-icon">
                    <span>AI写作</span>
                  </div>
                  
                  <div 
                    v-if="currentMode === 'ai-qa' || currentMode === 'safety-training'"
                    class="mode-chip" 
                    :class="{ active: currentMode === 'safety-training' }"
                    @click="setMode('safety-training')"
                  >
                    <img src="../assets/chat/14.png" alt="安全培训" class="chip-icon">
                    <span>安全培训</span>
                  </div>

                  <div 
                    v-if="currentMode === 'ai-qa' || currentMode === 'exam-workshop'"
                    class="mode-chip" 
                    :class="{ active: currentMode === 'exam-workshop' }"
                    @click="setMode('exam-workshop')"
                  >
                    <img src="../assets/chat/19.png" alt="考试工坊" class="chip-icon">
                    <span>考试工坊</span>
                  </div>
                </div>
              </div>

              <div class="toolbar-right">
                <!-- 在线大模型链接按钮 (左侧) -->
                <button 
                  class="model-link-btn" 
                  :class="{ 'active': isOnlineModel }"
                  @click="toggleModelType" 
                  :disabled="hasTypingMessage" 
                  :title="isOnlineModel ? '当前：在线大模型 (glm-4-plus)' : '当前：本地模型'"
                >
                  <div class="icon-container">
                    <img :src="isOnlineModel ? networkSearchIconOn : networkSearchIconOff" alt="在线大模型" class="action-icon network-search-icon" :class="{ 'active-icon': isOnlineModel }">
                  </div>
                </button>

                <!-- 附件图标 (右侧) -->
                <button class="attach-btn" @click="triggerFileUpload" :disabled="hasTypingMessage">
                  <div class="icon-container">
                    <img :src="attachmentIcon" alt="附件" class="action-icon">
                  </div>
                </button>

                <button 
                  class="send-btn" 
                  @click="isSending ? handleStopGeneration() : handleSendMessage()" 
                  :disabled="!isSending && (hasTypingMessage || !messageText.trim())"
                >
                  <span v-if="isSending" class="stop-text">停止</span>
                  <div v-else class="send-icon-circle" :class="{ 'active': messageText.trim() && !hasTypingMessage }">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                      <path d="M12 19V5M12 5L5 12M12 5L19 12" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                    </svg>
                  </div>
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    
    
    <!-- 隐藏的文件输入框 -->
    <input
      ref="fileInput"
      type="file"
      accept=".doc,.docx,.xls,.xlsx,.ppt,.pptx,.pdf,image/*,text/plain"
      style="display: none"
      @change="handleFileSelect"
    />
    
    <!-- Toast提示组件 -->
    <Toast
      ref="toastRef"
      :message="toastMessage"
      :type="toastType"
      :duration="toastDuration"
    />
    
    <!-- 删除确认弹窗 -->
    <DeleteConfirmModal
      :visible="showDeleteModal"
      :title="deleteConfirmTitle"
      :message="deleteConfirmMessage"
      @confirm="confirmDelete"
      @cancel="cancelDelete"
      @close="cancelDelete"
    />
    
    <!-- 文件预览抽屉 -->
    <FilePreviewDrawer
      v-model="showFilePreview"
      :file-path="previewFilePath"
      :file-name="previewFileName"
    />
    
    <!-- 网络搜索侧边栏 -->
    <WebSearchSidebar
      :visible="webSearchSidebarVisible"
      :results="currentWebSearchData.results"
      :keywords="currentWebSearchData.keywords"
      :total="currentWebSearchData.total"
      @update:visible="webSearchSidebarVisible = $event"
    />
    
  </div>
</template>

<script setup>
import { ref, nextTick, reactive, triggerRef, markRaw, onMounted, onBeforeUnmount, computed, watch, onActivated } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import Sidebar from '@/components/Sidebar.vue'
import ExamWorkshop from '@/views/ExamWorkshop.vue'
import * as mammoth from 'mammoth'

// 导入Element Plus组件
import { ElMessage } from 'element-plus'
import DeleteConfirmModal from '@/components/DeleteConfirmModal.vue'
import Toast from '@/components/Toast.vue'
import { useSpeechRecognition } from '@/composables/useSpeechRecognition'
// ===== 已删除：getUserId - 不再需要，改用token =====
// import { getUserId } from '@/utils/userManager.js'
import { stopSSEStream, updateAIMessageContent } from '@/utils/api.js'
import { getToken, getTokenType } from '@/utils/auth.js'
import { renderMarkdown } from '@/utils/markdown'
import 'katex/dist/katex.min.css'

// 导入ReportGenerator相关组件
import QuestionInput from '@/components/QuestionInput.vue'
import CategoryTitle from '@/components/CategoryTitle.vue'
import FileReportCard from '@/components/FileReportCard.vue'
import ExportButton from '@/components/ExportButton.vue'
import StreamMarkdown from '@/components/StreamMarkdown.vue'
import FilePreviewDrawer from '@/components/FilePreviewDrawer.vue'
import WebSearchCapsule from '@/components/WebSearchCapsule.vue'
import WebSearchSidebar from '@/components/WebSearchSidebar.vue'
import WebSearchSummary from '@/components/WebSearchSummary.vue'
import StatusAvatar from '@/components/StatusAvatar.vue'
import { createSSEConnection, closeSSEConnection } from '@/utils/sse'
import { getApiPrefix } from '@/utils/apiConfig'
import { Document } from '@element-plus/icons-vue'

// 导入发送按钮图标
import sendIconEmpty from '@/assets/chat/15.png'
import sendIconFilled from '@/assets/chat/16.png'

// 导入其他图片资源
import newChatIcon from '@/assets/chat/2.png'
import emptyIcon from '@/assets/Chat/22.png'
import aiAvatarIcon from '@/assets/Chat/29.png'
import bridgeIcon from '@/assets/chat/4.png'
import constructionIcon from '@/assets/chat/5.png'
import materialIcon from '@/assets/chat/6.png'
import standardIcon from '@/assets/chat/7.png'
import copyIcon from '@/assets/AIWriting/5.png'
import editIcon from '@/assets/AIWriting/6.png'
import regenerateIcon from '@/assets/AIWriting/7.png'
import deleteIcon from '@/assets/AIWriting/8.png'
import voiceIcon from '@/assets/AIWriting/9.png'
import likeIcon from '@/assets/AIWriting/10.png'
import dislikeIcon from '@/assets/AIWriting/11.png'
import questionIcon1 from '@/assets/chat/12.png'
import questionIcon2 from '@/assets/chat/10.png'
import questionIcon3 from '@/assets/chat/11.png'
import attachmentIcon from '@/assets/chat/9.png'
import voiceInputIcon from '@/assets/Chat/18.png'
import networkSearchIconOn from '@/assets/Chat/24.png'
import networkSearchIconOff from '@/assets/Chat/25.png'
import wordDocIcon from '@/assets/Chat/26.png'
import { Link } from '@element-plus/icons-vue'

import { apis } from '@/request/apis.js'



// 路由实例
const route = useRoute()
const router = useRouter()

// 响应式数据
const messageText = ref('')
const selectedHistoryItem = ref(null) // 选中的历史记录项
const showChat = ref(false) // 控制是否显示聊天界面
const isSending = ref(false) // 控制发送状态
const isOnlineModel = ref(true)  // 是否使用在线大模型

// 切换模型类型
const toggleModelType = () => {
  isOnlineModel.value = !isOnlineModel.value
  showToast(isOnlineModel.value ? '已切换至在线大模型 (glm-4-plus)' : '已切换至本地模型')
}

// 当前激活的模块模式：'ai-qa', 'ai-writing', 'safety-training', 'exam-workshop'
const currentMode = ref('ai-qa')

// 切换到对应模块
const setMode = (mode) => {
  if (currentMode.value === mode) {
    currentMode.value = 'ai-qa' // 再次点击取消选中，回到默认问答
  } else {
    currentMode.value = mode
  }
}

// ReportGenerator相关状态
const categoryExpandStates = ref({})
const currentQuestion = ref('')
let sseConnection = null
const streamingReports = ref(new Map())

// 删除确认弹窗状态
const showDeleteModal = ref(false)
const deleteTargetItem = ref(null) // 要删除的历史记录项
const deleteType = ref('') // 删除类型：'history' 或 'message'

// 功能卡片和热点问题数据
const functionCards = ref([])
const hotQuestions = ref([])

// 聊天消息数据
const chatMessages = ref([])
const messageContentRefs = ref({})
const messageScrollStates = ref({})


// Toast相关
const toastRef = ref(null)
const toastMessage = ref('')
const toastType = ref('success')
const toastDuration = ref(2000)

// 显示Toast提示
const showToast = (message, type = 'success', duration = 2000) => {
  toastMessage.value = message
  toastType.value = type
  toastDuration.value = duration
  
  // 显示Toast
  if (toastRef.value) {
    toastRef.value.show()
  }
}

// 语音功能
const {
  isSupported: speechSupported,
  isListening,
  isSpeaking: speechIsSpeaking,
  transcript,
  error: speechError,
  startListening,
  stopListening,
  speakText,
  stopSpeaking
} = useSpeechRecognition()

// 记录正在朗读的消息ID
const speakingMessageId = ref(null)

// 页面卸载事件处理函数
const handlePageUnload = () => {
  if (speakingMessageId.value) {
    stopAllAudio()
    speakingMessageId.value = null
  }
}

// 页面可见性变化处理函数
const handleVisibilityChange = () => {
  if (document.hidden && speakingMessageId.value) {
    stopAllAudio()
    speakingMessageId.value = null
  }
}


// 文件上传相关
const fileInput = ref(null)
const selectedFile = ref(null)
const isUploadingFile = ref(false)
const fileContent = ref('') // 存储文件内容

// 用户推荐问题相关
const userRecommendQuestions = ref([]) // 用户输入时获取的推荐问题
const isGettingRecommendQuestions = ref(false) // 是否正在获取推荐问题
const recommendQuestionsTimer = ref(null) // 防抖定时器

// AI回复相关推荐问题
const aiRelatedQuestions = ref([]) // AI回复后的相关推荐问题
const isGettingRelatedQuestions = ref(false) // 是否正在获取相关推荐问题
const relatedQuestionsMessageId = ref(null) // 关联的消息ID
const isAIReplyProcessComplete = ref(true) // AI回复流程是否完成（包括联网搜索和推荐问题）

// 联网搜索相关
const isNetworkSearchEnabled = ref(true) // 联网搜索是否启用，默认为true
const onlineSearchResults = ref({}) // 存储每个消息的联网搜索结果
const isGettingOnlineSearch = ref(false) // 是否正在获取联网搜索结果
const onlineSearchLoadingMessages = ref(new Set()) // 记录正在加载联网搜索的消息ID

// 搜索来源展开状态
const expandedSearchSources = ref({}) // 记录每个消息的搜索来源展开状态
const expandedOnlineSearchResults = ref({}) // 记录每个消息的联网搜索结果展开状态

// 网络搜索结果数据（新增）
const webSearchSidebarVisible = ref(false) // 网络搜索侧边栏显示状态
const currentWebSearchData = ref({
  results: [],
  keywords: [],
  total: 0
}) // 当前查看的网络搜索数据

// 搜索来源数据现在从历史记录中动态获取，不再使用模拟数据

// 文件处理配置
const fileConfig = reactive({
  maxSize: 20 * 1024 * 1024, // 20MB
  allowedTypes: ['.docx'] // 只允许.docx格式的Word文档
})

// 文件预览相关
const showFilePreview = ref(false)
const previewFilePath = ref('')
const previewFileName = ref('')

// 计算属性 - 是否有正在打字的AI消息或AI回复流程未完成
const hasTypingMessage = computed(() => {
  return chatMessages.value.some(message => message.type === 'ai' && message.isTyping) || !isAIReplyProcessComplete.value
})

// ReportGenerator相关计算属性
const exportTitle = computed(() => {
  if (currentQuestion.value) {
    return currentQuestion.value.substring(0, 20) + (currentQuestion.value.length > 20 ? '...' : '')
  }
  return 'AI问题分析报告'
})

// 计算属性 - 是否有正在加载的AI消息（内容为空且正在打字）
const hasLoadingMessage = computed(() => {
  return chatMessages.value.some(message => 
    message.type === 'ai' && 
    message.isTyping && 
    (!message.content || message.content.trim() === '')
  )
})

// 计算属性 - 是否有正在打字的AI消息（有内容）
const hasTypingWithContent = computed(() => {
  return chatMessages.value.some(message => 
    message.type === 'ai' && 
    message.isTyping && 
    message.content && 
    message.content.trim() !== ''
  )
})

// 删除确认消息
const deleteConfirmMessage = computed(() => {
  if (deleteType.value === 'history') {
    const title = deleteTargetItem.value?.item?.title || ''
    return `确定要删除历史记录"${title}"吗？删除后将无法恢复。`
  } else if (deleteType.value === 'message') {
    return '确定要删除这条消息吗？删除后将无法恢复。'
  }
  return '确定要删除吗？删除后将无法恢复。'
})

// 删除确认标题
const deleteConfirmTitle = computed(() => {
  if (deleteType.value === 'history') {
    return '删除历史记录'
  } else if (deleteType.value === 'message') {
    return '删除消息'
  }
  return '删除确认'
})

// 处理AI回复中的特殊字符和表情符号
const processAIResponse = (text) => {
  if (!text) return text
  
  try {
    // URL解码
    if (text.includes('%')) {
      text = decodeURIComponent(text)
    }
    
    // Unicode转义序列
    if (text.includes('\\u')) {
      text = text.replace(/\\u[\dA-F]{4}/gi, (match) => {
        return String.fromCharCode(parseInt(match.replace(/\\u/g, ''), 16))
      })
    }
    
    // HTML实体解码
    if (text.includes('&')) {
      const textarea = document.createElement('textarea')
      textarea.innerHTML = text
      text = textarea.value
    }
    
    // LaTeX公式转换
    return convertLatexToDisplay(text)
  } catch (error) {
    console.warn('文本处理失败:', error)
    return text
  }
}

// 打字机效果函数
const typewriterIntervals = new Map() // 存储每个消息的打字机定时器
const reportTypewriters = new Map() // 存储每个报告字段的打字机定时器

const startTypewriterEffect = (message, fullContent, speed = 30) => {
  return new Promise((resolve) => {
    // 如果已经有打字机在运行,先清除
    if (typewriterIntervals.has(message.id)) {
      clearInterval(typewriterIntervals.get(message.id))
      typewriterIntervals.delete(message.id)
    }
    
    let currentIndex = 0
    message.displayContent = ''
    message.isTyping = true
    
    const interval = setInterval(() => {
      if (currentIndex < fullContent.length) {
        // 每次增加的字符数(速度越快,每次增加越多)
        const charsToAdd = Math.max(1, Math.floor(speed / 10))
        currentIndex = Math.min(currentIndex + charsToAdd, fullContent.length)
        
        // 更新显示内容
        message.displayContent = fullContent.substring(0, currentIndex)
      } else {
        // 打字完成
        clearInterval(interval)
        typewriterIntervals.delete(message.id)
        message.isTyping = false
        message.displayContent = fullContent
        
        // 确保状态更新为完成
        if (message.showStats && message.progress < 100) {
          updateMessageStatus(message, 'completed')
        }
        
        resolve()
      }
    }, 1000 / 60) // 60fps
    
    typewriterIntervals.set(message.id, interval)
  })
}

// 为报告字段添加打字机效果
const startReportFieldTypewriter = (report, field, fullContent, speed = 50) => {
  return new Promise((resolve) => {
    const key = `${report.file_index}_${field}`
    
    // 如果已经有打字机在运行,先清除
    if (reportTypewriters.has(key)) {
      clearInterval(reportTypewriters.get(key))
      reportTypewriters.delete(key)
    }
    
    // 初始化打字机状态
    if (!report._typewriterStates) {
      report._typewriterStates = {}
    }
    
    let currentIndex = 0
    report._typewriterStates[field] = { currentIndex: 0, isTyping: true }
    
    const interval = setInterval(() => {
      if (currentIndex < fullContent.length) {
        const charsToAdd = Math.max(1, Math.floor(speed / 10))
        currentIndex = Math.min(currentIndex + charsToAdd, fullContent.length)
        
        // 更新显示内容
        report.report[field] = fullContent.substring(0, currentIndex)
        report._typewriterStates[field].currentIndex = currentIndex
      } else {
        // 打字完成
        clearInterval(interval)
        reportTypewriters.delete(key)
        report._typewriterStates[field].isTyping = false
        report.report[field] = fullContent
        resolve()
      }
    }, 1000 / 60) // 60fps
    
    reportTypewriters.set(key, interval)
  })
}

// 清除所有打字机定时器
const clearAllTypeIntervals = () => {
  typewriterIntervals.forEach((interval, messageId) => {
    clearInterval(interval)
  })
  typewriterIntervals.clear()
  
  reportTypewriters.forEach((interval, key) => {
    clearInterval(interval)
  })
  reportTypewriters.clear()
}

// 处理文件标签格式的回显
const processFileDisplay = (text, file) => {
  if (!file) {
    // 如果没有文件对象，尝试从文本中提取文件信息
    return processFileDisplayFromText(text)
  }
  
  // 查找文件标签并替换为显示格式
  const fileDisplay = `
📄 文件信息：
文件名：${file.name}
文件大小：${formatFileSize(file.size)}
文件类型：${file.type}

📝 文件内容：
${file.content}

---
`
  
  // 替换文件标签为显示格式
  let processedText = text
    .replace(/<word>.*?<\/word>/gs, fileDisplay)
    .replace(/<filename>.*?<\/filename>/g, '')
    .replace(/<filesize>.*?<\/filesize>/g, '')
  
  return processedText
}

// 从文本中提取文件信息并转换为显示格式
const processFileDisplayFromText = (text) => {
  // 提取文件名
  const filenameMatch = text.match(/<filename>(.*?)<\/filename>/)
  const filename = filenameMatch ? filenameMatch[1] : '未知文件'
  
  // 提取文件大小
  const filesizeMatch = text.match(/<filesize>(.*?)<\/filesize>/)
  const filesize = filesizeMatch ? parseInt(filesizeMatch[1]) : 0
  
  // 提取文件内容
  const wordMatch = text.match(/<word>(.*?)<\/word>/s)
  const fileContent = wordMatch ? wordMatch[1].trim() : '无内容'
  
  // 创建文件显示格式
  const fileDisplay = `
📄 文件信息：
文件名：${filename}
文件大小：${formatFileSize(filesize)}
文件类型：${filename.endsWith('.docx') ? '.docx' : filename.endsWith('.doc') ? '.doc' : '未知'}

📝 文件内容：
${fileContent}

---
`
  
  // 替换文件标签为显示格式
  let processedText = text
    .replace(/<word>.*?<\/word>/gs, fileDisplay)
    .replace(/<filename>.*?<\/filename>/g, '')
    .replace(/<filesize>.*?<\/filesize>/g, '')
  
  return processedText
}

// 使用markdown.js渲染Markdown内容
const renderMarkdownContent = (content) => {
  try {
    let html = renderMarkdown(content)
    html = processStandardReferences(html)
    
    nextTick(() => {
      bindStandardReferenceEvents()
    })
    
    return html
  } catch (error) {
    console.error('Markdown渲染失败:', error)
    return content.replace(/\n/g, '<br>')
  }
}

// LaTeX公式转换函数
const convertLatexToDisplay = (text) => {
  if (!text) return text
  
  let convertedText = text
  
  // 希腊字母转换
  const greekLetters = {
    '\\alpha': 'α', '\\beta': 'β', '\\gamma': 'γ', '\\delta': 'δ', '\\epsilon': 'ε',
    '\\varepsilon': 'ε', '\\zeta': 'ζ', '\\eta': 'η', '\\theta': 'θ', '\\iota': 'ι',
    '\\kappa': 'κ', '\\lambda': 'λ', '\\mu': 'μ', '\\nu': 'ν', '\\xi': 'ξ',
    '\\pi': 'π', '\\rho': 'ρ', '\\sigma': 'σ', '\\tau': 'τ', '\\upsilon': 'υ',
    '\\phi': 'φ', '\\chi': 'χ', '\\psi': 'ψ', '\\omega': 'ω',
    '\\Gamma': 'Γ', '\\Delta': 'Δ', '\\Theta': 'Θ', '\\Lambda': 'Λ', '\\Xi': 'Ξ',
    '\\Pi': 'Π', '\\Sigma': 'Σ', '\\Upsilon': 'Υ', '\\Phi': 'Φ', '\\Psi': 'Ψ', '\\Omega': 'Ω'
  }
  
  // 转换希腊字母
  for (const [latex, symbol] of Object.entries(greekLetters)) {
    const regex = new RegExp(latex.replace(/\\/g, '\\\\'), 'g')
    convertedText = convertedText.replace(regex, symbol)
  }
  
  // 分数转换 \frac{a}{b} → a/b
  convertedText = convertedText.replace(/\\frac\{([^}]+)\}\{([^}]+)\}/g, '$1/$2')
  
  // 上标转换 a^b → a^b (保持原样，因为前端可以显示)
  // convertedText = convertedText.replace(/\^(\w+)/g, '^$1')
  
  // 下标转换 a_b → a_b (保持原样，因为前端可以显示)
  // convertedText = convertedText.replace(/_(\w+)/g, '_$1')
  
  // 根号转换 \sqrt{a} → √a
  convertedText = convertedText.replace(/\\sqrt\{([^}]+)\}/g, '√$1')
  
  // 积分符号转换
  convertedText = convertedText.replace(/\\int/g, '∫')
  convertedText = convertedText.replace(/\\sum/g, '∑')
  convertedText = convertedText.replace(/\\prod/g, '∏')
  convertedText = convertedText.replace(/\\partial/g, '∂')
  convertedText = convertedText.replace(/\\nabla/g, '∇')
  convertedText = convertedText.replace(/\\infty/g, '∞')
  
  // 其他数学符号
  convertedText = convertedText.replace(/\\pm/g, '±')
  convertedText = convertedText.replace(/\\times/g, '×')
  convertedText = convertedText.replace(/\\div/g, '÷')
  convertedText = convertedText.replace(/\\leq/g, '≤')
  convertedText = convertedText.replace(/\\geq/g, '≥')
  convertedText = convertedText.replace(/\\neq/g, '≠')
  convertedText = convertedText.replace(/\\approx/g, '≈')
  convertedText = convertedText.replace(/\\equiv/g, '≡')
  convertedText = convertedText.replace(/\\propto/g, '∝')
  
  // 集合符号
  convertedText = convertedText.replace(/\\in/g, '∈')
  convertedText = convertedText.replace(/\\notin/g, '∉')
  convertedText = convertedText.replace(/\\subset/g, '⊂')
  convertedText = convertedText.replace(/\\supset/g, '⊃')
  convertedText = convertedText.replace(/\\cup/g, '∪')
  convertedText = convertedText.replace(/\\cap/g, '∩')
  convertedText = convertedText.replace(/\\emptyset/g, '∅')
  
  // 逻辑符号
  convertedText = convertedText.replace(/\\land/g, '∧')
  convertedText = convertedText.replace(/\\lor/g, '∨')
  convertedText = convertedText.replace(/\\neg/g, '¬')
  convertedText = convertedText.replace(/\\rightarrow/g, '→')
  convertedText = convertedText.replace(/\\leftarrow/g, '←')
  convertedText = convertedText.replace(/\\leftrightarrow/g, '↔')
  convertedText = convertedText.replace(/\\forall/g, '∀')
  convertedText = convertedText.replace(/\\exists/g, '∃')
  
  return convertedText
}

// 处理规范引用 - 将<file></file>标签内容转换为可点击的规范引用
const processStandardReferences = (html) => {
  if (!html) return html
  
  const refStyle = 'background-color: #EAEAEE; color: #616161; font-size: 0.75rem; padding: 3px 8px; border-radius: 6px; cursor: pointer; display: inline-block; margin: 4px 2px; border: 1px solid #EAEAEE; font-weight: 500; transition: all 0.2s ease; line-height: 1.4; max-width: 300px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;'
  
  return html.replace(/<file>(.*?)<\/file>/g, (match, content) => {
    if (/^<span\s+class="standard-reference"/i.test(content)) {
      return match
    }
    
    const standardMatch = content.match(/^([《「『【]?[\s\S]*?[》」』】]?)[\s]*\(([^)]+)\)$/)
    if (standardMatch) {
      return `<span class="standard-reference" data-standard="${content}" title="点击查看标准详情" style="${refStyle}">${content}</span>`
    }
    
    return `<span class="standard-reference" data-reference="${content}" title="点击查看详情" style="${refStyle}">${content}</span>`
  })
}

// 历史记录数据
const historyData = ref([])
const historyTotal = ref(0) // 历史记录总数
const isLoadingHistory = ref(false) // 是否正在加载历史记录

// 获取历史记录列表 (合并所有模块)
const getHistoryRecordList = async () => {
  try {
    isLoadingHistory.value = true
    
    // 分别请求四种业务类型的历史记录
    const businessTypes = [0, 1, 2, 3] // 0:AI问答, 1:安全培训, 2:AI写作, 3:考试工坊
    
    const requests = businessTypes.map(type => 
      apis.getHistoryRecord({ 
        ai_conversation_id: 0,
        business_type: type
      })
    )
    
    const responses = await Promise.all(requests)
    
    let allRecords = []
    let totalCount = 0
    
    responses.forEach(response => {
      if (response.statusCode === 200 && response.data) {
        totalCount += response.total || response.data.length || 0
        allRecords = allRecords.concat(response.data)
      }
    })
    
    // 按时间降序排序
    allRecords.sort((a, b) => new Date(b.updated_at) - new Date(a.updated_at))
    
    historyTotal.value = totalCount
    historyData.value = allRecords.map(conversation => ({
      id: conversation.id,
      title: conversation.title || generateConversationTitle(conversation.content),
      time: formatTime(conversation.updated_at),
      businessType: conversation.business_type,
      isActive: false,
      rawData: conversation
    }))
  } catch (error) {
    console.error('获取历史记录失败:', error)
  } finally {
    isLoadingHistory.value = false
  }
}

// 获取指定对话的详细消息
const getConversationMessages = async (conversationId) => {
  try {
    const response = await apis.getHistoryRecord({ 
      // ===== 已删除：user_id - 后端从token解析 =====
      ai_conversation_id: conversationId,
      business_type: 0
    })
    
    if (response.statusCode === 200) {
      if (!response.data || !Array.isArray(response.data)) {
        console.error('响应数据格式错误')
        return false
      }
      
      const messages = await Promise.all(response.data.map(async (message, index) => {
        const userFeedback = convertUserFeedback(message.user_feedback)
        
        // 如果是用户消息且包含文件标签，提取文件信息
        let file = null
        let userContent = message.content
        
        // 获取前一条用户消息作为AI消息的问题上下文
        let userQuestion = null
        if (message.type === 'ai' && index > 0) {
          const prevMessage = response.data[index - 1]
          if (prevMessage && prevMessage.type === 'user') {
            // 提取用户实际问题（去除文件标签）
            if (prevMessage.content.includes('</filesize>')) {
              const userMessageMatch = prevMessage.content.split('</filesize>')[1]
              userQuestion = userMessageMatch ? userMessageMatch.trim() : prevMessage.content
            } else {
              userQuestion = prevMessage.content
            }
          }
        }
        
        if (message.type === 'user' && message.content.includes('</filesize>')) {
          // 提取文件信息
          const filenameMatch = message.content.match(/<filename>(.*?)<\/filename>/)
          const filesizeMatch = message.content.match(/<filesize>(.*?)<\/filesize>/)
          const wordMatch = message.content.match(/<word>(.*?)<\/word>/s)
          
          if (filenameMatch && filesizeMatch) {
            const filename = filenameMatch[1]
            const filesize = parseInt(filesizeMatch[1])
            const fileContent = wordMatch ? wordMatch[1].trim() : ''
            
            // 创建文件对象
            file = {
              name: filename,
              size: filesize,
              type: filename.endsWith('.docx') ? '.docx' : filename.endsWith('.doc') ? '.doc' : '.docx',
              icon: getFileIcon(filename.endsWith('.docx') ? '.docx' : filename.endsWith('.doc') ? '.doc' : '.docx'),
              content: fileContent
            }
            
            // 提取用户实际说的话（</filesize>标签后的内容）
            const userMessageMatch = message.content.split('</filesize>')[1]
            userContent = userMessageMatch ? userMessageMatch.trim() : ''
          }
        }
        
        // 为AI消息准备displayContent
        let displayContent = userContent || ''
        let reports = []
        let summary = message.summary || '' // 从后端恢复summary字段
        
        if (message.type === 'ai') {
          try {
            const contentStr = message.content || ''
            
            // 尝试解析content为JSON
            if (contentStr.trim().startsWith('[') || contentStr.trim().startsWith('{')) {
              try {
                const parsedContent = JSON.parse(contentStr)
                
                // 检查是否是新格式（包含reports和webSearch数据）
                if (parsedContent.reports && Array.isArray(parsedContent.reports)) {
                  reports = parsedContent.reports
                  // 恢复网络搜索数据
                  if (parsedContent.webSearchRaw) {
                    message.webSearchRaw = parsedContent.webSearchRaw
                  }
                  if (parsedContent.webSearchSummary) {
                    message.webSearchSummary = parsedContent.webSearchSummary
                    message.hasWebSearchResults = parsedContent.hasWebSearchResults || false
                  }
                  // ===== 🔧 修复：从content JSON中恢复summary =====
                  if (parsedContent.summary) {
                    summary = parsedContent.summary
                  }
                } else if (Array.isArray(parsedContent)) {
                  // 旧格式，直接是reports数组
                  reports = parsedContent
                } else {
                  throw new Error('Not an array or valid format')
                }
              } catch (jsonError) {
                // JSON解析失败,当作普通Markdown文本处理
                let processedContent = contentStr
                  .replace(/\\n/g, '\n')
                  .replace(/\\t/g, '\t')
                  .replace(/\\r/g, '\r')
                
                displayContent = renderMarkdownContent(processedContent)
              }
            } else {
              // 不是JSON格式,直接按Markdown处理
              let processedContent = contentStr
                .replace(/\\n/g, '\n')
                .replace(/\\t/g, '\t')
                .replace(/\\r/g, '\r')
              
              displayContent = renderMarkdownContent(processedContent)
            }
          } catch (error) {
            console.error('历史记录处理失败:', error)
            displayContent = message.content || ''
          }
        }
        
        // 如果有reports,计算相关统计信息
        let totalFiles = 0
        let completedCount = 0
        let progress = 100
        
        if (reports.length > 0) {
          // 过滤掉category_title类型,只统计实际报告
          const actualReports = reports.filter(r => r.type !== 'category_title')
          totalFiles = actualReports.length
          completedCount = actualReports.filter(r => r.status === 'completed').length
          progress = totalFiles > 0 ? Math.round((completedCount / totalFiles) * 100) : 100
        }
        
        return {
          type: message.type, // 'user' 或 'ai'
          content: userContent, // 使用提取的用户消息
          displayContent: displayContent,
          reports: reports, // 添加reports数组
          summary: summary, // 添加summary字段
          totalFiles: totalFiles, // 总文件数
          completedCount: completedCount, // 完成数
          progress: progress, // 进度
          file: file, // 添加文件对象
          isTyping: false,
          id: message.id,
          userFeedback: userFeedback,
          userQuestion: userQuestion, // AI消息对应的用户问题
          searchSources: message.type === 'ai' && message.search_source ? parseSearchSources(message.search_source) : null, // 解析搜索来源
          // 保存原始数据
          rawData: message,
          // 网络搜索数据（如果有）
          webSearchRaw: message.webSearchRaw || null,
          webSearchSummary: message.webSearchSummary || null,
          hasWebSearchResults: message.hasWebSearchResults || false,
          webSearchTotal: message.webSearchRaw?.total || 0,
          // 状态管理（历史记录默认完成状态）
          showStats: totalFiles > 0,
          currentStatus: 'completed',
          statusMessage: totalFiles > 0 
            ? (message.webSearchRaw?.total > 0 
                ? ` <span class="ai-name">蜀道安全管理AI智能助手</span>正在为您分析 <span class="file-count">${totalFiles}</span> 个知识库文件，以及 <span class="file-count">${message.webSearchRaw.total}</span> 个相关网络资源`
                : ` <span class="ai-name">蜀道安全管理AI智能助手</span>正在为您分析 <span class="file-count">${totalFiles}</span> 个知识库文件`)
            : ''
        }
      }))
      
      chatMessages.value = messages
      ai_conversation_id.value = conversationId
      
      const lastAIMessage = messages.filter(msg => msg.type === 'ai').pop()
      
      // 恢复所有AI消息的联网搜索结果、推荐问题和分类展开状态
      messages.forEach((message, index) => {
        if (message.type === 'ai' && message.rawData) {
          // 恢复联网搜索结果
          if (message.rawData.search_source) {
            try {
              const searchResults = JSON.parse(message.rawData.search_source)
              if (Array.isArray(searchResults) && searchResults.length > 0) {
                onlineSearchResults.value[message.id] = searchResults
              }
            } catch (error) {
              console.error('解析搜索结果失败:', error)
            }
          }
          
          // 恢复reports的分类展开状态
          if (message.reports && message.reports.length > 0) {
            if (!categoryExpandStates.value[index]) {
              categoryExpandStates.value[index] = {}
            }
            
            const categories = message.reports
              .filter(r => r.type === 'category_title')
              .map(r => r.category)
            
            categories.forEach(category => {
              categoryExpandStates.value[index][category] = true
            })
          }
          
          // 恢复推荐问题（只处理最后一条AI消息）
          if (message === lastAIMessage && message.rawData.guess_you_want) {
            try {
              const questions = message.rawData.guess_you_want.trim()
                .split('\n')
                .map(q => q.trim())
                .filter(q => q.length > 0)
                .filter((q, index, arr) => arr.indexOf(q) === index)
                .slice(0, 3)
              
              if (questions.length > 0) {
                aiRelatedQuestions.value = questions
                relatedQuestionsMessageId.value = message.id
              }
            } catch (error) {
              console.error('解析推荐问题失败:', error)
            }
          }
        }
      })
      
      // 等待DOM更新后绑定规范引用事件
      await nextTick()
      setTimeout(() => bindStandardReferenceEvents(), 100)
      
      return true
    } else {
      console.error('获取对话消息失败:', response.statusCode)
      return false
    }
  } catch (error) {
    console.error('获取对话消息失败:', error)
    return false
  }
}

// 生成对话标题（从内容中提取）
const generateConversationTitle = (content) => {
  if (!content) return '未知对话'
  
  // 检查是否包含文件标签格式
  if (content.includes('</filesize>')) {
    // 提取</filesize>标签后面的内容
    const userMessage = content.split('</filesize>')[1]
    if (userMessage && userMessage.trim()) {
      // 清理多余的空格和换行
      const cleanMessage = userMessage.replace(/\s+/g, ' ').trim()
      
      // 提取第一句话作为标题，但排除AI回复的开头
      let firstSentence = cleanMessage.split(/[。！？\n]/)[0]
      
      // 如果包含AI回复的开头，只取用户问题部分
      if (firstSentence.includes('基于您好') || firstSentence.includes('蜀道安全管理AI智能助手')) {
        // 提取"问题描述:"后面的内容
        const problemMatch = firstSentence.match(/问题描述[：:](.+?)(?=分析结果|$)/)
        if (problemMatch) {
          firstSentence = problemMatch[1].trim()
        } else {
          // 如果没有找到问题描述，取前20个字符
          firstSentence = firstSentence.substring(0, 20)
        }
      }
      
      // 限制标题长度
      if (firstSentence.length > 30) {
        return firstSentence.substring(0, 30) + '...'
      }
      
      return firstSentence || '新对话'
    }
  }
  
  // 如果没有文件标签，使用原来的方法
  let cleanContent = content.replace(/<[^>]*>/g, '')
  cleanContent = cleanContent.replace(/\s+/g, ' ').trim()
  
  // 提取第一句话作为标题，但排除AI回复的开头
  let firstSentence = cleanContent.split(/[。！？\n]/)[0]
  
  // 如果包含AI回复的开头，只取用户问题部分
  if (firstSentence.includes('基于您好') || firstSentence.includes('蜀道安全管理AI智能助手')) {
    // 提取"问题描述:"后面的内容
    const problemMatch = firstSentence.match(/问题描述[：:](.+?)(?=查询结果|$)/)
    if (problemMatch) {
      firstSentence = problemMatch[1].trim()
    } else {
      // 如果没有找到问题描述，取前20个字符
      firstSentence = firstSentence.substring(0, 20)
    }
  }
  
  // 限制标题长度
  if (firstSentence.length > 30) {
    return firstSentence.substring(0, 30) + '...'
  }
  
  return firstSentence || '新对话'
}

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return '未知时间'
  
  let date
  if (typeof timestamp === 'string') {
    date = new Date(timestamp)
  } else {
    let timestampMs = timestamp
    if (timestamp.toString().length === 10 || timestamp.toString().length === 11) {
      timestampMs = timestamp * 1000
    }
    date = new Date(timestampMs)
  }
  
  const now = new Date()
  const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate())
  const yesterdayStart = new Date(todayStart.getTime() - 24 * 60 * 60 * 1000)
  
  if (date >= todayStart) {
    return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  }
  
  if (date >= yesterdayStart && date < todayStart) {
    return '昨天 ' + date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  }
  
  const month = date.getMonth() + 1
  const day = date.getDate()
  const time = date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  return `${month}月${day}日 ${time}`
}

// 转换用户反馈状态
const convertUserFeedback = (feedback) => {
  switch (parseInt(feedback)) {
    case 2: return 'like'
    case 3: return 'dislike'
    default: return null
  }
}

// 转换前端反馈状态为后端格式
const convertFeedbackToBackend = (feedback) => {
  switch (feedback) {
    case 'like': return 2
    case 'dislike': return 3
    default: return 0
  }
}

// 解析搜索来源数据
const parseSearchSources = (searchSourceStr) => {
  try {
    if (!searchSourceStr || typeof searchSourceStr !== 'string' || !searchSourceStr.trim()) {
      return null
    }
    
    const sources = JSON.parse(searchSourceStr)
    
    if (!Array.isArray(sources)) {
      return null
    }
    
    const validSources = sources.filter(source => 
      source && typeof source === 'object' && source.title && source.content
    )
    
    return validSources.length > 0 ? validSources : null
  } catch (error) {
    console.error('解析搜索来源失败:', error)
    return null
  }
}

//对话id
const ai_conversation_id = ref(0)
//业务类型
const business_type = ref(0)

// 清理新对话状态
const clearNewConversationState = () => {
  if (chatMessages.value.length === 0) {
    historyData.value.forEach(item => item.isActive = false)
    expandedSearchSources.value = {}
    expandedOnlineSearchResults.value = {}
    onlineSearchResults.value = {}
  }
}

// 发送消息
const handleSendMessage = async () => {
  if (!messageText.value.trim() || isSending.value) return
    
  clearRecommendQuestions()
  aiRelatedQuestions.value = []
  relatedQuestionsMessageId.value = null
  isSending.value = true
  showChat.value = true
    
  clearNewConversationState()
  
  if (currentMode.value === 'ai-writing' || currentMode.value === 'safety-training') {
    await handleNonStreamingSubmit({
      question: messageText.value,
      businessType: currentMode.value === 'ai-writing' ? 2 : 1
    })
  } else {
    await handleReportGeneratorSubmit({
      question: messageText.value,
      windowSize: 3,
      nResults: 10
    })
  }
    
  messageText.value = ''
  clearRecommendQuestions()
  
  if (selectedFile.value) {
    removeSelectedFile()
  }
  
  scrollToBottom()
}

// 处理非流式请求 (AI写作 和 安全培训)
const handleNonStreamingSubmit = async (data) => {
  currentQuestion.value = data.question
  
  // 添加用户消息
  chatMessages.value.push({
    id: Date.now(),
    type: 'user',
    content: data.question,
    timestamp: new Date().toISOString()
  })
  
  // 添加AI消息占位符
  const aiMessageIndex = chatMessages.value.length
  chatMessages.value.push({
    id: Date.now() + 1,
    type: 'ai',
    userQuestion: data.question,
    isTyping: true, // 显示 loading 状态
    content: '',
    displayContent: '',
    timestamp: new Date().toISOString(),
    reports: []
  })
  
  try {
    const response = await apis.sendDeepseekMessage({
      user_question: data.question,
      business_type: data.businessType,
      enable_online_model: isOnlineModel.value,
      ai_conversation_id: ai_conversation_id.value
    })

    if (response.statusCode === 200) {
      const aiMessage = chatMessages.value[aiMessageIndex]
      aiMessage.isTyping = false
      aiMessage.content = response.data
      
      // 更新 conversation ID
      if (response.ai_conversation_id) {
        ai_conversation_id.value = response.ai_conversation_id
      }
      
      // 添加打字机效果显示
      if (data.businessType === 1) {
        // 安全培训: 只展示一个输出文档
        aiMessage.isDocument = true
        aiMessage.displayContent = `<div class="safety-training-doc-card">
          <div class="doc-header">
            <span class="doc-icon">📄</span>
            <span class="doc-title">安全培训生成文档</span>
          </div>
          <div class="doc-actions">
            <button class="view-doc-btn">查看详情</button>
          </div>
        </div>`
        // 实际内容保存起来，点击查看详情时可以使用
        aiMessage.fullContent = response.data
      } else {
        // AI写作等: 正常打字机输出
        startTypewriterEffect(aiMessage, response.data, 30)
      }
      
      // 刷新历史记录
      getHistoryRecordList()
    } else {
      throw new Error(response.msg || '请求失败')
    }
  } catch (error) {
    console.error('发送请求失败:', error)
    const aiMessage = chatMessages.value[aiMessageIndex]
    aiMessage.isTyping = false
    aiMessage.displayContent = '抱歉，生成内容时发生错误，请重试。'
    ElMessage.error(`请求失败: ${error.message}`)
  } finally {
    isSending.value = false
  }
}
// 功能卡片图标计数器
let functionCardIconIndex = 0
// 推荐问题图标计数器
let questionIconIndex = 0

// 根据功能卡片标题返回对应的图标
const getFunctionCardIcon = (title) => {
  // 按顺序循环使用4个图标
  const icons = [bridgeIcon, constructionIcon, materialIcon, standardIcon]
  const icon = icons[functionCardIconIndex % icons.length]
  functionCardIconIndex++
  return icon
}

// 根据问题标题返回对应的图标
const getQuestionIcon = (question) => {
  // 按顺序循环使用3个图标
  const icons = [questionIcon1, questionIcon2, questionIcon3]
  const icon = icons[questionIconIndex % icons.length]
  questionIconIndex++
  return icon
}

// 点击功能卡片
// ReportGenerator相关方法
const handleCategoryToggle = (messageIndex, data) => {
  if (!categoryExpandStates.value[messageIndex]) {
    categoryExpandStates.value[messageIndex] = {}
  }
  categoryExpandStates.value[messageIndex][data.category] = data.expanded
}

const isCategoryExpanded = (messageIndex, category) => {
  if (!category) return true
  if (!categoryExpandStates.value[messageIndex]) {
    categoryExpandStates.value[messageIndex] = {}
    return true
  }
  return categoryExpandStates.value[messageIndex][category] !== false
}

// 处理安全培训文档点击
const handleSafetyDocClick = (message) => {
  if (message.rawData && message.rawData.ai_conversation_id) {
    router.push({ path: '/safety-hazard', query: { id: message.rawData.ai_conversation_id } })
  } else if (ai_conversation_id.value) {
    router.push({ path: '/safety-hazard', query: { id: ai_conversation_id.value } })
  }
}

// 检查reports数组是否只包含分类标题，没有实际报告
const hasOnlyCategoryTitles = (reports) => {
  if (!reports || reports.length === 0) return false
  // 检查是否所有报告都是category_title类型
  return reports.every(r => r.type === 'category_title')
}

// 将消息状态映射到头像状态
const getAvatarStatus = (currentStatus, progress) => {
  if (progress === 100) return 'completed'
  
  switch (currentStatus) {
    case 'querying_kb':
    case 'web_searching':
      return 'searching'
    case 'analyzing_files':
    case 'analyzing_web':
      return 'analyzing'
    case 'deep_thinking':
      return 'thinking'
    case 'outputting':
      return 'analyzing'
    case 'completed':
      return 'completed'
    case 'error':
      return 'error'
    default:
      return 'idle'
  }
}

// 更新AI消息状态和进度
const updateMessageStatus = (aiMessage, status, customMessage = null) => {
  const statusConfig = {
    querying_kb: {
      message: '🔍 <span class="ai-name">蜀道安全管理AI智能助手</span>正在为您分析知识库……',
      progress: 10
    },
    web_searching: {
      message: '🌐 <span class="ai-name">蜀道安全管理AI智能助手</span>正在为您联网分析……',
      progress: 15
    },
    data_retrieved: {
      message: null, // 动态生成
      progress: 30
    },
    analyzing_files: {
      message: '😊 <span class="ai-name">蜀道安全管理AI智能助手</span>正在为您分析文件内容……',
      progress: 45
    },
    analyzing_web: {
      message: '😉 <span class="ai-name">蜀道安全管理AI智能助手</span>正在分析联网数据……',
      progress: 70
    },
    deep_thinking: {
      message: '🤔 <span class="ai-name">蜀道安全管理AI智能助手</span>正在深度思考中，请您稍等片刻……',
      progress: 75
    },
    outputting: {
      message: '😄 <span class="ai-name">蜀道安全管理AI智能助手</span>正在整理分析中！',
      progress: 90
    },
    completed: {
      message: null, // 动态生成
      progress: 100
    }
  }
  
  const config = statusConfig[status]
  if (config) {
    aiMessage.currentStatus = status
    
    // 对于data_retrieved状态，生成动态消息
    if (status === 'data_retrieved') {
      const kbCount = aiMessage.totalFiles || 0
      const webCount = aiMessage.webSearchTotal || 0
      
      if (webCount > 0) {
        aiMessage.statusMessage = `<span class="ai-name">蜀道安全管理AI智能助手</span>正在为您分析 <span class="file-count">${kbCount}</span> 个知识库文件，以及 <span class="file-count">${webCount}</span> 个相关网络资源`
      } else {
        aiMessage.statusMessage = `<span class="ai-name">蜀道安全管理AI智能助手</span>正在为您分析 <span class="file-count">${kbCount}</span> 个知识库文件`
      }
    } else if (status === 'completed') {
      // 对于completed状态，生成动态完成消息
      const kbCount = aiMessage.totalFiles || 0
      const webCount = aiMessage.webSearchTotal || 0
      
      if (webCount > 0) {
        aiMessage.statusMessage = `✅ <span class="ai-name">蜀道安全管理AI智能助手</span>已为您检索到 <span class="file-count">${kbCount}</span> 个知识库文件，以及 <span class="file-count">${webCount}</span> 个相关网络资源`
      } else {
        aiMessage.statusMessage = `✅ <span class="ai-name">蜀道安全管理AI智能助手</span>已为您检索到 <span class="file-count">${kbCount}</span> 个知识库文件`
      }
    } else {
      aiMessage.statusMessage = customMessage || config.message
    }
    
    aiMessage.progress = config.progress
  }
}

const handleSSEMessage = (data, aiMessageIndex) => {
  const aiMessage = chatMessages.value[aiMessageIndex]
  if (!aiMessage) return
  
  // 🔍 调试：打印SSE返回的完整数据对象
  console.log('🔍 SSE事件完整数据:', {
    type: data.type,
    conversation_id: data.conversation_id,
    message_id: data.message_id,
    ai_conversation_id: data.ai_conversation_id,
    ai_message_id: data.ai_message_id,
    allKeys: Object.keys(data)
  })
  
  // 捕获conversation_id（后端返回的字段名，可能是conversation_id或ai_conversation_id）
  const conversationId = data.conversation_id || data.ai_conversation_id
  if (conversationId) {
    if (ai_conversation_id.value === 0) {
      ai_conversation_id.value = conversationId
      console.log('✅ SSE收到conversation_id并赋值:', conversationId)
    }
  }
  
  // 捕获message_id（后端返回的字段名，可能是message_id或ai_message_id）
  const messageId = data.message_id || data.ai_message_id
  if (messageId) {
    if (!aiMessage.ai_message_id) {
      aiMessage.ai_message_id = messageId
      console.log('✅ SSE收到message_id并赋值:', messageId)
      console.log('  - aiMessage.id (前端临时ID):', aiMessage.id)
      console.log('  - aiMessage.ai_message_id (后端ID):', aiMessage.ai_message_id)
      
      // 同时更新rawData对象，确保操作按钮能够使用正确的ID
      if (!aiMessage.rawData) {
        aiMessage.rawData = {}
      }
      aiMessage.rawData.id = messageId
      console.log('  - aiMessage.rawData.id:', aiMessage.rawData.id)
    }
  }
  
  switch (data.type) {
    case 'intent':
      // 检查是否为专业问题
      if (data.is_professional_question === false) {
        // 非专业问题：立即隐藏状态显示组件
        aiMessage.showStats = false

        // 非专业问题,只输出summary字段内容并终止流程
        const summaryContent = data.summary || '抱歉,我暂时无法回答您的问题。'

        // 先缓存summary作为兜底内容，但继续等待online_answer/completed事件
        aiMessage.summary = summaryContent
        aiMessage._fullSummary = summaryContent
        break
      }

      // 专业问题：意图识别完成，更新为查询知识库状态
      updateMessageStatus(aiMessage, 'querying_kb')

      // 如果启用联网搜索，稍后会更新为web_searching状态
      // （当收到web_search_raw事件时）

      // 保存问题总结并使用打字机效果
      if (data.summary) {
        const fullSummary = data.summary
        aiMessage._fullSummary = fullSummary
        aiMessage.summary = ''

        // 使用打字机效果显示问题总结
        startReportFieldTypewriter(
          { file_index: 'summary', report: aiMessage, _typewriterStates: {} },
          'summary',
          fullSummary,
          50
        ).catch(err => {
          console.error('问题总结打字机效果失败:', err)
          aiMessage.summary = fullSummary
        })
      }
      break

    case 'online_answer': {
      aiMessage.showStats = false
      aiMessage.summary = ''

      const finalContent = data.content || ''
      aiMessage.content = finalContent

      if (!finalContent.trim()) {
        aiMessage.displayContent = ''
        aiMessage.isTyping = false
        break
      }

      const processedReply = processAIResponse(finalContent)
      const renderedReply = renderMarkdownContent(processedReply)

      startTypewriterEffect(aiMessage, renderedReply, 200)
        .catch(err => {
          console.error('在线回答打字机效果失败:', err)
          aiMessage.displayContent = renderedReply
          aiMessage.isTyping = false
        })
      break
    }

    case 'online_error':
      aiMessage.showStats = false
      aiMessage.content = data.message || '在线模型服务暂不可用'
      aiMessage.displayContent = renderMarkdownContent(processAIResponse(aiMessage.content))
      aiMessage.isTyping = false
      break
      
    case 'documents':
      aiMessage.totalFiles = data.total
      aiMessage.completedCount = 0
      
      // 收到文档数据后的状态处理
      if (isNetworkSearchEnabled.value) {
        // 如果启用了联网搜索，更新状态为联网搜索中
        updateMessageStatus(aiMessage, 'web_searching')
        // 等待web_search_raw事件后再更新为data_retrieved
      } else {
        // 如果没有联网搜索，直接显示检索结果
        updateMessageStatus(aiMessage, 'data_retrieved')
      }
      
      // 文档数量更新后，触发滚动检测以初始化进度卡片
      nextTick(() => {
        handleProgressCardScroll()
      })
      break
      
    case 'category_title':
      // 第一个分类标题时，说明开始分析文件
      if (aiMessage.reports.length === 0) {
        // 只有在当前状态进度 >= data_retrieved的进度时，才更新为analyzing_files
        // 这样确保data_retrieved状态能被看到
        if (aiMessage.progress >= 30) {
          updateMessageStatus(aiMessage, 'analyzing_files')
        }
      }
      
      const categoryTitle = {
        type: 'category_title',
        category: data.category,
        number: data.number,
        count: data.count,
        source_file: `【${data.number}、${data.category}】（共${data.count}个文件）`,
        file_index: -1,
        status: 'category'
      }
      aiMessage.reports.push(categoryTitle)
      
      // 初始化该分类为展开状态
      if (!categoryExpandStates.value[aiMessageIndex]) {
        categoryExpandStates.value[aiMessageIndex] = {}
      }
      categoryExpandStates.value[aiMessageIndex][data.category] = true
      
      // 保存当前分类名称,用于后续报告匹配
      aiMessage.currentCategory = data.category
      break
    
    case 'report_start':
      // 调试日志：查看完整的数据结构
      console.log('🔍 [DEBUG] report_start 数据:', {
        file_index: data.file_index,
        source_file: data.source_file,
        file_path: data.file_path,
        metadata: data.metadata,
        完整data: data
      })
      
      const placeholderReport = {
        file_index: data.file_index,
        total_files: aiMessage.totalFiles,
        source_file: data.source_file,
        file_path: data.file_path,
        similarity: data.similarity,
        metadata: {
          ...data.metadata,
          _displayCategory: aiMessage.currentCategory // 存储当前显示的分类名
        },
        report: {
          display_name: '',
          summary: '',
          analysis: '',
          clauses: ''
        },
        status: 'streaming'
      }
      aiMessage.reports.push(placeholderReport)
      streamingReports.value.set(data.file_index, aiMessage.reports.length - 1)
      break
    
    case 'report_chunk':
      // 不再处理report_chunk,等待完整的report消息后用打字机效果显示
      // 这样可以避免与打字机效果冲突
      break
      
    case 'report':
      // 第一个报告开始时，更新到深度思考状态
      if (aiMessage.reports.filter(r => r.status === 'completed').length === 0) {
        updateMessageStatus(aiMessage, 'deep_thinking')
      }
      
      const reportData = data.data || data
      
      // 调试日志：查看完整的report数据
      console.log('🔍 [DEBUG] report 数据:', {
        file_index: reportData.file_index,
        source_file: reportData.source_file,
        file_path: reportData.file_path,
        metadata: reportData.metadata,
        完整reportData: reportData
      })
      
      const idx = streamingReports.value.get(reportData.file_index)
      
      let targetReport
      if (idx !== undefined) {
        const displayCategory = aiMessage.reports[idx].metadata?._displayCategory
        const fullSummary = reportData.report?.summary || ''
        const fullAnalysis = reportData.report?.analysis || ''
        const fullClauses = reportData.report?.clauses || ''
        const fullDisplayName = reportData.report?.display_name || ''
        
        // 创建带空内容的报告对象，保留所有原始字段
        aiMessage.reports[idx] = { 
          ...reportData, // 保留所有原始字段，包括可能的链接字段
          report: {
            display_name: fullDisplayName, // 直接显示
            summary: '',
            analysis: '',
            clauses: ''
          },
          status: 'completed',
          metadata: {
            ...reportData.metadata, // 保留所有metadata字段
            _displayCategory: displayCategory || aiMessage.currentCategory
          },
          _fullContent: {
            display_name: fullDisplayName,
            summary: fullSummary,
            analysis: fullAnalysis,
            clauses: fullClauses
          }
        }
        targetReport = aiMessage.reports[idx]
        streamingReports.value.delete(reportData.file_index)
      } else {
        const fullSummary = reportData.report?.summary || ''
        const fullAnalysis = reportData.report?.analysis || ''
        const fullClauses = reportData.report?.clauses || ''
        const fullDisplayName = reportData.report?.display_name || ''
        
        const newReport = { 
          ...reportData, // 保留所有原始字段，包括可能的链接字段
          report: {
            display_name: fullDisplayName, // 直接显示
            summary: '',
            analysis: '',
            clauses: ''
          },
          status: 'completed',
          metadata: {
            ...reportData.metadata, // 保留所有metadata字段
            _displayCategory: aiMessage.currentCategory
          },
          _fullContent: {
            display_name: fullDisplayName,
            summary: fullSummary,
            analysis: fullAnalysis,
            clauses: fullClauses
          }
        }
        aiMessage.reports.push(newReport)
        targetReport = newReport
      }
      
      // 使用顺序打字机效果：概述 -> 解析 -> 相关条款
      if (targetReport._fullContent && !targetReport._typewriterCompleted) {
        // 标记打字机已启动，防止重复触发
        targetReport._typewriterStarted = true
        
        // 先打概述（速度200 = 每次20个字符，极快）
        startReportFieldTypewriter(targetReport, 'summary', targetReport._fullContent.summary || '', 200)
          .then(() => {
            // 概述完成后打解析
            return startReportFieldTypewriter(targetReport, 'analysis', targetReport._fullContent.analysis || '', 200)
          })
          .then(() => {
            // 解析完成后打相关条款
            if (targetReport._fullContent.clauses) {
              return startReportFieldTypewriter(targetReport, 'clauses', targetReport._fullContent.clauses || '', 200)
            }
          })
          .then(() => {
            // 全部完成，标记为已完成
            targetReport._typewriterCompleted = true
          })
          .catch(err => {
            console.error('报告打字机效果失败:', err)
            // 失败时直接显示完整内容
            targetReport.report.summary = targetReport._fullContent.summary || ''
            targetReport.report.analysis = targetReport._fullContent.analysis || ''
            targetReport.report.clauses = targetReport._fullContent.clauses || ''
            targetReport._typewriterCompleted = true
          })
        
        console.log('📝 [DEBUG] 报告打字机已启动:', {
          file_index: targetReport.file_index,
          summary_length: targetReport._fullContent.summary?.length || 0,
          analysis_length: targetReport._fullContent.analysis?.length || 0,
          clauses_length: targetReport._fullContent.clauses?.length || 0
        })
      }
      
      // 更新进度
      aiMessage.completedCount = aiMessage.reports.filter(r => r.status === 'completed' && r.type !== 'category_title').length
      const reportProgress = aiMessage.totalFiles > 0 ? (aiMessage.completedCount / aiMessage.totalFiles) : 0
      
      // 根据报告完成度更新状态
      if (reportProgress >= 1) {
        // 所有报告完成，进入输出阶段
        updateMessageStatus(aiMessage, 'outputting')
      } else if (reportProgress >= 0.5) {
        // 过半，深度思考
        updateMessageStatus(aiMessage, 'deep_thinking')
      } else {
        // 继续分析文件
        const currentProgress = 30 + Math.round(reportProgress * 30) // 30%~60%
        aiMessage.progress = currentProgress
      }
      break
      
    case 'web_search_raw':
      // 处理网络搜索原始数据
      if (data.results && data.results.length > 0) {
        aiMessage.webSearchRaw = {
          results: data.results || [],
          keywords: data.keywords || [],
          total: data.total || 0
        }
        aiMessage.webSearchTotal = data.total || 0
        
        // 更新状态显示：已检索到数据（联网搜索完成）
        const statusMsg = `<span class="ai-name">蜀道安全管理AI智能助手</span>已为您检索到 <span class="file-count">${aiMessage.totalFiles || 0}</span> 个知识库文件，以及 <span class="file-count">${aiMessage.webSearchTotal}</span> 个相关网络资源`
        updateMessageStatus(aiMessage, 'data_retrieved', statusMsg)
        
        console.log(`[网络搜索] 收到原始数据: ${data.total} 条结果`)
      } else {
        // 如果没有搜索结果，也要更新状态，但只显示知识库文件数
        const statusMsg = `<span class="ai-name">蜀道安全管理AI智能助手</span>已为您检索到 <span class="file-count">${aiMessage.totalFiles || 0}</span> 个知识库文件`
        updateMessageStatus(aiMessage, 'data_retrieved', statusMsg)
        console.log('[网络搜索] 无搜索结果，仅使用知识库')
      }
      break
      
    case 'web_search_summary':
      // 处理网络搜索AI总结 - 使用更快的打字机效果
      if (data.has_results && data.summary) {
        // 检查是否已经有内容，避免重复触发
        if (aiMessage._webSearchSummaryCompleted) {
          console.log('[网络搜索] 总结已完成，跳过重复打字机')
          break
        }
        
        // 保存完整内容
        aiMessage._fullWebSearchSummary = data.summary
        aiMessage.webSearchSummary = '' // 先置空，通过打字机填充
        aiMessage.hasWebSearchResults = true
        
        // 使用更快的打字机效果（速度200 = 每次20个字符）
        const summaryReport = {
          file_index: 'web_search_summary',
          report: aiMessage,
          _typewriterStates: {}
        }
        
        startReportFieldTypewriter(summaryReport, 'webSearchSummary', data.summary, 200)
          .then(() => {
            // 标记为已完成，防止重复触发
            aiMessage._webSearchSummaryCompleted = true
          })
          .catch(err => {
            console.error('网络搜索总结打字机效果失败:', err)
            aiMessage.webSearchSummary = data.summary
            aiMessage._webSearchSummaryCompleted = true
          })
        
        console.log('[网络搜索] 收到AI总结，长度:', data.summary.length)
        
        // 网络搜索总结已接收,准备保存并更新为完成状态
        updateMessageStatus(aiMessage, 'outputting')
        
        // 保存完整数据到后端 - 使用完整的summary而不是打字机过程中的部分内容
        if (aiMessage.ai_message_id) {
          const contentData = {
            reports: aiMessage.reports || [],
            webSearchRaw: aiMessage.webSearchRaw || null,
            webSearchSummary: aiMessage._fullWebSearchSummary || data.summary, // 使用完整的webSearchSummary
            hasWebSearchResults: true,
            // ===== 🔧 修复：将summary也包含在content JSON中 =====
            summary: aiMessage.summary || aiMessage._fullSummary || ''
          }
          
          const collectedContent = JSON.stringify(contentData)
          
          // 同时保存summary字段（作为单独字段）
          const summaryToSave = aiMessage.summary || aiMessage._fullSummary || ''
          
          updateAIMessageContent(aiMessage.ai_message_id, collectedContent, summaryToSave)
            .then((response) => {
              console.log('[网络搜索] AI消息保存成功，更新为完成状态')
              // 保存成功后，更新状态为completed
              updateMessageStatus(aiMessage, 'completed')
              aiMessage.isTyping = false
              isSending.value = false
              streamingReports.value.clear()
              
              // 重置AI回复流程状态
              isAIReplyProcessComplete.value = true
            })
            .catch(err => {
              console.error('[网络搜索] AI消息保存失败:', err)
              // 即使保存失败，也更新为完成状态
              updateMessageStatus(aiMessage, 'completed')
              aiMessage.isTyping = false
              isSending.value = false
            })
        } else {
          // 没有ai_message_id时，直接更新为完成状态
          updateMessageStatus(aiMessage, 'completed')
          aiMessage.isTyping = false
          isSending.value = false
        }
      }
      break
      
    case 'error':
      ElMessage.error(data.message)
      isSending.value = false
        break
      
    case 'completed':
      console.log('[SSE] 收到completed事件')
      isSending.value = false
      streamingReports.value.clear()
      aiMessage.isTyping = false
      
      // 只有在还未完成时才更新状态
      if (aiMessage.progress < 100) {
        updateMessageStatus(aiMessage, 'completed')
      }
      
      ElMessage.success('报告生成完成')
      break
      
    case 'interrupted':
      isSending.value = false
      streamingReports.value.clear()
      aiMessage.isTyping = false
      ElMessage.warning(data.message || '报告生成已中断')
      break
  }
}

const handleSSEError = (error) => {
  console.error('❌ SSE连接异常断开:', error)
  
  // 清理SSE连接
  if (sseConnection) {
    closeSSEConnection(sseConnection)
    sseConnection = null
  }
  
  isSending.value = false
  streamingReports.value.clear()
  
  // 将所有正在打字的AI消息标记为完成
  chatMessages.value.forEach(message => {
    if (message.type === 'ai' && message.isTyping) {
      message.isTyping = false
    }
  })
  
  // 重置AI回复流程状态
  isAIReplyProcessComplete.value = true
  
  // 这是非预期的连接断开（网络错误、后端崩溃等）
  ElMessage.error('连接已断开')
}

const handleSSEComplete = () => {
  isSending.value = false
  
  chatMessages.value.forEach(message => {
    if (message.type === 'ai' && message.isTyping) {
      message.isTyping = false
      
      if (message.ai_message_id) {
        // 构建完整的内容数据，包含报告、网络搜索结果和summary
        const contentData = {
          reports: message.reports || [],
          webSearchRaw: message.webSearchRaw || null,
          // 使用完整的webSearchSummary，而不是打字机过程中的部分内容
          webSearchSummary: message._fullWebSearchSummary || message.webSearchSummary || null,
          hasWebSearchResults: message.hasWebSearchResults || false,
          // ===== 🔧 修复：将summary也包含在content JSON中 =====
          summary: message.summary || message._fullSummary || ''
        }
        
        const collectedContent = message.reports && message.reports.length > 0 
          ? JSON.stringify(contentData)
          : (message.content || message._fullSummary || message.summary || '')
        
        if (collectedContent) {
          // 同时保存summary字段（作为单独字段）
          const summaryToSave = message.summary || message._fullSummary || ''
          
          updateAIMessageContent(message.ai_message_id, collectedContent, summaryToSave)
            .catch(err => console.error('回写AI消息失败:', err))
        }
      }
    }
  })
  
  isAIReplyProcessComplete.value = true
  
  // ===== 🎯 更新历史记录列表并高亮 =====
  console.log('📝 AI回复完成，准备更新历史记录')
  console.log('  - ai_conversation_id:', ai_conversation_id.value)
  
  if (ai_conversation_id.value && ai_conversation_id.value !== 0) {
    console.log('✅ 开始更新历史记录列表')
    
    // 先清除所有高亮
    historyData.value.forEach((item) => {
      item.isActive = false
    })
    
    // 获取第一条用户消息作为标题
    const firstUserMessage = chatMessages.value.find(msg => msg.type === 'user')
    const title = firstUserMessage ? firstUserMessage.content.substring(0, 20) + '...' : '新对话'
    console.log('📝 生成的标题:', title)
    
    // 检查是否已存在
    const existingIndex = historyData.value.findIndex(item => item.id === ai_conversation_id.value)
    console.log('🔍 检查是否已存在，索引:', existingIndex)
    
    if (existingIndex === -1) {
      // 不存在，在最前面插入新项
      const newItem = {
        id: ai_conversation_id.value,
        title: title,
        time: formatTime(new Date().toISOString()),
        businessType: 0,
        isActive: true,
        rawData: {
          id: ai_conversation_id.value,
          content: firstUserMessage?.content || '',
          updated_at: new Date().toISOString()
        }
      }
      console.log('📦 准备插入的新项:', newItem)
      historyData.value.unshift(newItem)
      console.log('✅ 已在列表最前面插入新历史记录并设为高亮')
      console.log('📊 更新后的历史记录数量:', historyData.value.length)
    } else {
      // 已存在，设为高亮并移到最前面
      console.log('🔄 历史记录已存在，将其移到最前面')
      const existingItem = historyData.value.splice(existingIndex, 1)[0]
      existingItem.isActive = true
      existingItem.time = formatTime(new Date().toISOString())
      historyData.value.unshift(existingItem)
      console.log('✅ 已将现有历史记录移到最前面并设为高亮')
    }
    
    // 更新历史记录总数
    historyTotal.value = historyData.value.length
    console.log('📊 最终历史记录总数:', historyTotal.value)
  } else {
    console.warn('⚠️ ai_conversation_id 为 0 或未设置，跳过历史记录更新')
  }
  
  // ===== 🎯 获取AI相关推荐问题 =====
  console.log('🎯 准备获取AI相关推荐问题')
  // 找到最后一条用户消息和最后一条AI消息
  const lastUserMessage = chatMessages.value.filter(msg => msg.type === 'user').pop()
  const lastAIMessage = chatMessages.value.filter(msg => msg.type === 'ai').pop()
  
  if (lastUserMessage && lastAIMessage && lastAIMessage.ai_message_id) {
    console.log('📝 找到最后一条用户消息和AI消息')
    console.log('  - 用户消息:', lastUserMessage.content)
    console.log('  - AI消息ID:', lastAIMessage.ai_message_id)
    
    // 构建AI回复内容用于生成推荐问题
    let aiReplyContent = ''
    
    // 优先使用summary字段
    if (lastAIMessage.summary) {
      aiReplyContent = lastAIMessage.summary
    } 
    // 其次使用content字段
    else if (lastAIMessage.content) {
      aiReplyContent = lastAIMessage.content
    }
    // 如果有reports，使用reports的summary
    else if (lastAIMessage.reports && lastAIMessage.reports.length > 0) {
      const summaries = lastAIMessage.reports
        .filter(r => r.report && r.report.summary)
        .map(r => r.report.summary)
        .slice(0, 3) // 只取前3个
      aiReplyContent = summaries.join('\n\n')
    }
    
    if (aiReplyContent && aiReplyContent.trim()) {
      console.log('📝 AI回复内容长度:', aiReplyContent.length)
      // 获取AI相关推荐问题
      getAIRelatedQuestions(
        lastUserMessage.content, 
        aiReplyContent, 
        lastAIMessage.ai_message_id
      )
    } else {
      console.warn('⚠️ AI回复内容为空，跳过推荐问题获取')
    }
  } else {
    console.warn('⚠️ 未找到有效的用户消息或AI消息，跳过推荐问题获取')
  }
}

const handleSSEInterrupted = (data) => {
  if (sseConnection) {
    closeSSEConnection(sseConnection)
    sseConnection = null
  }
  
  isSending.value = false
  streamingReports.value.clear()
  
  chatMessages.value.forEach(message => {
    if (message.type === 'ai' && message.isTyping) {
      message.isTyping = false
      
      // 中断时设置为完成状态
      updateMessageStatus(message, 'completed')
      
      // 保留已接收的网络搜索数据
      // 即使中断，也要确保已接收的webSearchRaw和webSearchSummary能够显示
      if (message.webSearchRaw || message.webSearchSummary) {
        console.log('✅ 保留已接收的网络搜索数据')
      }
      
      if (message.ai_message_id) {
        // 构建完整的内容数据，包含报告、网络搜索结果和summary
        const contentData = {
          reports: message.reports || [],
          webSearchRaw: message.webSearchRaw || null,
          // 使用完整的webSearchSummary，而不是打字机过程中的部分内容
          webSearchSummary: message._fullWebSearchSummary || message.webSearchSummary || null,
          hasWebSearchResults: message.hasWebSearchResults || false,
          // ===== 🔧 修复：将summary也包含在content JSON中 =====
          summary: message.summary || message._fullSummary || ''
        }
        
        const collectedContent = message.reports && message.reports.length > 0 
          ? JSON.stringify(contentData)
          : (message.content || message._fullSummary || message.summary || '')
        
        if (collectedContent) {
          // 同时保存summary字段（作为单独字段）
          const summaryToSave = message.summary || message._fullSummary || ''
          
          updateAIMessageContent(message.ai_message_id, collectedContent, summaryToSave)
            .catch(err => console.error('回写AI消息失败:', err))
        }
      }
    }
  })
  
  isAIReplyProcessComplete.value = true
  ElMessage.warning(data.message || '报告生成已中断')
}

const handleCancel = () => {
  if (sseConnection) {
    closeSSEConnection(sseConnection)
    sseConnection = null
  }
  isSending.value = false
  ElMessage.warning('已取消生成')
}

// 停止报告生成
const handleStopGeneration = async () => {
  if (!sseConnection || ai_conversation_id.value === undefined || ai_conversation_id.value === null) {
    return
  }
  
  if (sseConnection) {
    closeSSEConnection(sseConnection)
    sseConnection = null
  }
  
  isSending.value = false
  streamingReports.value.clear()
  
  chatMessages.value.forEach(message => {
    if (message.type === 'ai' && message.isTyping) {
      message.isTyping = false
      
      // 停止时设置为完成状态
      updateMessageStatus(message, 'completed')
      
      // 保留已接收的网络搜索数据
      // 即使停止，也要确保已接收的webSearchRaw和webSearchSummary能够显示
      if (message.webSearchRaw || message.webSearchSummary) {
        console.log('✅ 停止时保留已接收的网络搜索数据')
      }
      
      // 回写数据到后端，包含网络搜索结果和summary
      if (message.ai_message_id) {
        const contentData = {
          reports: message.reports || [],
          webSearchRaw: message.webSearchRaw || null,
          // 使用完整的webSearchSummary，而不是打字机过程中的部分内容
          webSearchSummary: message._fullWebSearchSummary || message.webSearchSummary || null,
          hasWebSearchResults: message.hasWebSearchResults || false,
          // ===== 🔧 修复：将summary也包含在content JSON中 =====
          summary: message.summary || message._fullSummary || ''
        }
        
        const collectedContent = message.reports && message.reports.length > 0 
          ? JSON.stringify(contentData)
          : (message.content || message._fullSummary || message.summary || '')
        
        if (collectedContent) {
          // 同时保存summary字段（作为单独字段）
          const summaryToSave = message.summary || message._fullSummary || ''
          
          updateAIMessageContent(message.ai_message_id, collectedContent, summaryToSave)
            .catch(err => console.error('回写AI消息失败:', err))
        }
      }
    }
  })
  
  isAIReplyProcessComplete.value = true
  ElMessage.success('已停止生成')
  
  // ===== 已删除：getUserId() - stopSSEStream 函数需要更新 =====
  stopSSEStream(null, ai_conversation_id.value)
    .catch(error => console.warn('停止请求失败:', error))
}

// ReportGenerator提交处理
const handleReportGeneratorSubmit = async (data) => {
  isSending.value = true
  currentQuestion.value = data.question
  
  // 添加用户消息
  chatMessages.value.push({
    id: Date.now(),
    type: 'user',
    content: data.question,
    timestamp: new Date().toISOString()
  })
  
  // 添加AI消息占位符
  const aiMessageIndex = chatMessages.value.length
  chatMessages.value.push({
    id: Date.now() + 1,
    type: 'ai',
    userQuestion: data.question, // 用户问题
    summary: '',
    totalFiles: 0,
    webSearchTotal: 0,
    progress: 0,
    completedCount: 0,
    reports: [],
    isTyping: true,
    content: '',
    displayContent: '',
    timestamp: new Date().toISOString(),
    // 新增：状态管理
    currentStatus: 'querying_kb', // 当前状态
    statusMessage: '🔍 <span class="ai-name">蜀道安全管理AI智能助手</span>正在从知识库中学习相关信息……', // 状态消息
    showStats: true, // 是否显示统计卡片
    // 新增：后端消息ID（初始为null，从SSE接收后赋值）
    ai_message_id: null,
    rawData: null,
    userFeedback: null
  })
  
  // 等待DOM更新后触发滚动检测，初始化进度卡片状态
  nextTick(() => {
    setTimeout(() => {
      handleProgressCardScroll()
    }, 100)
  })
  
  try {
    const apiPrefix = getApiPrefix()
    const url = `${apiPrefix}/report/complete-flow`

    // 构建 POST 请求体
    const requestBody = {
      user_question: data.question,
      window_size: data.windowSize,
      n_results: 10,
      ai_conversation_id: ai_conversation_id.value,
      is_network_search_enabled: isNetworkSearchEnabled.value,
      enable_online_model: isOnlineModel.value
    }

    console.log('📤 发起 SSE POST 请求:', {
      url,
      body: requestBody
    })

    sseConnection = createSSEConnection(url, {
      onMessage: (eventData) => handleSSEMessage(eventData, aiMessageIndex),
      onError: handleSSEError,
      onComplete: handleSSEComplete,
      onInterrupted: handleSSEInterrupted
    }, {
      body: requestBody
    })

  } catch (error) {
    console.error('启动失败:', error)
    ElMessage.error(`启动失败: ${error.message}`)
    isSending.value = false
  }
}

const handleFunctionCard = (cardType) => {
  clearAllTypeIntervals()
  chatMessages.value = []
  ai_conversation_id.value = 0
  showChat.value = true
  
  handleReportGeneratorSubmit({
    question: `请详细介绍${cardType}的相关内容`,
    windowSize: 3,
    nResults: 10
  })
}

// 点击推荐问题
const handleRecommendedQuestion = (question) => {
  clearAllTypeIntervals()
  chatMessages.value = []
  ai_conversation_id.value = 0
  showChat.value = true
  
  handleReportGeneratorSubmit({
    question: question,
    windowSize: 3,
    nResults: 10
  })
}

// 点击用户推荐问题
const handleUserRecommendQuestion = (question) => {
  clearRecommendQuestions()
  
  handleReportGeneratorSubmit({
    question: question,
    windowSize: 3,
    nResults: 10
  })
}

// 点击历史记录
const handleHistoryItem = async (historyItem) => {
  if (isSending.value) return
  
  if (speakingMessageId.value) {
    stopAllAudio()
    speakingMessageId.value = null
  }
  
  clearAllTypeIntervals()
  expandedSearchSources.value = {}
  expandedOnlineSearchResults.value = {}
  onlineSearchResults.value = {}
  isAIReplyProcessComplete.value = true
  selectedHistoryItem.value = historyItem
  
  // 设置当前问题为历史记录的标题
  currentQuestion.value = historyItem.title
  
  historyData.value.forEach(item => {
    item.isActive = item.id === historyItem.id
  })
  
  showChat.value = true
  
  const loadingMessage = {
    type: 'ai',
    content: '正在加载历史对话...',
    displayContent: '正在加载历史对话...',
    isTyping: true,
    id: Date.now() + 1,
    userFeedback: null
  }
  chatMessages.value = [loadingMessage]
  
  try {
    const success = await getConversationMessages(historyItem.id)
    
    if (success) {
      chatMessages.value = chatMessages.value.filter(msg => msg.id !== loadingMessage.id)
      
      // 根据历史记录的业务类型切换当前模式
      if (historyItem.businessType === 2) {
        currentMode.value = 'ai-writing'
      } else if (historyItem.businessType === 1) {
        currentMode.value = 'safety-training'
      } else if (historyItem.businessType === 3) {
        currentMode.value = 'exam-workshop'
      } else {
        currentMode.value = 'ai-qa'
      }
      
      await nextTick()
      scrollToBottom()
      
      if (aiRelatedQuestions.value.length > 0) {
        setTimeout(() => scrollToBottom(), 200)
      }
    } else {
      chatMessages.value = [{
        type: 'ai',
        content: '抱歉，加载历史对话失败，请稍后重试。',
        displayContent: '抱歉，加载历史对话失败，请稍后重试。',
        isTyping: false,
        id: Date.now() + 1,
        userFeedback: null
      }]
      
      await nextTick()
      scrollToBottom()
    }
  } catch (error) {
    console.error('加载历史对话失败:', error)
    chatMessages.value = [{
      type: 'ai',
      content: '抱歉，加载历史对话时发生错误，请稍后重试。',
      displayContent: '抱歉，加载历史对话时发生错误，请稍后重试。',
      isTyping: false,
      id: Date.now() + 1,
      userFeedback: null
    }]
    
    await nextTick()
    scrollToBottom()
  }
}

// 删除历史记录
const deleteHistoryItem = (historyItem, index) => {
  deleteTargetItem.value = { item: historyItem, index: index }
  deleteType.value = 'history'
  showDeleteModal.value = true
}

// 统一的确认删除函数
const confirmDelete = async () => {
  if (!deleteTargetItem.value) return
  
  if (deleteType.value === 'history') {
    await confirmDeleteHistory()
  } else if (deleteType.value === 'message') {
    await confirmDeleteMessage()
  }
}

// 确认删除历史记录
const confirmDeleteHistory = async () => {
  const { item: historyItem, index } = deleteTargetItem.value
  
  try {
    // 调用删除接口
    const response = await apis.deleteHistoryRecord({ 
      ai_conversation_id: historyItem.id 
    })
    
    if (response.statusCode === 200) {
      historyData.value.splice(index, 1)
      
      // 更新历史记录总数
      historyTotal.value = historyData.value.length
      
      if (historyItem.isActive) {
        await createNewChat()
      }
      
      ElMessage.success('删除成功')
    } else {
      ElMessage.error(response.msg || '删除失败')
    }
  } catch (error) {
    console.error('删除失败:', error)
    ElMessage.error('删除失败，请稍后重试')
  } finally {
    showDeleteModal.value = false
    deleteTargetItem.value = null
    deleteType.value = ''
  }
}

// 确认删除消息
const confirmDeleteMessage = async () => {
  const { messageIndex } = deleteTargetItem.value
  
  try {
    const aiMessage = chatMessages.value[messageIndex]
    
    // 优先使用ai_message_id（后端消息ID），其次使用rawData.id
    const messageId = aiMessage.ai_message_id || (aiMessage.rawData && aiMessage.rawData.id)
    
    if (aiMessage && messageId) {
        const response = await apis.deleteConversation({
        ai_message_id: messageId
        })
        
        if (response.statusCode === 200) {
          chatMessages.value.splice(messageIndex, 1)
          if (messageIndex > 0) {
            chatMessages.value.splice(messageIndex - 1, 1)
          }
          ElMessage.success('删除成功')
        } else {
        ElMessage.error('删除失败，请稍后重试')
      }
    } else {
      chatMessages.value.splice(messageIndex, 1)
      ElMessage.success('删除成功')
    }
  } catch (error) {
    console.error('删除失败:', error)
    ElMessage.error('删除失败，请稍后重试')
  } finally {
    showDeleteModal.value = false
    deleteTargetItem.value = null
    deleteType.value = ''
  }
}

// 取消删除
const cancelDelete = () => {
  showDeleteModal.value = false
  deleteTargetItem.value = null
  deleteType.value = ''
}

// 新建聊天
const createNewChat = async () => {
  if (isSending.value) return
  
  if (speakingMessageId.value) {
    stopAllAudio()
    speakingMessageId.value = null
  }
  
  clearAllTypeIntervals()
  
  ai_conversation_id.value = 0
  chatMessages.value = []
  messageText.value = ''
  currentQuestion.value = '' // 清空当前问题
  selectedFile.value = null
  showChat.value = false
  aiRelatedQuestions.value = []
  relatedQuestionsMessageId.value = null
  onlineSearchResults.value = {}
  expandedOnlineSearchResults.value = {}
  expandedSearchSources.value = {}
  
  historyData.value.forEach(item => item.isActive = false)
  
  await getHistoryRecordList()
}

// 语音输入
const handleVoiceClick = () => {
  isListening.value ? stopVoiceInput() : startVoiceInput()
}

const startVoiceInput = () => {
  const success = startListening()
  if (!success) {
    ElMessage.error('语音识别启动失败，请检查麦克风权限')
  }
}

const stopVoiceInput = () => {
  stopListening()
  if (transcript.value.trim()) {
    messageText.value = transcript.value
  }
}

// 当前播放的音频对象
const currentAudio = ref(null)
// 音频队列管理
const audioQueue = ref([])
const isPlayingQueue = ref(false)

// 获取TTS服务地址（自动判断是否使用代理）
const getTTSUrl = () => {
  // 在开发环境中使用代理，生产环境中使用直接地址
  const isDevelopment = import.meta.env.DEV
  if (isDevelopment) {
    return '/api/tts/voice'  // 使用Vite代理
  } else {
    return window.location.origin + '/tts/voice'  // 生产环境直接地址
  }
}

// 测试TTS服务连接
const testTTSConnection = async () => {
  const ttsUrl = getTTSUrl()
  
  try {
    const controller = new AbortController()
    const timeoutId = setTimeout(() => controller.abort(), 8000)
    
    // 准备请求头，添加认证 Token
    const headers = { 'Content-Type': 'application/json' }
    const token = getToken()
    const tokenType = getTokenType()
    if (token && tokenType) {
      // 确保 Bearer 首字母大写
      const bearerType = tokenType.charAt(0).toUpperCase() + tokenType.slice(1).toLowerCase()
      headers['Authorization'] = `${bearerType} ${token}`
    }
    
    const response = await fetch(ttsUrl, {
      method: 'POST',
      headers,
      body: JSON.stringify({ text: '测试' }),
      signal: controller.signal
    })
    
    clearTimeout(timeoutId)
    
    if (response.ok) {
      await response.blob()
      return { success: true, message: 'TTS服务连接正常' }
    } else {
      return { success: false, message: `TTS服务响应错误: ${response.status}` }
    }
  } catch (error) {
    let message = 'TTS服务连接失败'
    if (error.name === 'AbortError') {
      message = 'TTS服务连接超时'
    } else if (error.message.includes('Failed to fetch')) {
      message = '无法连接到TTS服务'
    }
    return { success: false, message }
  }
}

// 调用TTS接口进行语音合成（带重试机制）
const callTTSAPI = async (text, retryCount = 0) => {
  const ttsUrl = getTTSUrl()
  const maxRetries = 2
  
  try {
    const controller = new AbortController()
    const timeoutId = setTimeout(() => controller.abort(), 15000)
    
    // 准备请求头，添加认证 Token
    const headers = { 'Content-Type': 'application/json' }
    const token = getToken()
    const tokenType = getTokenType()
    if (token && tokenType) {
      // 确保 Bearer 首字母大写
      const bearerType = tokenType.charAt(0).toUpperCase() + tokenType.slice(1).toLowerCase()
      headers['Authorization'] = `${bearerType} ${token}`
    }
    
    const response = await fetch(ttsUrl, {
      method: 'POST',
      headers,
      body: JSON.stringify({ text }),
      signal: controller.signal
    })
    
    clearTimeout(timeoutId)
    
    if (!response.ok) {
      throw new Error(`TTS接口调用失败: ${response.status}`)
    }
    
    const audioBlob = await response.blob()
    if (audioBlob.size === 0) {
      throw new Error('TTS接口返回的音频数据为空')
    }
    
    return URL.createObjectURL(audioBlob)
  } catch (error) {
    // 重试逻辑
    if (retryCount < maxRetries && (
      error.name === 'AbortError' || 
      error.message.includes('Failed to fetch') ||
      error.message.includes('NetworkError')
    )) {
      await new Promise(resolve => setTimeout(resolve, (retryCount + 1) * 1000))
      return callTTSAPI(text, retryCount + 1)
    }
    
    // 错误信息
    let errorMessage = '语音合成失败'
    if (error.name === 'AbortError') {
      errorMessage = '语音合成请求超时'
    } else if (error.message.includes('Failed to fetch')) {
      errorMessage = '无法连接到语音合成服务'
    } else if (error.message.includes('TTS接口调用失败')) {
      errorMessage = error.message
    }
    
    const detailedError = new Error(errorMessage)
    detailedError.originalError = error
    throw detailedError
  }
}

// 清理文本内容，移除HTML标签和非文本字符
const cleanTextForTTS = (text) => {
  if (!text) return ''
  
  // 移除HTML标签
  let cleanText = text.replace(/<[^>]*>/g, '')
  
  // 移除多余的空白字符
  cleanText = cleanText.replace(/\s+/g, ' ').trim()
  
  // 移除特殊字符，保留中文、英文、数字和基本标点
  cleanText = cleanText.replace(/[^\u4e00-\u9fa5a-zA-Z0-9\s，。！？、；：""''（）【】《》]/g, '')
  
  return cleanText
}

// 将长文本分块处理（第一块较小，后续块较大）
const splitTextIntoChunks = (text) => {
  if (text.length <= 60) {
    return [text]
  }
  
  const chunks = []
  let currentChunk = ''
  let isFirstChunk = true
  
  // 按句子分割
  const sentences = text.split(/[。！？]/)
  
  for (const sentence of sentences) {
    if (sentence.trim().length === 0) continue
    
    const sentenceWithPunctuation = sentence + (sentence.match(/[。！？]$/) ? '' : '。')
    
    // 第一块限制为60字，后续块限制为200字
    const maxLength = isFirstChunk ? 60 : 200
    
    if (currentChunk.length + sentenceWithPunctuation.length <= maxLength) {
      currentChunk += sentenceWithPunctuation
    } else {
      if (currentChunk.length > 0) {
        chunks.push(currentChunk.trim())
        currentChunk = sentenceWithPunctuation
        isFirstChunk = false // 第一块已完成
      } else {
        // 如果单个句子就超过最大长度，强制分割
        const maxLen = isFirstChunk ? 60 : 200
        chunks.push(sentenceWithPunctuation.substring(0, maxLen))
        currentChunk = sentenceWithPunctuation.substring(maxLen)
        isFirstChunk = false
      }
    }
  }
  
  if (currentChunk.trim().length > 0) {
    chunks.push(currentChunk.trim())
  }
  
  return chunks
}

// 播放音频
const playAudio = (audioUrl) => {
  return new Promise((resolve, reject) => {
    const audio = new Audio(audioUrl)
    currentAudio.value = audio
    
    audio.onended = () => {
      currentAudio.value = null
      resolve()
    }
    
    audio.onerror = (error) => {
      currentAudio.value = null
      reject(error)
    }
    
    audio.play().catch(error => {
      currentAudio.value = null
      reject(error)
    })
  })
}

// 停止所有音频播放
const stopAllAudio = () => {
  try {
    if (currentAudio.value) {
      currentAudio.value.pause()
      currentAudio.value.currentTime = 0
      currentAudio.value = null
    }
    
    audioQueue.value = []
    isPlayingQueue.value = false
    window.speechSynthesis && window.speechSynthesis.cancel()
  } catch (e) {
    console.warn('停止音频播放失败:', e)
  }
}

// 优化后的并行预加载音频并播放队列
const playAudioQueue = async (chunks, messageId) => {
  if (speakingMessageId.value !== messageId) return
  
  try {
    const firstAudioUrl = await callTTSAPI(chunks[0])
    if (speakingMessageId.value !== messageId) {
      URL.revokeObjectURL(firstAudioUrl)
      return
    }
    
    const remainingChunks = chunks.slice(1)
    const remainingPromises = remainingChunks.map(async (chunk, index) => {
      try {
        const audioUrl = await callTTSAPI(chunk)
        return { index: index + 1, audioUrl }
      } catch (error) {
        return { index: index + 1, audioUrl: null }
      }
    })
    
    await playAudio(firstAudioUrl)
    URL.revokeObjectURL(firstAudioUrl)
    
    if (speakingMessageId.value !== messageId) {
      const remainingResults = await Promise.allSettled(remainingPromises)
      remainingResults.forEach(result => {
        if (result.status === 'fulfilled' && result.value.audioUrl) {
          URL.revokeObjectURL(result.value.audioUrl)
        }
      })
      return
    }
    
    const remainingResults = await Promise.allSettled(remainingPromises)
    if (speakingMessageId.value !== messageId) {
      remainingResults.forEach(result => {
        if (result.status === 'fulfilled' && result.value.audioUrl) {
          URL.revokeObjectURL(result.value.audioUrl)
        }
      })
      return
    }
    
    isPlayingQueue.value = true
    for (const result of remainingResults) {
      if (speakingMessageId.value !== messageId) break
      
      if (result.status === 'fulfilled' && result.value.audioUrl) {
        try {
          await playAudio(result.value.audioUrl)
          URL.revokeObjectURL(result.value.audioUrl)
        } catch (error) {
          console.error('音频播放失败:', error)
        }
      }
    }
    
    isPlayingQueue.value = false
  } catch (error) {
    console.error('音频队列播放失败:', error)
    isPlayingQueue.value = false
  }
}

// 语音朗读相关方法
const handleVoiceRead = async (message) => {
  if (speakingMessageId.value === message.id) {
    // 如果正在朗读这条消息，则停止
    stopAllAudio()
    speakingMessageId.value = null
  } else {
    // 如果朗读其他消息，先停止当前朗读
    if (speakingMessageId.value) {
      stopAllAudio()
      speakingMessageId.value = null
    }
    
    const textToRead = message.displayContent || message.content
    if (textToRead && textToRead.trim()) {
      try {
        const cleanText = cleanTextForTTS(textToRead)
        
        if (cleanText.length === 0) {
          ElMessage.warning('文本内容为空，无法进行语音合成')
          return
        }
        
        speakingMessageId.value = message.id
        
        if (cleanText.length <= 60) {
          const audioUrl = await callTTSAPI(cleanText)
          await playAudio(audioUrl)
          URL.revokeObjectURL(audioUrl)
        } else {
          const chunks = splitTextIntoChunks(cleanText)
          await playAudioQueue(chunks, message.id)
        }
      } catch (error) {
        console.error('语音合成失败:', error)
        ElMessage.error('语音合成失败，请稍后重试')
      } finally {
        speakingMessageId.value = null
        isPlayingQueue.value = false
      }
    }
  }
}

// 检查消息是否正在朗读
const isSpeaking = (messageId) => {
  return speakingMessageId.value === messageId
}

// 删除弹窗相关方法
const handleDeleteClick = (messageIndex) => {
  console.log('点击删除按钮，消息索引:', messageIndex)
  
  // 检查是否只剩一句AI回复和一句用户发言
  if (chatMessages.value.length === 2) {
    ElMessage.warning('第一句话无法删除')
    return
  }
  
  // 设置删除类型和要删除的消息索引
  deleteType.value = 'message'
  deleteTargetItem.value = { messageIndex: messageIndex }
  showDeleteModal.value = true
}


// 处理输入框输入，限制2000字
const handleInput = () => {
  if (messageText.value.length > 2000) {
    messageText.value = messageText.value.substring(0, 2000)
    ElMessage.warning('消息长度不能超过2000字')
  }
  
  // 防抖获取推荐问题
  if (recommendQuestionsTimer.value) {
    clearTimeout(recommendQuestionsTimer.value)
  }
  
  // 如果输入内容为空，清空推荐问题
  if (!messageText.value.trim()) {
    userRecommendQuestions.value = []
    return
  }
  
  // 延迟500ms后获取推荐问题，避免频繁调用
  recommendQuestionsTimer.value = setTimeout(() => {
    getUserRecommendQuestions(messageText.value)
  }, 100)

}

// 触发文件上传
const triggerFileUpload = () => {

  if (selectedFile.value) {
    ElMessage.warning('只能上传一个文件，请先删除当前文件')
    return
  }
  fileInput.value?.click()
}





// 读取Word文件内容
const readWordFile = async (file) => {
  try {
    if (file.size === 0) throw new Error('Word文件为空')
    if (!mammoth) throw new Error('Word文档解析库未正确加载')
    
    const fileExtension = file.name.toLowerCase().split('.').pop()
    const arrayBuffer = await file.arrayBuffer()
    
    // 检查文件格式
    if (fileExtension === 'docx') {
      const uint8Array = new Uint8Array(arrayBuffer.slice(0, 2))
      if (uint8Array[0] !== 0x50 || uint8Array[1] !== 0x4B) {
        throw new Error('文件不是有效的.docx格式，可能已损坏')
      }
    } else if (fileExtension === 'doc') {
      throw new Error('检测到.doc格式文件。请将文件另存为.docx格式后重新上传。')
    }
    
    const result = await mammoth.extractRawText({ arrayBuffer })
    return result.value
  } catch (error) {
    console.error('Word文件读取失败:', error)
    
    if (error.message.includes('Can\'t find end of central directory')) {
      throw new Error('文件格式错误：这不是一个有效的Word文档，或者文件已损坏。')
    } else if (error.message.includes('Invalid file format')) {
      throw new Error('Word文件格式无效或已损坏')
    } else {
      throw error
    }
  }
}

// 处理文件选择
const handleFileSelect = async (event) => {
  const file = event.target.files[0]
  if (!file) return
  
  try {
    const fileExtension = validateFile(file)
    if (!mammoth) {
      throw new Error('Word文档解析库未正确加载，请刷新页面重试')
    }
    
    isUploadingFile.value = true
    const extractedContent = await readWordFile(file)
    
    selectedFile.value = {
      file,
      name: file.name,
      size: file.size,
      type: fileExtension,
      icon: getFileIcon(fileExtension),
      content: extractedContent
    }
    
    ElMessage.success(`文件读取成功，共提取 ${extractedContent.length} 个字符`)
  } catch (error) {
    console.error('文件读取失败:', error)
    ElMessage.error(error.message || '文件读取失败，请重试')
  } finally {
    isUploadingFile.value = false
    event.target.value = ''
  }
}

// 删除选中的文件
const removeSelectedFile = () => {
  if (selectedFile.value) {
    selectedFile.value = null
  }
}



// 获取功能卡片数据
const getFunctionCards = async () => {
  try {
    console.log('开始获取功能卡片...')
    let functionType = 0; // AI问答
    if (currentMode.value === 'ai-writing') functionType = 2;
    if (currentMode.value === 'safety-training') functionType = 1;
    if (currentMode.value === 'exam-workshop') functionType = 3;

    const response = await apis.getFunctionCard({ function_type: functionType })
    console.log('功能卡片响应:', response)
    
    if (response.statusCode === 200) {
      functionCards.value = response.data
      console.log('功能卡片数据已设置:', functionCards.value)
    } else {
      console.error('获取功能卡片失败:', response.statusCode)
    }
  } catch (error) {
    console.error('获取功能卡片失败:', error)
  }
}

// 获取热点问题数据
const getHotQuestions = async () => {
  try {
    console.log('开始获取热点问题...')
    let questionType = 0; // AI问答
    if (currentMode.value === 'ai-writing') questionType = 2;
    if (currentMode.value === 'safety-training') questionType = 1;
    if (currentMode.value === 'exam-workshop') questionType = 3;

    const response = await apis.getHotQuestion({ question_type: questionType })
    console.log('热点问题响应:', response)
    
    if (response.statusCode === 200) {
      hotQuestions.value = response.data
      console.log('热点问题数据已设置:', hotQuestions.value)
    } else {
      console.error('获取热点问题失败:', response.statusCode)
    }
  } catch (error) {
    console.error('获取热点问题失败:', error)
  }
}

// 监听模式变化，重新获取卡片和问题
watch(currentMode, () => {
  getFunctionCards()
  getHotQuestions()
})

// 清除推荐问题
const clearRecommendQuestions = () => {
  userRecommendQuestions.value = []
  if (recommendQuestionsTimer.value) {
    clearTimeout(recommendQuestionsTimer.value)
    recommendQuestionsTimer.value = null
  }
}

// 处理容器点击事件
const handleContainerClick = (event) => {
  // 如果点击的不是推荐问题区域，则清除推荐问题
  if (!event.target.closest('.user-recommend-questions')) {
    clearRecommendQuestions()
  }
  
  // 如果点击的不是网络搜索胶囊或侧边栏，则关闭侧边栏
  if (webSearchSidebarVisible.value && 
      !event.target.closest('.web-search-capsule-outer') &&
      !event.target.closest('.web-search-sidebar')) {
    webSearchSidebarVisible.value = false
  }
}

// 切换联网搜索状态
const toggleNetworkSearch = () => {
  isNetworkSearchEnabled.value = !isNetworkSearchEnabled.value
  ElMessage[isNetworkSearchEnabled.value ? 'success' : 'info'](
    isNetworkSearchEnabled.value ? '联网搜索已启用' : '联网搜索已关闭'
  )
}

// 切换搜索来源展开状态
const toggleSearchSources = (messageId) => {
  expandedSearchSources.value[messageId] = !expandedSearchSources.value[messageId]
}

// 切换联网搜索结果展开状态
const toggleOnlineSearchResults = (messageId) => {
  expandedOnlineSearchResults.value[messageId] = !expandedOnlineSearchResults.value[messageId]
}

// 打开链接
const openUrl = (url) => {
  if (!url || typeof url !== 'string' || !url.trim()) {
    ElMessage.warning('链接地址无效')
    return
  }
  
  try {
    let targetUrl = url.trim()
    if (!targetUrl.startsWith('http://') && !targetUrl.startsWith('https://')) {
      targetUrl = 'https://' + targetUrl
    }
    window.open(targetUrl, '_blank', 'noopener,noreferrer')
  } catch (error) {
    console.error('打开链接失败:', error)
    ElMessage.error('无法打开链接')
  }
}

// 打开搜索来源链接
const openSearchSource = openUrl

// 打开联网搜索结果链接
const openSearchResult = openUrl

// 处理提问联想点击
const handleRelatedQuestion = (question) => {
  aiRelatedQuestions.value = []
  relatedQuestionsMessageId.value = null
  messageText.value = question
  handleSendMessage()
}

// 获取用户推荐问题
const getUserRecommendQuestions = async (userMessage) => {
  if (!userMessage || !userMessage.trim() || isSending.value || hasTypingMessage.value) {
    userRecommendQuestions.value = []
    return
  }
  
  try {
    isGettingRecommendQuestions.value = true
    
    const response = await apis.getUserRecommendQuestion({ 
      user_message: userMessage.trim()
      // ===== 已删除：user_id - 后端从token解析 =====
    })
    
    if (isSending.value || hasTypingMessage.value) {
      userRecommendQuestions.value = []
      return
    }
    
    if (response.statusCode === 200 && response.data && response.data.questions) {
      userRecommendQuestions.value = response.data.questions
    } else {
      userRecommendQuestions.value = []
    }
  } catch (error) {
    console.error('获取推荐问题失败:', error)
    userRecommendQuestions.value = []
  } finally {
    isGettingRecommendQuestions.value = false
  }
}

// 联网搜索功能
const performOnlineSearch = async (userInput, messageId) => {
  if (!userInput || userInput.trim() === '') {
    console.log('用户输入为空，跳过搜索')
    return
  }
  
  if (!messageId) {
    console.error('消息ID为空，无法进行联网搜索')
    return
  }
  
  try {
    console.log('开始联网搜索，用户输入:', userInput, '消息ID:', messageId)
    isGettingOnlineSearch.value = true
    onlineSearchLoadingMessages.value.add(messageId)
    
    const response = await apis.onlineSearch({ 
      keywords: userInput.trim()
    })
    
    console.log('联网搜索结果:', response)
    
    if (response.statusCode === 200 && response.results) {
      try {
        // 解析搜索结果
        const results = response.results
      
        
        // 处理数据格式，确保有必要的字段
        const processedResults = results.map((result, index) => ({
          title: result.title || `搜索结果 ${index + 1}`,
          content: result.content || '暂无内容',
          url: result.url || null
        }))
        
        // 先保存搜索结果并立即显示
        onlineSearchResults.value[messageId] = processedResults
        
        // 设置联网搜索结果默认收起
        expandedOnlineSearchResults.value[messageId] = false
        
        console.log('联网搜索结果已保存，消息ID:', messageId, '结果数量:', processedResults.length)
        console.log('处理后的搜索结果:', processedResults)
        console.log('联网搜索结果已设置为默认收起')
        
        // 保存联网搜索结果到数据库
        try {
          const saveData = {
            id: messageId,
            ai_conversation_id: ai_conversation_id.value,
            search_source: JSON.stringify(processedResults)
          }
          
          const saveResponse = await apis.saveOnlineSearchResult(saveData)
          console.log('联网搜索结果保存到数据库成功:', saveResponse)
        } catch (saveError) {
          console.error('保存联网搜索结果到数据库失败:', saveError)
        }
        
        // 返回搜索结果，但不立即显示
        return processedResults
      } catch (parseError) {
        console.error('解析联网搜索结果失败:', parseError)
        onlineSearchResults.value[messageId] = []
      }
    } else {
      console.error('联网搜索失败:', response.statusCode)
      onlineSearchResults.value[messageId] = []
    }
  } catch (error) {
    console.error('联网搜索请求失败:', error)
    onlineSearchResults.value[messageId] = []
  } finally {
    isGettingOnlineSearch.value = false
    onlineSearchLoadingMessages.value.delete(messageId)
  }
}

// 获取AI回复相关推荐问题
const getAIRelatedQuestions = async (userMessage, aiReply, messageId) => {
  if (!userMessage || !aiReply || !messageId) {
    console.log('参数不完整，跳过相关推荐问题获取')
    return
  }
  
  try {
    console.log('开始获取AI回复相关推荐问题')
    console.log('用户问题:', userMessage)
    console.log('AI回复:', aiReply.substring(0, 100) + '...')
    console.log('消息ID:', messageId)
    
    isGettingRelatedQuestions.value = true
    
    // 设计提示词让大模型返回3条相关推荐问题
    const prompt = `基于以下对话内容，直接生成3条相关的推荐问题。

【对话内容】
用户问题：${userMessage}
AI回复：${aiReply}

【生成要求】
- 直接输出3个问题，每个问题一行
- 问题要与原问题相关但有所延伸
- 问题要具体、实用，符合中文表达习惯
- 不要包含任何编号、标题、说明文字
- 不要重复上述指令内容`
    
    const response = await apis.guessYouWant({
      message: prompt,
      // ===== 已删除：user_id - 后端从token解析 =====
      ai_message_id: messageId
    })
    
    console.log('AI相关推荐问题响应:', response)
    
    if (response.statusCode === 200 && response.data && response.data.reply) {
      // 解析大模型返回的推荐问题
      const replyText = response.data.reply.trim()
      const questions = replyText.split('\n')
        .map(q => q.trim())
        .filter(q => q.length > 0)
        // 过滤掉包含提示词、标题、说明文字的行
        .filter(q => {
          // 过滤包含特定关键词的行
          const excludeKeywords = ['请生成', '推荐问题', '相关问题', '生成要求', '对话内容', '【', '】', '指令']
          return !excludeKeywords.some(keyword => q.includes(keyword))
        })
        // 过滤掉以"-"或"•"开头的行（通常是说明文字）
        .filter(q => !q.startsWith('-') && !q.startsWith('•') && !q.startsWith('*'))
        // 移除可能的编号前缀（1. 2. 3. 或 1、2、3、）
        .map(q => q.replace(/^[0-9]+[\.\、]\s*/, ''))
        .filter(q => q.length > 0)
        // 过滤掉包含冒号的行（通常是标题）
        .filter(q => !q.includes('：') && !q.includes(':'))
        .filter((q, index, arr) => arr.indexOf(q) === index) // 去重
        .slice(0, 3) // 只取前3个
      
      if (questions.length > 0) {
        aiRelatedQuestions.value = questions
        relatedQuestionsMessageId.value = messageId
        console.log('✅ AI相关推荐问题数据已设置:')
        console.log('  - 推荐问题数量:', questions.length)
        console.log('  - 推荐问题内容:', questions)
        console.log('  - 关联消息ID:', messageId)
        
        // 只需要等待DOM更新即可，不需要滚动到底部
        await nextTick()
        console.log('✅ DOM已更新，推荐问题已显示')
      } else {
        console.log('解析推荐问题失败，使用默认问题')
        aiRelatedQuestions.value = []
        relatedQuestionsMessageId.value = null
      }
    } else {
      console.error('获取AI相关推荐问题失败:', response.statusCode)
      aiRelatedQuestions.value = []
      relatedQuestionsMessageId.value = null
    }
  } catch (error) {
    console.error('获取AI相关推荐问题失败:', error)
    aiRelatedQuestions.value = []
    relatedQuestionsMessageId.value = null
  } finally {
    isGettingRelatedQuestions.value = false
  }
}

// 文件处理工具函数
const validateFile = (file) => {
  // 检查文件大小
  if (file.size > fileConfig.maxSize) {
    throw new Error('文件大小不能超过20MB')
  }
  
  // 检查文件类型
  const fileExtension = '.' + file.name.split('.').pop().toLowerCase()
  
  // 支持的扩展名列表（对应于 input 的 accept 属性）
  const supportedExtensions = ['.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx', '.pdf', '.png', '.jpg', '.jpeg', '.gif', '.txt']
  
  if (!supportedExtensions.includes(fileExtension)) {
    throw new Error(`不支持的文件格式: ${fileExtension}。支持的格式: 图片、文档、表格、PPT、PDF等。`)
  }
  
  return fileExtension
}

// 获取文件图标
const getFileIcon = (fileType) => {
  const type = fileType.toLowerCase()
  if (['.doc', '.docx'].includes(type)) {
    return wordDocIcon
  } else if (['.xls', '.xlsx'].includes(type)) {
    return new URL('../assets/chat/excel.png', import.meta.url).href
  } else if (['.ppt', '.pptx'].includes(type)) {
    return new URL('../assets/chat/ppt.png', import.meta.url).href
  } else if (type === '.pdf') {
    return new URL('../assets/chat/pdf.png', import.meta.url).href
  } else if (['.png', '.jpg', '.jpeg', '.gif'].includes(type)) {
    return new URL('../assets/chat/image.png', import.meta.url).href
  } else if (type === '.txt') {
    return new URL('../assets/chat/txt.png', import.meta.url).href
  }
  return '📎'
}

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    const chatContent = document.querySelector('.chat-content')
    if (chatContent) {
      chatContent.scrollTop = chatContent.scrollHeight
    }
  })
}

// 检查是否在底部
const isAtBottom = () => {
  const chatContent = document.querySelector('.chat-content')
  if (!chatContent) return true
  
  const threshold = 3.125 // 50px的容差 (50px)
  return chatContent.scrollHeight - chatContent.scrollTop - chatContent.clientHeight < threshold
}

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 编辑用户消息
const editUserMessage = (message) => {
  console.log('编辑用户消息:', message.content)
  messageText.value = message.content
  
  // 恢复文件信息
  if (message.file) {
    selectedFile.value = message.file
    console.log('恢复文件信息:', message.file.name)
  }
  
  // 聚焦到输入框
  const inputElement = document.querySelector('.message-input')
  if (inputElement) {
      inputElement.focus()
      inputElement.setSelectionRange(inputElement.value.length, inputElement.value.length)
  }
}

// 重新生成AI回复
const regenerateResponse = async (messageIndex) => {
  console.log('重新生成回复，消息索引:', messageIndex)
  
  // 找到对应的用户消息
  if (messageIndex > 0) {
    const userMessage = chatMessages.value[messageIndex - 1]
    if (userMessage && userMessage.type === 'user') {
      console.log('重新发送用户消息:', userMessage.content)
      
      // 恢复消息文本和文件信息
      messageText.value = userMessage.content
      
      // 恢复文件信息
      if (userMessage.file) {
        selectedFile.value = userMessage.file
      }
      
      await handleSendMessage()
    }
  }
}

// 复制功能
const copyToClipboard = async (text) => {
  try {
    await navigator.clipboard.writeText(text)
    ElMessage.success('复制成功')
  } catch (err) {
    // 降级方案：使用传统复制方法
    const textArea = document.createElement('textarea')
    textArea.value = text
    document.body.appendChild(textArea)
    textArea.select()
    document.execCommand('copy')
    document.body.removeChild(textArea)
    ElMessage.success('复制成功')
  }
}

// 复制用户消息
const copyUserMessage = (message) => {
  copyToClipboard(message.content)
}

// 复制AI消息
const copyAIMessage = (message) => {
  // 优先使用summary（非专业问题的回复），然后是displayContent，最后是content
  let textToCopy = message.summary || message.displayContent || message.content
  
  // 如果包含HTML标签，转换为纯文本
  if (textToCopy && textToCopy.includes('<')) {
    // 创建临时DOM元素来提取纯文本
    const tempDiv = document.createElement('div')
    tempDiv.innerHTML = textToCopy
    textToCopy = tempDiv.textContent || tempDiv.innerText || textToCopy
  }
  
  // 如果还是没有内容，尝试从reports中提取
  if (!textToCopy && message.reports && message.reports.length > 0) {
    textToCopy = message.reports
      .filter(r => r.type !== 'category_title')
      .map(r => r.report || '')
      .join('\n\n')
  }
  
  // 如果有网络搜索总结，也添加进去
  if (message.webSearchSummary) {
    textToCopy = textToCopy 
      ? `${textToCopy}\n\n【网络搜索总结】\n${message.webSearchSummary}`
      : message.webSearchSummary
  }
  
  if (textToCopy && textToCopy.trim()) {
  copyToClipboard(textToCopy)
  } else {
    ElMessage.warning('暂无可复制的内容')
  }
}

// 点赞和点踩功能
const handleThumbsUp = async (message) => {
  console.log('点赞消息:', message.id)
  
  // 如果已经点赞，则取消点赞
  if (message.userFeedback === 'like') {
    message.userFeedback = null
  } else {
    // 设置点赞，取消点踩
    message.userFeedback = 'like'
  }
  
  // 强制触发Vue响应式更新
  chatMessages.value = [...chatMessages.value]
  
  // 同步反馈到后端
  await syncFeedbackToBackend(message)
}

const handleThumbsDown = async (message) => {
  console.log('点踩消息:', message.id)
  
  // 如果已经点踩，则取消点踩
  if (message.userFeedback === 'dislike') {
    message.userFeedback = null
  } else {
    // 设置点踩，取消点赞
    message.userFeedback = 'dislike'
  }
  
  // 强制触发Vue响应式更新
  chatMessages.value = [...chatMessages.value]
  
  // 同步反馈到后端
  await syncFeedbackToBackend(message)
}

// 同步用户反馈到后端
const syncFeedbackToBackend = async (message) => {
  try {
    console.log('🔍 syncFeedbackToBackend 收到的message对象:', {
      id: message.id,
      ai_message_id: message.ai_message_id,
      rawData: message.rawData,
      rawData_id: message.rawData?.id
    })
    
    // 优先使用ai_message_id，其次使用rawData.id
    const messageId = message.ai_message_id || (message.rawData && message.rawData.id)
    
    if (!messageId) {
      console.warn('❌ 消息缺少ID，无法同步反馈')
      console.warn('  - message.ai_message_id:', message.ai_message_id)
      console.warn('  - message.rawData:', message.rawData)
      return
    }
    
    const feedback = convertFeedbackToBackend(message.userFeedback)
    console.log('✅ 同步反馈到后端:', {
      messageId: messageId,
      feedback: feedback
    })
    
    // 调用后端点赞点踩接口
    const response = await apis.likeAndDislike({
      id: messageId,
      user_feedback: feedback
    })
    
    if (response.statusCode === 200) {
      console.log('反馈同步成功')
      // 根据反馈类型显示不同提示
      if (feedback === 2) {
        ElMessage.success('点赞成功')
      } else if (feedback === 3) {
        ElMessage.success('点踩成功')
      } else {
        ElMessage.success('已取消反馈')
      }
    } else {
      console.error('反馈同步失败:', response.msg)
      ElMessage.error('反馈提交失败，请稍后重试')
    }
    
  } catch (error) {
    console.error('同步反馈失败:', error)
    ElMessage.error('反馈同步失败，请稍后重试')
  }
}

// 自动发送消息功能
const autoSendMessage = async (message) => {
  if (!message || !message.trim()) return
  
  console.log('自动发送消息:', message)
  
  // 显示聊天界面
  showChat.value = true
  
  // 如果是新对话，清除所有历史记录的选中状态
  if (chatMessages.value.length === 0) {
    historyData.value.forEach((item) => {
      item.isActive = false
    })
    console.log('自动发送新对话，清除所有历史记录的选中状态')
    
    // 清除所有展开状态
    expandedSearchSources.value = {}
    expandedOnlineSearchResults.value = {}
    
    // 清除之前的联网搜索结果，避免重复显示
    onlineSearchResults.value = {}
  }
  
  // 清除AI相关推荐问题
  aiRelatedQuestions.value = []
  relatedQuestionsMessageId.value = null
  
  // 使用ReportGenerator的提交逻辑（与直接发送消息一致）
  await handleReportGeneratorSubmit({
    question: message,
    windowSize: 3,
    nResults: 10
  })
}

// 初始化中括号缩放补偿
const initBracketZoomCompensation = () => {
  try {
    // 检测系统缩放比例
    const devicePixelRatio = window.devicePixelRatio || 1
    // console.log('🔍 检测到系统缩放比例:', devicePixelRatio)
    
    // 设置CSS变量，用于CSS缩放补偿
    document.documentElement.style.setProperty('--system-zoom', devicePixelRatio)
    
    // 如果系统缩放不是100%，应用补偿
    if (devicePixelRatio !== 1) {
      const compensationScale = 1 / devicePixelRatio
      // console.log('📐 应用中括号缩放补偿:', compensationScale)
      
      // 动态更新CSS样式
      const style = document.createElement('style')
      style.id = 'bracket-zoom-compensation'
      
      // 移除旧的样式（如果存在）
      const oldStyle = document.getElementById('bracket-zoom-compensation')
      if (oldStyle) {
        oldStyle.remove()
      }
      
      // 添加新的样式
      document.head.appendChild(style)
      
      // console.log('✅ 中括号缩放补偿已应用')
    } else {
      // console.log('🔄 系统缩放100%，无需补偿')
    }
    
    // 监听窗口大小变化，重新检测缩放
    const handleResize = () => {
      setTimeout(() => {
        initBracketZoomCompensation()
      }, 100)
    }
    
    window.addEventListener('resize', handleResize)
    
    // 返回清理函数
    return () => {
      window.removeEventListener('resize', handleResize)
      const style = document.getElementById('bracket-zoom-compensation')
      if (style) {
        style.remove()
      }
    }
    
  } catch (error) {
    console.error('❌ 中括号缩放补偿初始化失败:', error)
  }
}

// 处理文件引用和链接点击
const handleStandardReferenceClick = async (event) => {
  const target = event.target
  
  // 检查是否是链接胶囊或其子元素
  const linkCapsule = target.closest('.link-capsule')
  if (linkCapsule) {
    event.preventDefault()
    event.stopPropagation()
    
    const href = linkCapsule.getAttribute('data-link') || linkCapsule.getAttribute('href')
    if (href && href !== '#') {
      // 使用iframe打开链接
      showLinkInIframe(href)
    }
    return
  }
  
  // 原有的标准引用处理逻辑
  if (!target.classList.contains('standard-reference')) return
  
  event.preventDefault()
  event.stopPropagation()
  
  const fileName = target.getAttribute('data-standard') || target.getAttribute('data-reference')
    
    if (fileName) {
      try {
        const response = await apis.getFileLink({ fileName })
        
        if (response.statusCode === 200 && response.data) {
        if (response.data) {
          window.open(response.data, '_blank')
          } else {
            ElMessage.warning('暂无文件')
          }
        } else {
          ElMessage.warning('暂无文件')
        }
      } catch (error) {
      console.error('获取文件失败:', error)
        ElMessage.error('获取文件失败，请稍后重试')
      }
    }
  }

// 在iframe中显示链接
const showLinkInIframe = (url) => {
  // 检查URL是否有效
  try {
    new URL(url)
  } catch {
    ElMessage.error('无效的链接地址')
    return
  }
  
  // 创建一个模态框显示iframe
  const modal = document.createElement('div')
  modal.style.cssText = `
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    z-index: 10000;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 20px;
  `
  
  const container = document.createElement('div')
  container.style.cssText = `
    width: 90%;
    height: 90%;
    background: white;
    border-radius: 12px;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
  `
  
  const header = document.createElement('div')
  header.style.cssText = `
    padding: 16px 20px;
    background: #f5f5f5;
    border-bottom: 1px solid #e0e0e0;
    display: flex;
    align-items: center;
    justify-content: space-between;
  `
  
  const urlDisplay = document.createElement('div')
  urlDisplay.style.cssText = `
    font-size: 14px;
    color: #666;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    flex: 1;
    margin-right: 16px;
  `
  urlDisplay.textContent = url
  
  const closeBtn = document.createElement('button')
  closeBtn.textContent = '✕'
  closeBtn.style.cssText = `
    background: none;
    border: none;
    font-size: 24px;
    color: #666;
    cursor: pointer;
    padding: 0;
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 4px;
    transition: all 0.2s;
  `
  closeBtn.onmouseover = () => {
    closeBtn.style.background = '#e0e0e0'
  }
  closeBtn.onmouseout = () => {
    closeBtn.style.background = 'none'
  }
  closeBtn.onclick = () => {
    document.body.removeChild(modal)
  }
  
  const iframe = document.createElement('iframe')
  iframe.src = url
  iframe.style.cssText = `
    width: 100%;
    height: 100%;
    border: none;
  `
  
  header.appendChild(urlDisplay)
  header.appendChild(closeBtn)
  container.appendChild(header)
  container.appendChild(iframe)
  modal.appendChild(container)
  
  // 点击背景关闭
  modal.onclick = (e) => {
    if (e.target === modal) {
      document.body.removeChild(modal)
    }
  }
  
  document.body.appendChild(modal)
}

// 文件预览处理函数
const handleFilePreview = (data) => {
  if (typeof data === 'string') {
    previewFilePath.value = data
    previewFileName.value = ''
  } else {
    previewFilePath.value = data.filePath
    previewFileName.value = data.fileName || ''
  }
  showFilePreview.value = true
}

// 处理网络搜索胶囊点击
const handleWebSearchToggle = (messageIndex) => {
  const message = chatMessages.value[messageIndex]
  if (message && message.webSearchRaw) {
    currentWebSearchData.value = message.webSearchRaw
    webSearchSidebarVisible.value = !webSearchSidebarVisible.value
  }
}

// 监听语音识别错误
watch(transcript, (newVal) => {
  if (!newVal || isListening.value) return
  messageText.value = newVal
})

watch(speechError, (newVal) => {
  if (newVal) {
    console.error('语音识别错误:', newVal)
    ElMessage.error(newVal)
  }
})

// 监听网络搜索侧边栏状态变化，实时更新吸附位置
watch(webSearchSidebarVisible, (newVal) => {
  console.log('🔍 网络搜索侧边栏状态变化:', newVal)
  
  // 等待下一帧，确保main-chat的class已更新
  requestAnimationFrame(() => {
    // 在transition完成后更新位置
    setTimeout(() => {
      handleBrowserResize()
    }, 350)
  })
})

// 绑定规范引用点击事件
const bindStandardReferenceEvents = () => {
  const references = document.querySelectorAll('.standard-reference')
  references.forEach(ref => {
    ref.removeEventListener('click', handleStandardReferenceClick)
    ref.addEventListener('click', handleStandardReferenceClick)
  })
}

// 监听路由变化，自动发送消息
// 处理浏览器缩放的防抖定时器
let resizeDebounceTimer = null
// 上次记录的fontSize，用于检测flexible缩放变化
let lastFontSize = null

// 处理文件统计卡片滚动吸附到顶部域
const handleProgressCardScroll = () => {
  console.log('📜 handleProgressCardScroll 被触发')
  const chatHeader = document.querySelector('.chat-header')
  const headerBottom = chatHeader ? chatHeader.getBoundingClientRect().bottom : 0
  console.log('📐 headerBottom:', headerBottom)
  
  console.log('📊 messageContentRefs 数量:', Object.keys(messageContentRefs.value).length)
  
  Object.keys(messageContentRefs.value).forEach(index => {
    const message = chatMessages.value[index]
    if (!message || message.type !== 'ai' || !message.showStats) {
      console.log(`⏭️ 跳过消息 ${index}:`, { 
        exists: !!message, 
        type: message?.type, 
        showStats: message?.showStats 
      })
      return
    }
    
    console.log(`✅ 处理消息 ${index}`)
    
    const contentEl = messageContentRefs.value[index]
    if (!contentEl) {
      console.log(`❌ 消息 ${index} 没有找到 contentEl`)
      return
    }
    
    // 查找文件统计白色卡片
    const statsCard = contentEl.querySelector('.files-stats-white')
    if (!statsCard) {
      console.log(`❌ 消息 ${index} 没有找到 .files-stats-white`)
      return
    }
    
    console.log(`✅ 消息 ${index} 找到进度卡片`)
    
    const cardRect = statsCard.getBoundingClientRect()
    const contentRect = contentEl.getBoundingClientRect()
    
    // 如果还没有保存状态，先初始化
    if (!messageScrollStates.value[index]) {
      // 初始化状态，但默认不吸附
      messageScrollStates.value[index] = {
        initialLeft: cardRect.left,  // 立即使用当前位置
        initialWidth: cardRect.width, // 立即使用当前宽度
        isSticky: false,
        // 保存卡片相对于消息内容的初始偏移量
        offsetTop: cardRect.top - contentRect.top,
        // 标记是否已初始化完成（用于延迟判断吸附）
        initialized: false,
        // 标记是否正在初始化
        isInitializing: true,
        // 记录初始化开始时间，用于防止过早吸附
        initStartTime: Date.now()
      }
      
      console.log(`[进度卡片] 开始初始化 - 消息${index}, left=${cardRect.left}, width=${cardRect.width}, offsetTop=${messageScrollStates.value[index].offsetTop}`)
      
      // 使用nextTick确保DOM渲染完成后再标记初始化完成
      nextTick(() => {
        // 再次使用requestAnimationFrame确保布局完成
        requestAnimationFrame(() => {
          if (messageScrollStates.value[index]) {
            // 重新获取元素位置（此时DOM已经稳定）
            const updatedStatsCard = contentEl.querySelector('.files-stats-white')
            if (updatedStatsCard) {
              const updatedCardRect = updatedStatsCard.getBoundingClientRect()
              messageScrollStates.value[index].initialLeft = updatedCardRect.left
              messageScrollStates.value[index].initialWidth = updatedCardRect.width
              
              console.log(`[进度卡片] 位置更新 - 消息${index}, left=${updatedCardRect.left}, width=${updatedCardRect.width}`)
            }
            
            // 设置一个最小初始化时间（100ms），防止过早吸附
            const elapsed = Date.now() - messageScrollStates.value[index].initStartTime
            const remainingTime = Math.max(0, 100 - elapsed)
            
      setTimeout(() => {
        if (messageScrollStates.value[index]) {
          messageScrollStates.value[index].initialized = true
                messageScrollStates.value[index].isInitializing = false
                console.log(`[进度卡片] 初始化完成 - 消息${index}`)
        }
            }, remainingTime)
          }
        })
      })
      
      // 初始化阶段直接返回，不进行吸附判断
      return
    }
    
    // 如果还没初始化完成或正在初始化，跳过吸附判断
    if (!messageScrollStates.value[index].initialized || messageScrollStates.value[index].isInitializing) {
      return
    }
    
    // 额外检查：确保初始化后至少过了100ms才允许吸附（防止初始化期间的意外吸附）
    const timeSinceInit = Date.now() - messageScrollStates.value[index].initStartTime
    if (timeSinceInit < 100) {
      console.log(`⏱️ 消息 ${index} 初始化中，已过${timeSinceInit}ms，跳过吸附判断`)
      return
    }
    
    // 计算卡片的"自然"位置（如果不吸附的话应该在哪里）
    // 自然位置 = 消息内容的顶部 + 卡片的初始偏移量
    const naturalTop = contentRect.top + messageScrollStates.value[index].offsetTop
    
    // 判断是否需要吸附
    // 条件：
    // 1. 卡片的自然位置已经到达或超过顶部域（naturalTop <= headerBottom）
    // 2. 输出框还在可视范围内（contentRect.bottom > headerBottom + 60）
    // 3. 当滚动回到原位置时，自然位置会大于顶部域，此时自动解除吸附
    const shouldStick = naturalTop <= headerBottom && contentRect.bottom > headerBottom + 60
    
    console.log(`📍 消息 ${index} 吸附判断:`, {
      naturalTop,
      headerBottom,
      'naturalTop <= headerBottom': naturalTop <= headerBottom,
      'contentRect.bottom': contentRect.bottom,
      'headerBottom + 60': headerBottom + 60,
      shouldStick,
      currentlySticky: messageScrollStates.value[index].isSticky
    })
    
    // 如果从吸附变为非吸附，或从非吸附变为吸附，更新位置信息
    if (messageScrollStates.value[index].isSticky !== shouldStick) {
      if (!shouldStick) {
        // 解除吸附时，重新计算位置（此时卡片回到正常流，可以获取正确位置）
        messageScrollStates.value[index].initialLeft = cardRect.left
        messageScrollStates.value[index].initialWidth = cardRect.width
      } else {
        // 开始吸附时，使用当前位置（此时还未fixed，位置准确）
        messageScrollStates.value[index].initialLeft = cardRect.left
        messageScrollStates.value[index].initialWidth = cardRect.width
      }
    }
    // 注意：当保持吸附状态时（shouldStick && isSticky都为true），不更新位置
    // 因为此时cardRect.left是fixed后的位置，可能因为缩放等原因不准确
    
    messageScrollStates.value[index].isSticky = shouldStick
    messageScrollStates.value[index].stickyTop = headerBottom
  })
}

// 处理浏览器缩放的函数（带防抖）
const handleBrowserResize = () => {
  // 检测是否是flexible方案导致的fontSize变化
  const currentFontSize = window.getComputedStyle(document.documentElement).fontSize
  const isFontSizeChanged = lastFontSize && currentFontSize !== lastFontSize
  
  if (isFontSizeChanged) {
    console.log('🔍 检测到flexible fontSize变化:', lastFontSize, '->', currentFontSize)
  }
  
  lastFontSize = currentFontSize
  
  // 清除之前的定时器
  if (resizeDebounceTimer) {
    clearTimeout(resizeDebounceTimer)
  }
  
  // 100ms防抖延迟（缩短延迟以更快响应）
  resizeDebounceTimer = setTimeout(() => {
    console.log('🔍 检测到窗口大小变化，重新计算所有吸附卡片位置')
    
    // 强制浏览器完成layout重排
    document.body.offsetHeight
    
    // 临时解除所有吸附状态，以便重新计算正确位置
    const stickyStates = {}
    Object.keys(messageScrollStates.value).forEach(index => {
      const state = messageScrollStates.value[index]
      if (state && state.isSticky) {
        stickyStates[index] = true
        state.isSticky = false
      }
    })
    
    // 使用nextTick确保DOM更新完成
    nextTick(() => {
      // 强制再次重排
      document.body.offsetHeight
      
      // 重新计算所有卡片的位置
      Object.keys(messageScrollStates.value).forEach(index => {
        const state = messageScrollStates.value[index]
        if (!state) return
        
        const contentEl = messageContentRefs.value[index]
        if (!contentEl) return
        
        const statsCard = contentEl.querySelector('.files-stats-white')
        if (!statsCard) return
        
        const cardRect = statsCard.getBoundingClientRect()
        const contentRect = contentEl.getBoundingClientRect()
        
        // 更新位置信息（此时元素已恢复正常流，位置准确）
        state.initialLeft = cardRect.left
        state.initialWidth = cardRect.width
        state.offsetTop = cardRect.top - contentRect.top
        
        console.log(`  - 更新消息${index}的位置: left=${cardRect.left}, width=${cardRect.width}`)
      })
      
      // 恢复吸附状态
      Object.keys(stickyStates).forEach(index => {
        if (messageScrollStates.value[index]) {
          messageScrollStates.value[index].isSticky = true
        }
      })
      
      // 再次触发滚动检测，确保吸附状态正确
      nextTick(() => {
        handleProgressCardScroll()
      })
    })
  }, 100)
}

onMounted(async () => {
  try {
    console.log('🚀 AI问答页面初始化开始，优先加载历史记录...')
    
    // 设置初始加载状态
    isLoadingHistory.value = true
    
    // 添加全局错误处理
    window.addEventListener('error', (event) => {
      console.error('全局错误:', event.error)
    })
    
    window.addEventListener('unhandledrejection', (event) => {
      console.error('未处理的Promise拒绝:', event.reason)
    })
    
    // 移除可能存在的旧事件监听器，然后添加新的
    document.removeEventListener('click', handleStandardReferenceClick)
    document.addEventListener('click', handleStandardReferenceClick)
    
    // 添加滚动监听用于进度卡片吸顶
    const chatContent = document.querySelector('.chat-content')
    if (chatContent) {
      console.log('✅ 找到 .chat-content 元素，添加滚动监听')
      console.log('📦 .chat-content 样式:', {
        overflow: window.getComputedStyle(chatContent).overflow,
        overflowY: window.getComputedStyle(chatContent).overflowY,
        height: chatContent.offsetHeight,
        scrollHeight: chatContent.scrollHeight
      })
      
      // 添加测试监听器来确认滚动事件能触发
      chatContent.addEventListener('scroll', () => {
        console.log('🔄 滚动事件触发！scrollTop:', chatContent.scrollTop)
      }, { once: true }) // 只触发一次，避免刷屏
      
      chatContent.addEventListener('scroll', handleProgressCardScroll)
    } else {
      console.error('❌ 未找到 .chat-content 元素')
    }
    
    // 初始化fontSize记录，用于检测flexible缩放变化
    lastFontSize = window.getComputedStyle(document.documentElement).fontSize
    console.log('📐 初始fontSize:', lastFontSize)
    
    // 添加浏览器缩放监听器（带防抖）
    window.addEventListener('resize', handleBrowserResize)
    
    // 添加页面卸载事件监听器，在刷新时停止语音朗读
    
    window.addEventListener('beforeunload', handlePageUnload)
    window.addEventListener('unload', handlePageUnload)
    document.addEventListener('visibilitychange', handleVisibilityChange)
    
    // 初始化缩放补偿 - 修复中括号背景色随浏览器缩放变化的问题
    initBracketZoomCompensation()
    
    // 1. 首先获取历史记录列表（最高优先级）
    await getHistoryRecordList()
    console.log('✅ AI问答历史记录加载完成')
    
    // 2. 测试TTS服务连接
    try {
      const ttsTest = await testTTSConnection()
      if (ttsTest.success) {
        console.log('✅ TTS服务连接正常')
      } else {
        console.warn('⚠️ TTS服务连接异常:', ttsTest.message)
      }
    } catch (error) {
      console.warn('⚠️ TTS服务连接测试失败:', error)
    }
    
    // 2. 并行获取其他非关键数据（不阻塞历史记录显示）
    const otherDataPromise = Promise.all([
      getFunctionCards(),
      getHotQuestions()
    ])
    
    // 3. 等待其他数据加载完成（后台进行）
    try {
      await otherDataPromise
      console.log('✅ AI问答其他数据加载完成')
    } catch (error) {
      console.warn('⚠️ AI问答其他数据加载失败，但不影响主要功能:', error)
    }
    
    console.log('🎉 AI问答页面初始化完成')
    
    // 检查是否有自动发送的消息
    const autoMessage = route.query.autoMessage
    if (autoMessage) {
      console.log('检测到自动发送消息:', autoMessage)
      
      // 立即清除URL中的autoMessage参数，防止刷新时重复发送
      router.replace({
        path: route.path,
        query: { ...route.query, autoMessage: undefined }
      })
      
      // 延迟一下，确保组件完全挂载
      // setTimeout(() => {
      //   autoSendMessage(autoMessage)
      // }, 100)
      autoSendMessage(autoMessage)
    }
  } catch (error) {
    console.error('组件初始化失败:', error)
  }
})

// 组件销毁前，强制停止任何朗读
onBeforeUnmount(() => {
  if (speakingMessageId.value) {
    stopAllAudio()
    speakingMessageId.value = null
  }
  
  // 清理所有打字机定时器
  clearAllTypeIntervals()
  
  // 清理事件监听器，防止重复绑定
  document.removeEventListener('click', handleStandardReferenceClick)
  
  // 清理进度卡片滚动监听
  const chatContent = document.querySelector('.chat-content')
  if (chatContent) {
    chatContent.removeEventListener('scroll', handleProgressCardScroll)
  }
  
  // 清理浏览器缩放监听器
  window.removeEventListener('resize', handleBrowserResize)
  
  // 清理防抖定时器
  if (resizeDebounceTimer) {
    clearTimeout(resizeDebounceTimer)
    resizeDebounceTimer = null
  }
  
  // 清理页面卸载和可见性变化事件监听器
  window.removeEventListener('beforeunload', handlePageUnload)
  window.removeEventListener('unload', handlePageUnload)
  document.removeEventListener('visibilitychange', handleVisibilityChange)
})

// 页面重新激活时，重新渲染所有AI消息的markdown内容
onActivated(async () => {
  console.log('页面重新激活，检查并重新渲染markdown内容')
  
  // 等待DOM更新
  await nextTick()
  
  // 重新渲染所有AI消息的markdown内容
  for (const message of chatMessages.value) {
    if (message.type === 'ai' && message.content && !message.isTyping) {
      try {
        console.log('重新渲染AI消息markdown:', message.id)
        const processedReply = processAIResponse(message.content)
        const processedReplyWithFileDisplay = processFileDisplay(processedReply, message.file)
        const htmlReply = renderMarkdownContent(processedReplyWithFileDisplay)
        message.displayContent = htmlReply
        
        // 重新绑定规范引用点击事件
        setTimeout(() => {
          bindStandardReferenceEvents()
        }, 100)
      } catch (error) {
        console.error('重新渲染markdown失败:', error)
        // 如果重新渲染失败，保持原有内容
      }
    }
  }
  
  // 强制触发Vue响应式更新
  chatMessages.value = [...chatMessages.value]
  
  console.log('页面重新激活完成，markdown内容已重新渲染')
})


</script>

<style lang="less" scoped>
// 删除图标样式
.delete-icon {
  width: 16px;
  height: 16px;
}

.chat-container {
  display: flex;
  height: 100vh;
  font-family: 'Alibaba PuHuiTi 3.0', sans-serif;
}

/* 中间历史记录栏 */
.history-sidebar {
  width: 280px;
  min-width: 280px;
  flex-shrink: 0;
  background: #E8F0FF;
  display: flex;
  flex-direction: column;
}

/* 中间历史记录栏样式 */
.history-sidebar {
  padding: 24px 16px 0 16px;

  .new-chat-container {
    margin-bottom: 24px;
    
    .new-chat-btn-full {
      width: 100%;
      height: 44px;
      background-color: #3E7BFA;
      color: white;
      border: none;
      border-radius: 8px;
      font-size: 14px;
      font-weight: 500;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 6px;
      cursor: pointer;
      transition: background-color 0.2s;
      
      .plus-icon {
        font-size: 18px;
        font-weight: 400;
        margin-bottom: 2px;
      }
      
      &:hover:not(:disabled) {
        background-color: #2b65e2;
      }
      
      &:disabled {
        opacity: 0.6;
        cursor: not-allowed;
      }
    }
  }

  .history-header {
    background: transparent;
    margin-bottom: 16px;
    
    .section-title {
      font-size: 16px;
      font-weight: 600;
      color: #2C3E50;
    }
  }
  
  .history-list {
    flex: 1;
    overflow-y: auto;
    width: 248px;
    height: 64px;
    
    /* 隐藏滚动条 */
    &::-webkit-scrollbar {
      display: none;
    }
    
    -ms-overflow-style: none;  /* IE and Edge */
    scrollbar-width: none;  /* Firefox */
    
    .history-item {
      background: white;
      border-radius: 8px;
      padding: 15px;
      margin-bottom: 8px;
      cursor: pointer;
      transition: all 0.3s ease;
      border-left: 3px solid transparent;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
      display: flex;
      align-items: center;
      justify-content: space-between;
      position: relative;
      
      &:hover {
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
        
        .delete-btn {
          opacity: 1;
          visibility: visible;
        }
      }
      
      &.active {
        border-left-color: #3E7BFA;
        box-shadow: 0 2px 8px rgba(62, 123, 250, 0.2);
        cursor: default;
        opacity: 0.8;
        
        &:hover {
          transform: none;
          box-shadow: 0 2px 8px rgba(62, 123, 250, 0.2);
        }
      }
      
      .history-content {
        flex: 1;
        min-width: 0; // 允许内容收缩
      }
      
      .history-title {
        font-size: 14px;
        line-height: 1.4;
        margin-bottom: 6px;
        color: #2C3E50;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      
      .history-time {
        font-size: 12px;
        color: #7C8DB5;
      }
      
      .delete-btn {
        opacity: 0;
        visibility: hidden;
        transition: all 0.2s ease;
        cursor: pointer;
        padding: 4px;
        border-radius: 4px;
        color: #7C8DB5;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-left: 8px;
        flex-shrink: 0;
        
        &:hover {
          color: #ff4757;
          background-color: rgba(255, 71, 87, 0.1);
        }
        
        &.always-visible {
          opacity: 1;
          visibility: visible;
        }
      }
    }
    
    .empty-history {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      // height: 200px;
      // padding: 20px;
      margin-top: 236px;
      
      .empty-icon {
        width: 147px;
        height: 148px;
        object-fit: contain;
        margin-bottom: 16px;
      }
      
      .empty-text {
        font-size: 16px;
        color: #9C9FA7;
        text-align: center;
      }
    }
  }
}



/* 主聊天区域 */
.embedded-exam-workshop {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  height: 100vh;
}

.exam-workshop-wrapper {
  flex: 1;
  overflow-y: auto;
  position: relative;
  background: #f5f7fb;
}

.main-chat {
  flex: 1;
  background: #EBF3FF;
  display: flex;
  flex-direction: column;
  transition: margin-right 0.3s ease;
}

.main-chat.sidebar-open {
  margin-right: 400px;
}

/* 聊天头部 */
.chat-header {
  background: transparent;
  padding: 20px 0px 0px 18px; /* 从30px改为20px，向上提升10px */
  
  .default-title {
    margin: 0;
    font-size: 20px;
    font-weight: 600;
    color: #2C3E50;
  }
  
  .question-title-card {
    display: inline-flex;
    align-items: center;
    background: rgba(91, 141, 239, 0.08);
    backdrop-filter: blur(10px);
    -webkit-backdrop-filter: blur(10px);
    border: 1px solid rgba(91, 141, 239, 0.2);
    border-radius: 20px;
    padding: 6px 16px;
    box-shadow: 0 2px 8px rgba(91, 141, 239, 0.1);
    transition: all 0.3s ease;
    max-width: 750px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;

    h2 {
      margin: 0;
      font-size: 13px;
      font-weight: 600;
      color: #5b8def;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      letter-spacing: 0.3px;
    }

    &:hover {
      background: rgba(91, 141, 239, 0.12);
      border-color: rgba(91, 141, 239, 0.3);
      transform: translateY(-1px);
      box-shadow: 0 4px 12px rgba(91, 141, 239, 0.15);
    }
  }
}

/* 聊天内容区域 */
.chat-content {
  flex: 1;
//   padding: 40px 30px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 24px;
}

/* 初始内容样式 */
.initial-content {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
}

/* 聊天消息区域 */
// .chat-messages {
//   width: 100%;
//   max-width: 900px;
//   padding: 0 30px;
//   display: flex;
//   flex-direction: column;
//   gap: 24px;
// }

/* 消息项样式 */
.message-item {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

/* 用户消息样式 */
.user-message {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 8px;
  
  .message-content {
    background: #004BFF20;
    color: #000000;
    padding: 16px 20px;
    border-radius: 18px 0px 18px 18px;
    max-width: 900px;
    word-wrap: break-word;
    line-height: 1.5;
    font-size: 16px;
    overflow: hidden;
    .message-file {
      margin-bottom: 12px;
      
      .file-display {
        display: flex;
        align-items: center;
        background: rgba(255, 255, 255, 0.8);
        border: 1px solid #E5E7EB;
        border-radius: 12px;
        padding: 16px;
        max-width: 400px;
        
        .file-icon {
          font-size: 32px;
          margin-right: 16px;
          width: 48px;
          text-align: center;
          
          .file-icon-img {
            width: 32px;
            height: 32px;
            object-fit: contain;
          }
        }
        
        .file-details {
          flex: 1;
          
          .file-name {
            font-size: 14px;
            font-weight: 500;
            color: #374151;
            margin-bottom: 4px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            max-width: 200px;
          }
          
          .file-size {
            font-size: 12px;
            color: #6B7280;
          }
        }
      }
    }
    
    .message-text {
      margin-top: 0;
    }
  }
  
  .message-actions {
    display: flex;
    // gap: 8px;
    
    .action-btn {
      background: none;
      border: none;
      padding: 6px 4px;
      border-radius: 4px;
      font-size: 12px;
      color: #6b7280;
      cursor: pointer;
      transition: all 0.2s ease;
      display: flex;
      align-items: center;
      gap: 4px;
      
      &:hover {
        color: #374151;
      }
      
      .action-icon {
        width: 16px;
        height: 16px;
        object-fit: contain;
      }
    }
  }
}

/* AI消息样式 */
.ai-message {
  display: flex;
  flex-direction: column;
  gap: 0;
  
  .ai-message-main {
    display: flex;
    gap: 12px;
  }
  
  // ReportGenerator相关样式
  .ai-response-content {
    width: 100%;
  }
  
  .question-summary {
    margin-bottom: 16px;
    font-size: 16px;
    line-height: 1.8;
    color: #606266;
  }
  
  .web-search-capsule-outer {
    margin-bottom: 7px;
    display: flex;
    justify-content: flex-start;
    padding-left: 52px;
  }
  
  .files-stats-white {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 16px;
    padding: 12px 16px;
    background: white;
    border-radius: 8px;
    margin-bottom: 16px;
    border: 1px solid #e8ecf1;
    transition: left 0.3s ease, width 0.3s ease, box-shadow 0.3s ease;
  }
  
  .files-stats-white.sticky {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    border-bottom: 2px solid #5b8def;
  }
  
  .stats-left {
    display: flex;
    align-items: center;
    gap: 12px;
    flex-shrink: 0;
  }
  
  .stats-avatar {
    flex-shrink: 0;
  }
  
  .stats-icon {
    font-size: 20px;
    color: #5b8def;
  }
  
  .stats-left span {
    font-size: 14px;
    font-weight: 500;
    color: #2d3748;
    white-space: nowrap;
  }
  
  .stats-left .brand-name {
    color: #5b8def !important;
    font-weight: 600 !important;
  }
  
  .stats-left .file-count {
    color: #5b8def !important;
    font-weight: 600 !important;
    font-size: 15px;
  }
  
  .stats-left .ai-name {
    color: #5b8def !important;
    font-weight: 600 !important;
  }
  
  /* 使用:deep()确保样式穿透到v-html渲染的内容 */
  .stats-left :deep(.ai-name) {
    color: #5b8def !important;
    font-weight: 600 !important;
  }
  
  .stats-left :deep(.file-count) {
    color: #5b8def !important;
    font-weight: 600 !important;
    font-size: 15px !important;
  }
  
  .stats-right {
    flex-shrink: 0;
  }
  
  /* 进度条内联样式 - 在白色卡片内 */
  .progress-capsule-inline {
    display: flex;
    align-items: center;
    gap: 12px;
    background: rgba(91, 141, 239, 0.08);
    border: 1px solid rgba(91, 141, 239, 0.2);
    padding: 8px 16px;
    border-radius: 20px;
    flex-shrink: 0;
  }
  
  .progress-capsule-inline .progress-label {
    white-space: nowrap;
    color: #5b8def;
    font-weight: 600;
    font-size: 13px;
  }
  
  .progress-capsule-inline .progress-bar-mini {
    position: relative;
    width: 100px;
    height: 6px;
    background: rgba(91, 141, 239, 0.15);
    border-radius: 3px;
    overflow: visible;
  }
  
  .progress-capsule-inline .progress-fill {
    height: 100%;
    background: linear-gradient(90deg, #5b8def 0%, #4a7ad8 100%);
    border-radius: 3px;
    transition: width 0.6s ease;
    box-shadow: 0 0 8px rgba(91, 141, 239, 0.3);
  }
  
  .progress-capsule-inline .progress-dot {
    position: absolute;
    top: 50%;
    transform: translate(-50%, -50%);
    width: 12px;
    height: 12px;
    background: white;
    border: 2px solid #5b8def;
    border-radius: 50%;
    box-shadow: 0 2px 6px rgba(91, 141, 239, 0.4);
    transition: left 0.6s ease;
    z-index: 1;
  }
  
  .progress-capsule-inline .progress-percentage {
    font-weight: 600;
    min-width: 40px;
    text-align: right;
    color: #5b8def;
    font-size: 13px;
  }
  
  
  .reports-list {
    margin-top: 8px;
  }
  
  .report-loading {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: flex-start;
    gap: 12px;
    padding: 12px 0;
    margin-top: 12px;
    margin-bottom: 8px;
  }
  
  .report-loading .loading-text {
    color: #6B7280;
    font-size: 14px;
    font-weight: 500;
  }
  
  .online-search-results {
    margin: 8px 0 12px 0;
    margin-top: 10px;
    background: white;
    border-radius: 12px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    margin-left: 52px;
    overflow: hidden;
    width: fit-content;
    
    .online-search-header {
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 12px;
      cursor: pointer;
      transition: background-color 0.2s ease;
      font-size: 14px;
      color: #37415180;
      
      &:hover {
        background-color: #f9fafb;
      }
      
      .expand-icon {
        margin-left: 8px;
        transition: transform 0.2s ease;
        color: #6b7280;
        
        &.expanded {
          transform: rotate(180deg);
        }
      }
    }
    
    .online-search-content {
      border-top: 1px solid #f3f4f6;
      padding: 16px;
      width: 735px;
      max-height: 400px;
      overflow-y: auto;
      
      /* 自定义滚动条样式 */
      &::-webkit-scrollbar {
        width: 6px;
      }
      
      &::-webkit-scrollbar-track {
        background: #f1f5f9;
        border-radius: 3px;
      }
      
      &::-webkit-scrollbar-thumb {
        background: #cbd5e1;
        border-radius: 3px;
        
        &:hover {
          background: #94a3b8;
        }
      }
      
      .search-results-section {
        .section-header {
          display: flex;
          align-items: center;
          margin-bottom: 16px;
          
          .section-icon {
            width: 24px;
            height: 24px;
            background: #f3f4f6;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 8px;
            font-size: 12px;
          }
          
          .section-title {
            font-size: 14px;
            color: #374151;
            font-weight: 500;
          }
        }
        
        .search-results-grid {
          display: grid;
          grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
          gap: 12px;
          
          .search-result-card {
            background: white;
            border: 1px solid #e5e7eb;
            border-radius: 8px;
            padding: 12px;
            position: relative;
            cursor: pointer;
            transition: all 0.2s ease;
            min-height: 80px;
            height: auto;
            
            &:hover {
              border-color: #3b82f6;
              box-shadow: 0 2px 8px rgba(59, 130, 246, 0.1);
            }
            
            .result-title {
              font-size: 13px;
              color: #1f2937;
              font-weight: 500;
              line-height: 1.4;
              margin-bottom: 6px;
              display: -webkit-box;
              -webkit-line-clamp: 1;
              line-clamp: 1;
              -webkit-box-orient: vertical;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
              padding-right: 30px;
            }
            
            .result-description {
              font-size: 12px;
              color: #6b7280;
              line-height: 1.4;
              display: -webkit-box;
              -webkit-line-clamp: 3;
              line-clamp: 3;
              -webkit-box-orient: vertical;
              overflow: hidden;
              word-break: break-word;
              text-overflow: ellipsis;
              padding-right: 30px;
            }
            
            .result-badge {
              position: absolute;
              top: 8px;
              right: 8px;
              width: 20px;
              height: 20px;
              background: #3b82f6;
              color: white;
              border-radius: 50%;
              display: flex;
              align-items: center;
              justify-content: center;
              font-size: 10px;
              font-weight: 600;
              z-index: 1;
            }
          }
        }
      }
    }
  }

  .search-sources {
    margin: 8px 0 12px 0;
    margin-top: 10px;
    background: white;
    border-radius: 12px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    margin-left: 52px;
    overflow: hidden;
    width: fit-content;
    
    .search-sources-header {
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 12px;
      cursor: pointer;
      transition: background-color 0.2s ease;
      font-size: 14px;
      color: #37415180;
      
      &:hover {
        background-color: #f9fafb;
      }
      
      .expand-icon {
        margin-left: 8px;
        transition: transform 0.2s ease;
        color: #6b7280;
        
        &.expanded {
          transform: rotate(180deg);
        }
      }
    }
    
    .search-sources-content {
      border-top: 1px solid #f3f4f6;
      padding: 16px;
      width: 735px;
      // max-width: 900px;
      max-height: 400px; /* 改为最大高度，允许动态调整 */
      overflow-y: auto;
      
      /* 自定义滚动条样式 */
      &::-webkit-scrollbar {
        width: 6px;
      }
      
      &::-webkit-scrollbar-track {
        background: #f1f5f9;
        border-radius: 3px;
      }
      
      &::-webkit-scrollbar-thumb {
        background: #cbd5e1;
        border-radius: 3px;
        
        &:hover {
          background: #94a3b8;
        }
      }
      
      .sources-section {
        .section-header {
          display: flex;
          align-items: center;
          margin-bottom: 16px;
          
          .section-icon {
            width: 24px;
            height: 24px;
            background: #f3f4f6;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 8px;
            font-size: 12px;
          }
          
          .section-title {
            font-size: 14px;
            color: #374151;
            font-weight: 500;
          }
        }
        
        .sources-grid {
          display: grid;
          grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
          gap: 12px;
          
          .source-card {
            background: white;
            border: 1px solid #e5e7eb;
            border-radius: 8px;
            padding: 12px;
            position: relative;
            cursor: pointer;
            transition: all 0.2s ease;
            min-height: 80px; /* 设置最小高度 */
            height: auto; /* 允许高度自适应 */
            
            &:hover {
              border-color: #3b82f6;
              box-shadow: 0 2px 8px rgba(59, 130, 246, 0.1);
            }
            
            .source-title {
              font-size: 13px;
              color: #1f2937;
              font-weight: 500;
              line-height: 1.4;
              margin-bottom: 6px;
              display: -webkit-box;
              -webkit-line-clamp: 1;
              line-clamp: 1;
              -webkit-box-orient: vertical;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
              padding-right: 30px; /* 为右侧数字留出空间 */
            }
            
            .source-description {
              font-size: 12px;
              color: #6b7280;
              line-height: 1.4;
              display: -webkit-box;
              -webkit-line-clamp: 3;
              line-clamp: 3;
              -webkit-box-orient: vertical;
              overflow: hidden;
              word-break: break-word;
              text-overflow: ellipsis;
              padding-right: 30px; /* 为右侧数字留出空间 */
            }
            
            .source-badge {
              position: absolute;
              top: 8px;
              right: 8px;
              width: 20px;
              height: 20px;
              background: #3b82f6;
              color: white;
              border-radius: 50%;
              display: flex;
              align-items: center;
              justify-content: center;
              font-size: 10px;
              font-weight: 600;
              z-index: 1; /* 确保在文字上方 */
            }
          }
        }
      }
    }
    
  }
  
    .related-questions {
      margin-top: 20px;
      padding: 0;
      margin-left: 52px;
      display: flex;
      flex-direction: column;
      gap: 8px;
      
      .related-question-item {
        display: flex;
        align-items: center;
        padding: 12px 16px;
        background: rgba(0,0,0,.05);
        border: 1px solid #e9ecef;
        border-radius: 12px;
        cursor: pointer;
        transition: all 0.2s ease;
        font-size: 16px;
        color: #212529;
        line-height: 1.4;
        width: fit-content;
        
        &:hover {
          background: #E2EBFE;
          border-color: #dee2e6;
        }
        
        .arrow-icon {
          width: 16px;
          height: 16px;
          color: #6c757d;
          flex-shrink: 0;
          margin-left: 8px;
        }
      }
    }
  
  .ai-avatar-small {
    width: 80px;
    height: 80px;
    animation: avatar-pulse 2s ease-in-out infinite;
    flex-shrink: 0;
    /* 位置调整：向上和向左移动，使输出框与搜索结果胶囊对齐 */
    margin-top: -40px;
    margin-left: -45px;
    
    .ai-icon {
      width: 100%;
      height: 100%;
      object-fit: contain;
      filter: drop-shadow(0 4px 16px rgba(91, 141, 239, 0.15));
    }
  }
  
  @keyframes avatar-pulse {
    0%, 100% {
      transform: scale(1);
    }
    50% {
      transform: scale(1.05);
    }
  }
  
  .message-content {
    background: white;
    color: #374151;
    padding: 16px 20px;
    border-radius: 0px 18px 18px 18px;
    max-width: 900px;
    width: 900px;
    word-wrap: break-word;
    line-height: 1.5;
    font-size: 16px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    white-space: normal;
    transition: width 0.3s ease;
    overflow: hidden;

    
    .ai-text {
      min-height: 20px;
      line-height: 1.5;
      margin-bottom: 16px;
      
      .typing-indicator {
        color: #9CA3AF;
        font-style: italic;
        font-size: 14px;
        display: flex;
        align-items: center;
        gap: 8px;
        white-space: nowrap;
        
        .thinking-animation {
          display: flex;
          gap: 4px;
          
          .dot {
            width: 6px;
            height: 6px;
            background: #9CA3AF;
            border-radius: 50%;
            animation: thinking 1.4s infinite ease-in-out;
            
            &:nth-child(1) { animation-delay: -0.32s; }
            &:nth-child(2) { animation-delay: -0.16s; }
            &:nth-child(3) { animation-delay: 0s; }
          }
        }
      }
      
      .safety-doc-card {
        display: flex;
        align-items: center;
        background: white;
        border: 1px solid #e2e8f0;
        border-radius: 12px;
        padding: 16px 20px;
        margin-bottom: 16px;
        cursor: pointer;
        transition: all 0.3s ease;
        box-shadow: 0 2px 8px rgba(0,0,0,0.04);
        max-width: 400px;

        &:hover {
          box-shadow: 0 4px 12px rgba(0,0,0,0.08);
          transform: translateY(-2px);
          border-color: #3e7bfa;
        }

        .doc-icon-wrapper {
          width: 48px;
          height: 48px;
          background: #f0f5ff;
          border-radius: 10px;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 16px;

          .doc-icon {
            width: 24px;
            height: 24px;
            object-fit: contain;
          }
        }

        .doc-info {
          flex: 1;

          .doc-title {
            font-size: 16px;
            font-weight: 600;
            color: #1f2937;
            margin-bottom: 4px;
          }

          .doc-time {
            font-size: 12px;
            color: #9ca3af;
          }
        }

        .doc-action {
          font-size: 14px;
          color: #3e7bfa;
          font-weight: 500;
        }
      }
      
      .ai-markdown-content {
        /* Markdown样式 - 与StreamMarkdown保持一致 */
        :deep(h2) {
          font-size: 16px;
          font-weight: 600;
          color: #303133;
          margin: 8px 0 4px 0;
          padding-bottom: 4px;
          border-bottom: 1px solid #dcdfe6;
        }

        :deep(h3) {
          font-size: 15px;
          font-weight: 600;
          color: #606266;
          margin: 8px 0 4px 0;
        }

        :deep(p) {
          margin: 8px 0;
          line-height: 1.8;
        }

        :deep(strong) {
          font-weight: 600;
          color: #303133;
        }

        :deep(ul),
        :deep(ol) {
          margin: 8px 0;
          padding-left: 24px;
        }

        :deep(li) {
          margin: 4px 0;
        }

        :deep(blockquote) {
          margin: 12px 0;
          padding: 8px 16px;
          border-left: 4px solid #5b8def;
          background-color: #f7f9fc;
          color: #606266;
        }

        :deep(code) {
          padding: 2px 6px;
          background-color: #f4f4f5;
          border-radius: 3px;
          font-family: 'Courier New', monospace;
          font-size: 13px;
        }

        :deep(pre) {
          margin: 12px 0;
          padding: 12px;
          background-color: #f4f4f5;
          border-radius: 4px;
          overflow-x: auto;
        }

        :deep(pre code) {
          padding: 0;
          background-color: transparent;
        }

        :deep(a) {
          color: #5b8def;
          text-decoration: none;
          cursor: pointer;
        }

        :deep(a:hover) {
          text-decoration: underline;
          color: #4a7de8;
        }

        :deep(hr) {
          margin: 16px 0;
          border: none;
          border-top: 1px solid #dcdfe6;
        }

        :deep(table) {
          border-collapse: collapse;
          width: 100%;
          margin: 12px 0;
        }

        :deep(th),
        :deep(td) {
          border: 1px solid #dcdfe6;
          padding: 8px 12px;
          text-align: left;
        }

        :deep(th) {
          background-color: #f4f4f5;
          font-weight: 600;
        }
      }
    }
    
    .divider {
      height: 1px;
      background: #e5e7eb;
      margin: 16px 0 8px 0;
    }
    
    
    .message-actions {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .left-actions {
        display: flex;
        gap: 8px;
        flex-wrap: wrap;
      }
      
      .right-actions {
        display: flex;
      }
      
              .action-btn {
          background: none;
          border: none;
          padding: 6px 5px;
          border-radius: 4px;
          cursor: pointer;
          transition: all 0.2s ease;
          display: flex;
          align-items: center;
          gap: 4px;
          font-size: 12px;
          color: #6b7280;
          
          &:hover:not(:disabled) {
            color: #374151;
            background: rgba(59, 130, 246, 0.1);
          }
          
          &:disabled {
            cursor: not-allowed;
          }
        
      .action-icon {
          width: 16px;
          height: 16px;
          object-fit: contain;
        }
        
      &.voice-btn.speaking {
        color: #dc2626;
        background: rgba(239, 68, 68, 0.08);
        
        .action-icon {
          filter: brightness(0) saturate(100%) invert(27%) sepia(51%) saturate(2878%) hue-rotate(0deg) brightness(104%) contrast(97%);
        }
      }

        // 点赞和点踩按钮的特殊样式
        &.thumbs-up-btn {
          transition: all 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55);
          
          &:hover {
            color: #059669;
            transform: scale(1.1);
          }
          
          &.active {
            color: #059669;
            transform: scale(1.2);
            
            .action-icon {
              filter: brightness(0) saturate(100%) invert(27%) sepia(51%) saturate(2878%) hue-rotate(142deg) brightness(104%) contrast(97%);
            }
          }
          
          &:active {
            transform: scale(0.9);
            transition: all 0.1s ease;
          }
        }
        
        &.thumbs-down-btn {
          transition: all 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55);
          
          &:hover {
            color: #dc2626;
            transform: scale(1.1);
          }
          
          &.active {
            color: #dc2626;
            transform: scale(1.2);
            
            .action-icon {
              filter: brightness(0) saturate(100%) invert(27%) sepia(51%) saturate(2878%) hue-rotate(0deg) brightness(104%) contrast(97%) !important;
            }
          }
          
          &:active {
            transform: scale(0.9);
            transition: all 0.1s ease;
          }
        }
      }
    }
  }
  

}

/* 打字动画 */
@keyframes thinking {
  0%, 80%, 100% {
    transform: scale(0.8);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

/* 初始内容样式 */
.initial-content {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
}

/* 聊天消息区域 */
.chat-messages {
  width: 100%;
  max-width: 1060px;
  padding: 0 75px 0 35px;
  display: flex;
  flex-direction: column;
  gap: 24px;
  padding-bottom: 40px; /* 添加底部间距 */
}

/* 消息项样式 */
// .message-item {
//   display: flex;
//   flex-direction: column;
//   gap: 12px;
// }


  
  /* 打字动画 */
  @keyframes fadeIn {
    from {
      opacity: 0;
      transform: translateY(2px);
    }
    to {
      opacity: 1;
      transform: translateY(0);
    }
  }
  
  /* AI助手介绍 */
.ai-intro {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 40px;
  
  .ai-avatar {
    width: 160px;
    height: 160px;
    border-radius: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 20px;
    animation: avatar-float 3s ease-in-out infinite;
    
    .ai-avatar-img {
      width: 100%;
      height: 100%;
      object-fit: contain;
      filter: drop-shadow(0 8px 24px rgba(91, 141, 239, 0.2));
    }
  }
  
  @keyframes avatar-float {
    0%, 100% {
      transform: translateY(0);
    }
    50% {
      transform: translateY(-8px);
    }
  }
  
  .ai-greeting {
    text-align: center;
    
    h3 {
      font-size: 24px;
      font-weight: 600;
      color: #2C3E50;
      margin: 0 0 8px 0;
    }
    
    p {
      font-size: 16px;
      color: #7C8DB5;
      margin: 0;
    }
  }
}

/* 功能卡片 */
.function-cards {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
  margin-top: 56px;
  max-width: 592px;
    
  
  .function-card {
    background: white;
    width: 288px;
    height: 112px;
    padding: 20px 0px;
    padding-left: 20px;
    border-radius: 12px;
    border: 1px solid #E5E8EB;
    cursor: pointer;
    transition: all 0.3s ease;
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    
    
    &:hover {
      border-color: #667eea;
      transform: translateY(-2px);
      box-shadow: 0 4px 20px rgba(102, 126, 234, 0.1);
    }
    
    .card-header {
      display: flex;
      align-items: center;
      gap: 16px;
      margin-bottom: 8px;
      
      .card-icon {
        width: 40px;
        height: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
        background: #F3F5FF;
        border-radius: 8px;
        flex-shrink: 0;
        
        .card-icon-img {
          width: 40px;
          height: 40px;
          object-fit: contain;
        }
      }
      
      h4 {
        font-size: 16px;
        font-weight: 600;
        color: #2C3E50;
        margin: 0;
        line-height: 1.5;
        flex: 1;
      }
    }
    
    .card-description {
        margin-left: 55px;
      p {
        font-size: 14px;
        color: #7C8DB5;
        margin: 0;
        line-height: 1.4;
      }
    }
  }
}

/* 推荐问题 */
.recommended-questions {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  justify-content: center;
  max-width: 900px;
  margin: 0 auto 12px auto;
  padding: 0;
  
  .question-tag {
    background: white;
    padding: 8px 16px;
    border-radius: 20px;
    border: 1px solid #E5E8EB;
    font-size: 14px;
    color: #5A6C7D;
    cursor: pointer;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    gap: 8px;
    white-space: nowrap;
    box-shadow: 0 2px 4px rgba(0,0,0,0.02);
    
    &:hover {
      border-color: #3E7BFA;
      color: #3E7BFA;
      transform: translateY(-1px);
      box-shadow: 0 4px 8px rgba(0,0,0,0.05);
    }
    
    .question-icon {
      width: 16px;
      height: 16px;
      object-fit: contain;
      flex-shrink: 0;
    }
  }
}

/* 用户推荐问题 */
.user-recommend-questions {
  position: absolute;
  bottom: 75px; /* 位于输入框上方 */
  left: 360px; /* 左侧边栏宽度 */
  right: 0;
  max-width: 900px; /* 与输入框容器的最大宽度一致 */
  margin: 0 auto; /* 居中显示 */
  background: white;
  border-radius: 12px;
  padding: 16px 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border: 1px solid #E5E8EB;
  z-index: 1; /* 降低z-index，避免覆盖输入框按钮 */
  
  .recommend-list {
    display: flex;
    flex-direction: column;
    gap: 8px;
    max-height: 280px; /* 限制高度，大约5条内容的高度 */
    overflow-y: auto; /* 超过高度时显示滚动条 */
    
    /* 自定义滚动条样式 */
    &::-webkit-scrollbar {
      width: 6px;
    }
    
    &::-webkit-scrollbar-track {
      background: #f1f5f9;
      border-radius: 3px;
    }
    
    &::-webkit-scrollbar-thumb {
      background: #cbd5e1;
      border-radius: 3px;
      
      &:hover {
        background: #94a3b8;
      }
    }
    
    .recommend-item {
      padding: 8px 10px;
      font-size: 16px;
      color: #000;
      cursor: pointer;
      transition: color 0.2s ease;
      line-height: 1.4;
      // border-bottom: 1px solid #F3F4F6;
      
      &:last-child {
        border-bottom: none;
      }
      
      &:hover {
        // color: #3E7BFA;
        background-color: #F5F6F9;
        border-radius: 10px;
      }
    }
  }
}

/* 文件预览区域 */
.file-preview-section {
  margin-bottom: 12px;
  
  .file-preview {
    position: relative;
    display: flex;
    align-items: center;
    background: rgba(255, 255, 255, 0.9);
    border: 1px solid #E5E7EB;
    border-radius: 12px;
    padding: 12px;
    max-width: 400px;
    
    .file-icon {
      font-size: 32px;
      margin-right: 12px;
      width: 48px;
      text-align: center;
      
      .file-icon-img {
        width: 32px;
        height: 32px;
        object-fit: contain;
      }
    }
    
    .file-info {
      flex: 1;
      
      .file-name {
        font-size: 14px;
        font-weight: 500;
        color: #374151;
        margin-bottom: 4px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        max-width: 200px;
      }
      
      .file-size {
        font-size: 12px;
        color: #6B7280;
        margin-bottom: 4px;
      }
      

    }
    
    .remove-file-btn {
      width: 24px;
      height: 24px;
      border: none;
      background: rgba(239, 68, 68, 0.1);
      color: #DC2626;
      border-radius: 50%;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: all 0.2s ease;
      
      &:hover {
        background: rgba(239, 68, 68, 0.2);
        transform: scale(1.1);
      }
      
      .remove-icon {
        font-size: 16px;
        font-weight: bold;
      }
    }
  }
}

/* 底部输入区域 */
.chat-input-section {
  background: transparent;
  padding: 9px 30px;
  
  .input-container {
    max-width: 900px;
    margin: 0 auto;
    
    
    .input-box {
      display: flex;
      flex-direction: column;
      background: white;
      border-radius: 16px;
      padding: 12px 16px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      transition: box-shadow 0.3s ease;
      border: 1px solid transparent;
      min-height: 120px;
      
      &:focus-within {
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
        border-color: #E5E8EB;
      }
      
      .attach-btn, .voice-btn, .network-search-btn {
        background: none;
        border: none;
        cursor: pointer;
        padding: 8px;
        border-radius: 6px;
        transition: all 0.3s ease;
        display: flex;
        align-items: center;
        justify-content: center;
        position: relative;
        
        &:hover:not(:disabled) {
          background: rgba(102, 126, 234, 0.1);
        }
        
        &:disabled {
          cursor: not-allowed;
        }
        
        &.recording {
          background: rgba(239, 68, 68, 0.1);
          animation: pulse 1.5s ease-in-out infinite;
        }
        
        &.active {
          background: rgba(62, 123, 250, 0.15);
          
          &:hover:not(:disabled) {
            background: rgba(62, 123, 250, 0.2);
          }
        }
        
        .icon-container {
          width: 20px;
          height: 20px;
          display: flex;
          align-items: center;
          justify-content: center;
          flex-shrink: 0;
          position: relative;
        }
        
        .recording-indicator {
          position: absolute;
          top: -2px;
          right: -2px;
          width: 8px;
          height: 8px;
          background: #ef4444;
          border-radius: 50%;
          animation: blink 1s ease-in-out infinite;
        }
        
        .action-icon {
          width: 20px;
          height: 20px;
          height: 20px !important;
          max-width: 20px !important;
          max-height: 20px !important;
          object-fit: contain;
          flex-shrink: 0;
        }
        
        // 联网搜索SVG图标样式
        .network-search-icon {
          width: 20px;
          height: 20px;
          color: #6B7280;
          transition: color 0.3s ease;
          flex-shrink: 0;
        }
      }
      
      // 联网搜索按钮激活状态下的图标颜色
      .network-search-btn.active .network-search-icon {
        color: #3E7BFA;
      }
      
      .mode-chips {
        display: flex;
        gap: 8px;
        margin-right: 12px;
      }
      
      .mode-chip {
        display: flex;
        align-items: center;
        background: transparent;
        color: #2C3E50;
        padding: 6px 12px;
        border-radius: 20px;
        font-size: 14px;
        font-weight: 500;
        gap: 6px;
        cursor: pointer;
        transition: all 0.2s ease;
        border: 1px solid transparent;
        
        .chip-icon {
          width: 16px;
          height: 16px;
          object-fit: contain;
          /* 将黑色图标转为灰色以匹配原图 */
          filter: invert(40%) sepia(8%) saturate(500%) hue-rotate(180deg) brightness(95%) contrast(85%);
          transition: filter 0.2s ease;
        }
        
        &:hover {
          background: #E8F0FE;
          color: #3E7BFA;
          
          .chip-icon {
            filter: invert(41%) sepia(91%) saturate(3574%) hue-rotate(213deg) brightness(101%) contrast(96%);
          }
        }
      }

      .expand-btn {
        background: none;
        border: none;
        cursor: pointer;
        padding: 8px;
        border-radius: 6px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 8px;
        
        &:hover:not(:disabled) {
          background: rgba(102, 126, 234, 0.1);
        }
        &:disabled {
          cursor: not-allowed;
          opacity: 0.5;
        }
      }

      .message-input {
        flex: 1;
        width: 100%;
        border: none;
        background: transparent;
        font-size: 15px;
        color: #2C3E50;
        outline: none;
        resize: none;
        font-family: inherit;
        padding: 0 4px;
        margin-bottom: 12px;
        
        &::placeholder {
          color: #A0A6B8;
        }
        
        &:disabled {
          cursor: not-allowed;
        }
      }

      .input-toolbar {
        display: flex;
        align-items: center;
        justify-content: space-between;
        width: 100%;

        .toolbar-left, .toolbar-right {
          display: flex;
          align-items: center;
          gap: 12px;
        }

        .model-link-btn, .attach-btn {
          background: none;
          border: none;
          cursor: pointer;
          padding: 8px;
          border-radius: 6px;
          display: flex;
          align-items: center;
          justify-content: center;
          
          &:hover:not(:disabled) {
            background: rgba(102, 126, 234, 0.1);
          }
          
          &:disabled {
            cursor: not-allowed;
            opacity: 0.5;
          }

          &.active {
            background: rgba(102, 126, 234, 0.1);
          }

          .action-icon {
            width: 20px;
            height: 20px;
            object-fit: contain;
          }

          .active-icon {
            filter: invert(41%) sepia(91%) saturate(3574%) hue-rotate(213deg) brightness(101%) contrast(96%);
          }
        }
      }
      
      .divider {
        width: 1px;
        height: 31px;
        background-color: #D6D5DE;
        margin: 0 4px;
      }
      
      .send-btn {
        background: none;
        border: none;
        cursor: pointer;
        margin-left: 4px;
        // padding: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 6px;
        transition: background 0.3s ease;
        display: flex;
        align-items: center;
        justify-content: center;
        
        &:hover:not(:disabled) {
          background: rgba(102, 126, 234, 0.1);
        }
        
        &:disabled {
          cursor: not-allowed;
        }
        
        .send-icon-circle {
          width: 36px;
          height: 36px;
          border-radius: 50%;
          background-color: #B0C4DE; /* Disabled state color */
          display: flex;
          align-items: center;
          justify-content: center;
          transition: background-color 0.3s ease;
          
          &.active {
            background-color: #7B9AF3; /* Active state color (matches the light blue in the image) */
          }
          
          svg {
            width: 20px;
            height: 20px;
          }
        }
        
        .stop-text {
          color: #FF4D4F;
          font-size: 14px;
          font-weight: 500;
          padding: 8px 16px;
          white-space: nowrap;
        }
      }
    }
  }
}


/* 点赞和点踩按钮的图标颜色变化 */
.thumbs-up-btn.active .action-icon {
  /* 绿色图标 */
  filter: brightness(0) saturate(100%) invert(27%) sepia(51%) saturate(2878%) hue-rotate(142deg) brightness(104%) contrast(97%) !important;
}

.thumbs-down-btn.active .action-icon {
  /* 红色图标 */
  filter: brightness(0) saturate(100%) invert(27%) sepia(51%) saturate(2878%) hue-rotate(0deg) brightness(104%) contrast(97%) !important;
}

/* 历史记录加载状态样式 */
.history-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  min-height: 200px;
}

.history-loading .loading-spinner {
  width: 32px;
  height: 32px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #409eff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 16px auto;
}

.history-loading .loading-text {
  color: #6B7280;
  font-size: 14px;
  margin: 0;
  font-weight: 400;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 联网搜索Loading样式 */
.online-search-loading {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 12px;
  margin-left: 52px;
  width: fit-content;
}

.online-search-loading .thinking-animation {
  display: flex;
  gap: 4px;
}

.online-search-loading .thinking-animation .dot {
  width: 6px;
  height: 6px;
  background: #9CA3AF;
  border-radius: 50%;
  animation: thinking 1.4s infinite ease-in-out;
}

.online-search-loading .thinking-animation .dot:nth-child(1) { 
  animation-delay: -0.32s; 
}

.online-search-loading .thinking-animation .dot:nth-child(2) { 
  animation-delay: -0.16s; 
}

.online-search-loading .thinking-animation .dot:nth-child(3) { 
  animation-delay: 0s; 
}

/* 推荐问题Loading样式 */
.related-questions-loading {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 12px;
  margin-left: 52px;
  width: fit-content;
}

.related-questions-loading .thinking-animation {
  display: flex;
  gap: 4px;
}

.related-questions-loading .thinking-animation .dot {
  width: 6px;
  height: 6px;
  background: #9CA3AF;
  border-radius: 50%;
  animation: thinking 1.4s infinite ease-in-out;
}

.related-questions-loading .thinking-animation .dot:nth-child(1) { 
  animation-delay: -0.32s; 
}

.related-questions-loading .thinking-animation .dot:nth-child(2) { 
  animation-delay: -0.16s; 
}

.related-questions-loading .thinking-animation .dot:nth-child(3) { 
  animation-delay: 0s; 
}

@keyframes pulse {
  0%, 100% {
    transform: scale(1);
    opacity: 1;
  }
  50% {
    transform: scale(1.05);
    opacity: 0.8;
  }
}

@keyframes blink {
  0%, 50% {
    opacity: 1;
  }
  51%, 100% {
    opacity: 0.3;
  }
}

/* ReportGenerator加载状态指示器样式（在AI回复下方左侧） */
.report-generator-loading {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 16px;
  margin-left: 52px; /* 与AI头像对齐，和提问联想一致 */
  margin-top: 20px;
}

.report-generator-loading .loading-dots {
  display: flex;
  gap: 4px;
}

.report-generator-loading .loading-dots span {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: #5b8def;
  animation: thinking 1.4s infinite ease-in-out;
}

.report-generator-loading .loading-dots span:nth-child(1) {
  animation-delay: -0.32s;
}

.report-generator-loading .loading-dots span:nth-child(2) {
  animation-delay: -0.16s;
}

.report-generator-loading .loading-dots span:nth-child(3) {
  animation-delay: 0s;
}

.report-generator-loading .loading-text {
  color: #5b8def;
  font-size: 14px;
  font-weight: 500;
}

/* 报告列表内Loading样式 */
.report-loading {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  margin: 12px 0;
}

.report-loading .thinking-animation {
  display: flex;
  gap: 6px;
}

.report-loading .thinking-animation .dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #5b8def;
  animation: thinking 1.4s infinite ease-in-out;
}

.report-loading .thinking-animation .dot:nth-child(1) {
  animation-delay: -0.32s;
}

.report-loading .thinking-animation .dot:nth-child(2) {
  animation-delay: -0.16s;
}

.report-loading .thinking-animation .dot:nth-child(3) {
  animation-delay: 0s;
}

/* 规范引用样式 */
:deep(.standard-reference) {
  background-color: #EAEAEE !important;
  color: #616161 !important;
  font-size: 0.75rem !important;
  padding: 3px 8px !important;
  border-radius: 6px !important;
  cursor: pointer !important;
  display: inline-block !important;
  margin: 4px 2px !important;
  border: 1px solid #EAEAEE !important;
  font-weight: 500 !important;
  transition: all 0.2s ease !important;
  line-height: 1.4 !important;
  max-width: 680px !important;
  white-space: nowrap !important;
  overflow: hidden !important;
  text-overflow: ellipsis !important;
  //向下移动
  transform: translateY(12px) !important;
}

:deep(.standard-reference:hover) {
  background-color: #d1d5db !important;
  border-color: #d1d5db !important;
}

</style>

