<template>
  <div class="layout" :class="{ 'dark-theme': isDarkTheme }">
    <!-- 添加密码修改弹窗组件 -->
    <ChangePasswordDialog
      v-model:visible="showPasswordDialog"
    />
    
    <!-- 进度条弹窗组件 -->
    <div v-if="showProgressModal" class="progress-modal-overlay">
      <div class="progress-modal">
        <div class="progress-modal-header">
          <h3>处理进度</h3>
          <button class="close-btn" @click="closeProgressModal">×</button>
        </div>
        <div class="progress-list">
          <div 
            v-for="(progress, index) in progressList" 
            :key="index" 
            class="progress-item"
            :class="{ 'completed': progress.value >= 100, 'error': progress.status === '错误' }"
          >
            <!-- 主进度项 -->
            <div class="progress-info">
              <div class="progress-title-wrapper">
                <span class="progress-icon">{{ getProgressIcon(progress) }}</span>
                <span class="progress-title">{{ progress.title }}</span>
              </div>
              <span class="progress-percentage" :class="getProgressClass(progress)">{{ progress.value }}%</span>
            </div>
            <div class="progress-bar-container">
              <div class="progress-bar" :style="{ width: progress.value + '%' }" :class="getProgressBarClass(progress)"></div>
            </div>
            <div class="progress-status">{{ progress.status }}</div>
            
            <!-- 子进度项 -->
            <div v-if="progress.subTasks && progress.subTasks.length > 0" class="sub-progress-list">
              <div 
                v-for="(subTask, subIndex) in progress.subTasks" 
                :key="subIndex"
                class="sub-progress-item"
                :class="{ 'completed': subTask.value >= 100, 'active': subTask.isActive }"
              >
                <div class="sub-progress-info">
                  <span class="sub-progress-icon">{{ getSubProgressIcon(subTask) }}</span>
                  <span class="sub-progress-title">{{ subTask.title }}</span>
                  <span class="sub-progress-percentage">{{ subTask.value }}%</span>
                </div>
                <div class="sub-progress-bar-container">
                  <div class="sub-progress-bar" :style="{ width: subTask.value + '%' }"></div>
                </div>
                
                <!-- 子子进度项 -->
                <div v-if="subTask.subSubTasks && subTask.subSubTasks.length > 0" class="sub-sub-progress-list">
                  <div 
                    v-for="(subSubTask, subSubIndex) in subTask.subSubTasks" 
                    :key="subSubIndex"
                    class="sub-sub-progress-item"
                    :class="{ 'completed': subSubTask.value >= 100, 'active': subSubTask.isActive }"
                  >
                    <div class="sub-sub-progress-info">
                      <span class="sub-sub-progress-icon">{{ getSubSubProgressIcon(subSubTask) }}</span>
                      <span class="sub-sub-progress-title">{{ subSubTask.title }}</span>
                      <span class="sub-sub-progress-percentage">{{ subSubTask.value }}%</span>
                    </div>
                    <div class="sub-sub-progress-bar-container">
                      <div class="sub-sub-progress-bar" :style="{ width: subSubTask.value + '%' }"></div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <div class="header">
      <div class="user-profile-bar">
         <div class="logo">
          <img
            :src="logo||'../assets/logoa.png'"
            alt="logo"
            class="logo-img"
          />
       <!--  <span>Raycos Tech</span> -->
      </div>
      <div class="user-info-bar">
        <!-- 添加文档预览测试按钮 -->
       <!--  <div class="test-preview-btn" @click="previewSprayPaintGuide" title="预览喷漆作业指导书">
          <span>📄</span>
          <span class="btn-text">预览文档</span>
        </div> -->
        
        <!-- 添加主题切换按钮 -->
        <div class="theme-switch" @click="toggleTheme" :title="isDarkTheme ? '切换到浅色模式' : '切换到深色模式'">
          <transition name="theme-icon" mode="out-in">
            <img 
            v-if="isDarkTheme"
              :key="isDarkTheme" 
              src="../assets/sun2.png" 
              alt="切换到浅色模式"
              class="theme-icon" 
            />
            <img v-else class="theme-icon"  src="../assets/night2.png" alt="切换到深色模式">
          </transition>
        </div>
        <div class="user-info" v-if="!isMobile" @click="toggleDropdown">
          <div class="user-name">商户名称：{{ userInfo.merchant_name || '未登录用户' }}</div>
          <div class="user-name" style="margin-left: 10px;">当前用户：{{ userInfo.username || '未登录用户' }}</div>
          <!-- <div class="user-role">{{ userInfo.role || '未设置角色' }}</div> -->
        </div>
        <div class="avatar" @click="toggleDropdown">
          <img src="../assets/avter.png" alt="用户头像" />
        </div>
      </div>
           <!-- Logo :draggable="false"-->
     
        <!-- 下拉菜单 -->
        <div class="dropdown-menu" v-show="showDropdown">
          <div class="dropdown-item" @click="handleModifyPassword">
            <i class="fas fa-key"></i>
            修改密码
          </div>
          <div class="dropdown-item" @click="handleCreateInvitation">
            <i class="fas fa-user-plus"></i>
            创建邀请
          </div>
          <div class="dropdown-item" @click="handleLogout">
            <i class="fas fa-sign-out-alt"></i>
            退出登录
          </div>
        </div>
      </div>
    </div>
    <div 
        class="collapse-left-button" 
        :class="{ 'menu-collapsed': isMenuCollapsed }"
        @click="toggleMenu"
      >
        <img 
          :src="isMenuCollapsed ? rightIcon : leftIcon" 
          alt="toggle" 
          class="collapse-icon"
        />
      </div>
    <div class="menu" :class="{ collapsed: isMenuCollapsed }">
      <!-- 添加收缩按钮 -->
      

   

      <!-- New Conversation 按钮 ,
            { active: currentConversationId === conversation.id }, -->
      <button class="new-conversation-btn" @click="addNewConversation">
        <img class="tab-icon" src="../assets/svg/plus.svg" alt="" />
        <span>New Conversation</span>
      </button>

      <!-- 会话列表 -->
      <div class="conversation-list">
        <div
          v-for="conversation in conversations.slice(0, 10)"
          :key="conversation.id"
          :class="[
            'conversation-item'
          ]"
          @click="switchConversation(conversation.id)"
        >
          <div class="conversation-title">{{ conversation.title }}</div>
          <div class="conversation-meta" v-if="conversation.sessionData">
            <span class="conversation-time">{{ formatTime(conversation.sessionData.user_message.created_at) }}</span>
            <span class="conversation-type">{{ getConversationType(conversation.sessionData.metadata.type) }}</span>
          </div>
        </div>
      </div>

      <!-- 添加模型配置和语音配置的容器 -->   <!-- <PermissionConfig/> -->
      <div class="config-container">
        <div class="config-header" style="border-bottom: 1px solid #e5e5e5;" @click="showSystemGraph">
            <img src="../assets/setting.png" alt="permission" class="config-icon" />
            <span style="color:#333333;">系统配置</span>
            <img  src="..//assets/svg/down.svg" alt="permission" style="margin-left:auto;" class="config-icon" />
          </div>
          
          <!-- 系统图抽屉 -->
          <a-drawer
            title="系统配置图"
            placement="right"
            :width="1000"
            :visible="systemGraphVisible"
            @close="closeSystemGraph"
          >
            <SystemGraph />
          </a-drawer>
         <div class="config-header" @click="goToRoleManagement">
            <img src="../assets/lock.png" alt="permission" class="config-icon" />
            <span style="color:#333333;">角色及权限</span>
             <img  src="..//assets/svg/down.svg" alt="permission" style="margin-left:auto;" class="config-icon" />
          </div>
          
        <!-- <div class="role-management-entry" @click="goToRoleManagement">
          <img src="../assets/lock.png" alt="role" class="config-icon" />
          <span>角色管理</span>
        </div> -->
        <KnowledgeConfig />
        <ModelConfig />
        <VoiceConfig />
      </div>
    </div>

    <div class="chat">
      <div class="chat-header">
          <h2>智能助手</h2>
          <div class="chat-status">
              <span class="status-indicator online"></span>
              <span>在线</span>
          </div>
      </div>
      <div v-if="messages.length === 0 && recommendedQuestions.length!== 0" class="welcome-section" style="margin-top:-220px">
        <!-- Do you want 部分 -->
        <div class="suggestion-section" style="margin-top:185px">

          <div class="cards-container">
            <div class="suggestion-card">
              <div class="suggestion-items" v-if="!inferenceModel">
                <!-- Combine both QA pairs and guides -->
                <div class="questions-list">
                  <div 
                    v-for="(question, index) in recommendedQuestions" 
                    :key="index"
                    class="suggestion-item"
                    @click="handleQuestionClick(question.example)"
                  >
                    {{ question.example }}
                  </div>
                </div>
              </div>
         
              <div class="suggestion-items" v-else >
                <div
                  v-for="(item, index) in recommendedQuestions"
                  :key="index"
                  class="suggestion-item"
                  @click="handleQuestionClick(item.example)"
                >
                  {{ item.example }}
                </div>
              </div>
                 
            </div>
          </div>
        </div>
      </div>
      <!-- 欢迎消息 -->
      <div v-if="messages.length === 0 && recommendedQuestions.length=== 0" class="welcome-section" style="margin-top:-220px">
        <!-- Do you want 部分 -->
        <div class="suggestion-section">
          <h3>嗨，我是你的智能助手</h3>

          <div class="cards-container">
            <div class="suggestion-card">
              <div class="card-header">
                <img
                  src="../assets/svg/hot-for-ux.svg"
                  alt="hot topics"
                  class="tab-icon"
                />
                <h4 v-if="!inferenceModel">推荐问题</h4>
                 <h4 v-else>待处理问题</h4>
              </div>
              <p class="card-subtitle" v-if="!inferenceModel">为您精选的热门问题</p>
              <!-- <p class="card-subtitle" v-else>当前问题</p> -->
              <div class="suggestion-items" v-if="!inferenceModel">
                <!-- Combine both QA pairs and guides -->
                <div
                  v-for="(item, index) in [
                    ...currentQaPairs,
                    ...currentDesignGuides,
                  ]"
                  :key="index"
                  class="suggestion-item"
                  @click="handleQaClick(item)"
                >
                  {{ item.question }}
                </div>
              </div>
         
              <div class="suggestion-items" v-else >
                <div
                  v-for="(item, index) in recommendedQuestions"
                  :key="index"
                  class="suggestion-item"
                  @click="handleQuestionClick(item.example)"
                >
                  {{ item.example }}
                </div>
              </div>
                 
            </div>
            <!-- Hot Topics 卡片 --><!-- Design Guide 卡片 -->
            <!--  <div class="suggestion-card">
              <div class="card-header">
                <img
                  src="../assets/svg/hot-for-ux.svg"
                  alt="hot topics"
                  class="tab-icon"
                />
                <h4>知识库相关问题：</h4>
              </div>
              <p class="card-subtitle">我们可以这样向知识库提问</p>
              <div class="suggestion-items">
                <div
                  v-for="(qa, index) in currentQaPairs"
                  :key="index"
                  class="suggestion-item"
                  @click="handleQaClick(qa)"
                >
                  {{ qa.question }}
                </div>
              </div>
            </div>

            
            <div class="suggestion-card">
              <div class="card-header">
                <img
                  src="../assets/svg/read.svg"
                  alt="hot topics"
                  class="tab-icon"
                />
                <h4>网上热搜问答</h4>
              </div>
              <p class="card-subtitle">搜索网上的热门回答</p>
              <div class="suggestion-items">
                <div
                  v-for="(guide, index) in currentDesignGuides"
                  :key="index"
                  class="suggestion-item"
                  @click="handleQaClick(guide)"
                >
                  {{ guide.question }}
                </div>
              </div>
            </div> -->
          </div>
        </div>
      </div>
      
      <!-- 修改消息列表部分 -->
      <div v-if="messages.length !== 0" class="message-list" ref="messageList">
        <!-- 添加流式思考步骤显示 -->
        <div v-if="currentThinkingSteps && currentThinkingSteps.length > 0" class="thinking-steps-stream">
          <div v-for="(step, index) in currentThinkingSteps" 
               :key="index" 
               class="thinking-step-stream"
               :class="[step.type, {'fade-in': true}]">
            {{ step.displayContent !== undefined ? step.displayContent : step.content }}
            <div v-if="index === currentThinkingSteps.length - 1" class="typing-indicator">
              <span></span>
              <span></span>
              <span></span>
            </div>
          </div>
        </div>
        
        <div
          v-for="(message,index) in messages"
          :key="message.id"
          :class="[
            'message-item',
            message.role === 'user' ? 'user' : 'assistant',
          ]"
        >
          <div class="message-bubble">
            <div class="message-content">
              <!-- 添加thinking steps显示 -->
              <div v-if="message.thinkingSteps && message.thinkingSteps.length > 0" class="thinking-steps">
              <!--   <div class="thinking-steps-header">
                  <span class="thinking-title">🤔 思考过程</span>
                </div> :class="step.type"-->
                <div v-for="(step, index) in message.thinkingSteps" 
                     :key="index" 
                     class="thinking-step"
                     >
                  <div class="step-content">{{ step.displayContent !== undefined ? step.displayContent : step.content }}</div>
                 <!--  <div class="step-meta">
                    <span class="step-type">{{ getStepTypeName(step.type) }}</span>
                    <span class="step-confidence">置信度: {{ (step.confidence * 100).toFixed(0) }}%</span>
                  </div> -->
                </div>
              </div>
              <template v-if="message.role === 'user' && message.files">
                <div
                  v-for="file in message.files"
                  :key="file.name"
                  class="file-message"
                >
                  <!-- 图片文件显示 -->
                  <template v-if="isImageFile(file)">
                    <div class="image-preview">
                      <img :src="file.url" class="preview-image" />
                    </div>
                  </template>

                  <!-- 视频文件显示 -->
                  <template v-else-if="isVideoFile(file)">
                    <div class="video-preview">
                      <video
                        controls
                        class="preview-video"
                        :src="file.url"
                        preload="metadata"
                      >
                        Your browser does not support the video tag.
                      </video>
                    </div>
                  </template>

                  <!-- 文档文件显示 -->
                  <template v-else>
                    <div class="file-info-display">
                      <img :src="getFileIcon(file)" class="file-type-icon" />
                      <div class="file-details">
                        <span class="file-name" :title="file.name">{{
                          file.name
                        }}</span>
                        <span class="file-size">{{ file.size }}</span>
                      </div>
                    </div>
                  </template>
                </div>
              </template>
              <div
                class="message-text"
                v-if="message.role === 'assistant'"
                v-html="renderMarkdown(message.displayContent)"
              ></div>
              <div v-else>{{ message.content }}</div>
              
              <!-- 知识源显示区域 -->
              <div v-if="message.role === 'assistant' && message.knowledgeSources && message.knowledgeSources.length > 0" class="knowledge-sources">
                <div class="knowledge-sources-header">
                  <DatabaseOutlined />
                  <span>知识来源</span>
                </div>
                <div class="knowledge-sources-list">
                  
                  <div 
                    v-for="(source, sourceIndex) in message.knowledgeSources" 
                    :key="sourceIndex"
                    class="knowledge-source-group"
                  >
                    
                      <div class="knowledge-source-items">
                        <div 
                          class="knowledge-source-item"
                          @click="handleKnowledgeSourceClick(source)"
                        >
                          <div class="knowledge-source-content">
                            <div class="knowledge-source-title" @click.stop="previewDocument(source)">
                              {{ source.file_name }}
                            </div>
                            <div class="knowledge-source-text" v-if="source.content">{{ source.content }}</div>
                           <!--  <div class="knowledge-source-meta">
                              <span class="knowledge-source-doc">文档ID: {{ source.doc_id }}</span>
                              <span class="knowledge-source-score" v-if="source.rerank_score">相关度: {{ (source.rerank_score * 100).toFixed(1) }}%</span>
                            </div> -->
                          </div>
                        </div>
                    </div>
                  </div>
                </div>
              </div>
            <div v-if="message.analysis_result" style="background-color: #f5f5f5; padding: 12px; border-radius: 8px; margin: 8px 0;">
                <div v-for="value in message.analysis_result.insights" style="margin-bottom: 6px; border-bottom: 1px dashed #e5e5e5;">
                  {{ value.message }}
                </div>
                <div v-for="value in message.analysis_result.issues" style="margin-bottom: 6px; border-bottom: 1px dashed #e5e5e5;">
                  {{ value.message }}
                </div>
                <div v-for="value in message.analysis_result.recommendations" style="margin-bottom: 6px; border-bottom: 1px dashed #e5e5e5;">
                  {{ value.description }}
                </div>
                <div v-for="value in message.automation_plan.steps" style="margin-bottom: 6px; ">
                <a href="#" @click="handleStepClick(value)" style="color: #0066cc; text-decoration: none;"> {{ value.description }}</a>
                </div>
              </div>

              <!-- 音频控制按钮 -->
              <div
                v-if="message.role === 'assistant'"
                class="audio-controls"
              >
                <button class="audio-btn" @click="handleAudioClick(message)">
                  <!-- 只在当前消息正在播放时显示波形动画 -->
                  <div
                    v-if="currentPlayingId === message.id"
                    class="wave-animation"
                  >
                    <span class="wave-bar"></span>
                    <span class="wave-bar"></span>
                    <span class="wave-bar"></span>
                    <span class="wave-bar"></span>
                  </div>
                  <!-- 其他情况显示播放图标 -->
                  <img v-else :src="playIcon" alt="播放" class="audio-icon" />
                </button>
              </div>
            </div>
          </div>
          <!-- 推荐问题组件 -->
           
            <div style="width: 80%;" v-if=" index === messages.length - 1 && message.role === 'assistant' &&recommended" class="recommended-questions">
               <div class="questions-list">
                  <div 
                    v-for="(question, index) in recommendedQuestions" 
                    :key="index"
                    class="question-item"
                    @click="handleQuestionClick(question.example)"
                  >
                    {{ question.example }}
                  </div>
                </div>
            </div>
              <div style="width: 80%;" v-if="message.role === 'assistant' && message.showRecommendedQuestions" class="recommended-questions">
                <div class="questions-header">
                  <!-- <img src="../assets/svg/hot-for-ux.svg" alt="推荐" class="hot-icon" /> -->
                  
                  <!-- <div class="questions-subtitle">为您精选的热门问题</div> -->
                </div>
                <div class="questions-list">
                  <div 
                    v-for="(question, index) in recommendedQuestions" 
                    :key="index"
                    class="question-item"
                    @click="handleQuestionClick(question.example)"
                  >
                    {{ question.example }}
                  </div>
                </div>
              </div>
        </div>
      </div>

      <!-- 输入框 -->
      <div class="input-container">
        <!-- 搜索开关组 -->
        <div class="search-toggles" :class="{ 'compact': isCompact }">

          <div class="left_item" style="display: flex;">
            <div class="search-toggle-item" style="width:33%;">
            <div class="toggle-content">
              <GlobalOutlined />
              <span class="toggle-text" >互联网</span><!-- v-show="!isCompact" -->
              <div class="toggle-switch">
                <input
                  type="checkbox"
                  id="webSearchToggle"
                  v-model="enableWebSearch"
                  @change="handleWebSearchToggle"
                  :disabled="attachedFiles.length > 0"
                  class="toggle-input"
                />
                <label
                  for="webSearchToggle"
                  class="toggle-label"
                  :class="{ disabled: attachedFiles.length > 0 }"
                >
                  <span class="toggle-slider"></span>
                </label>
              </div>
            </div>
          </div>
          
          <div class="search-toggle-item" style="width:33%;">
            <div class="toggle-content">
              <DatabaseOutlined />
              <span class="toggle-text" >知识库</span><!-- v-show="!isCompact" -->
              <div class="toggle-switch">
                <input
                  type="checkbox"
                  id="knowledgeSearchToggle"
                  v-model="enableKnowledgeSearch"
                  @change="handleKnowledgeToggle"
                  class="toggle-input"
                />
                <label
                  for="knowledgeSearchToggle"
                  class="toggle-label"
                >
                  <span class="toggle-slider"></span>
                </label>
              </div>
            </div>
          </div>
          <div class="search-toggle-item" style="width:33%;">
            <div class="toggle-content">
              <DatabaseOutlined />
              <span class="toggle-text" >智能体</span><!-- v-show="!isCompact" -->
              <div class="toggle-switch">
                <input
                  type="checkbox"
                  id="inferenceModelId"
                  v-model="inferenceModel"
                  
                  class="toggle-input"
                />
                <label
                  for="inferenceModelId"
                  class="toggle-label"
                >
                  <span class="toggle-slider"></span>
                </label>
              </div>
            </div>
          </div>
          </div>

          

          <div class="search-toggle-item">
            <div class="toggle-content">
              <!-- <SelectOutlined /> -->
              <!-- <span class="toggle-text">模型选择</span> -->
              <select 
                class="model-select" 
                :value="selectedModel"
                @change="handleModelChange($event.target.value)"
                :disabled="isLoadingModels"
              >
                <option v-if="isLoadingModels" value="">加载中...</option>
                <option v-else-if="models.length === 0" value="">无可用模型</option>
                <option 
                  v-for="model in models" 
                  :key="model.id" 
                  :value="model.id"
                >
                  {{ model.name }}
                </option>
              </select>
            </div>
          </div>

        </div>
        <!-- 添加附件面板 -->
        <div v-if="showAttachments" class="attachments-panel">
          <div class="panel-content">
            <div class="attachments-header">
              <span>Attachments</span>
              <button class="close-btn" @click="toggleAttachments">
                <img src="../assets/svg/close.svg" alt="" />
              </button>
            </div>
            <div
              v-if="attachedFiles.length === 0"
              style="display: flex; justify-content: center"
            >
              <div
                class="upload-area"
                :class="{ 'has-files': attachedFiles.length > 0 }"
                @click="triggerFileInput"
                @drop.prevent="handleFileDrop"
                @dragover.prevent
                @dragenter.prevent
              >
                <!-- 移除条件判断，让整个区域始终可点击 -->
                <template v-if="isUploading">
                  <div class="upload-loading">
                    <div class="loading-spinner"></div>
                    <div class="upload-text">Uploading...</div>
                  </div>
                </template>
                <template v-else>
                  <img
                    src="../assets/svg/upload.svg"
                    alt="upload"
                    class="upload-icon"
                  />
                  <div class="upload-text">Upload files</div>
                  <div class="upload-hint">
                    Click or drag files to this area to upload
                  </div>
                </template>
                <input
                  type="file"
                  ref="fileInput"
                  style="display: none"
                  @change="handleFileUpload"
                  multiple
                />
              </div>
            </div>
            <!-- 上传内容列表 -->
            <div v-if="attachedFiles.length !== 0">
              <div class="file-list">
                <div
                  v-for="file in attachedFiles"
                  :key="file.name"
                  class="file-item"
                  :class="{ 'is-image': isImageFile(file) }"
                >
                  <div :class="isImageFile(file) ? 'file-wrapper' : ''">
                    <!-- 添加文件 loading 状态 -->
                    <div v-if="file.isUploading" class="file-loading">
                      <div class="loading-spinner"></div>
                    </div>
                    <!-- 其他文件显示逻辑保持不变 -->
                    <img
                      v-else-if="isImageFile(file)"
                      :src="file.url"
                      alt="file"
                      class="file-icon"
                    />
                    <video
                      v-else-if="isVideoFile(file)"
                      :src="file.url"
                      class="file-icon"
                      preload="metadata"
                    >
                      Your browser does not support the video tag.
                    </video>
                    <img
                      v-else
                      :src="getFileIcon(file)"
                      alt="file"
                      :class="
                        isImageFile(file) || isVideoFile(file)
                          ? 'file-icon'
                          : ''
                      "
                    />
                    <button
                      class="remove-btn"
                      @click.stop="removeFile(file)"
                      v-if="!file.isUploading"
                    >
                      ×
                    </button>
                  </div>
                  <div class="file-info" v-if="!isImageFile(file)">
                    <span class="file-name">{{ file.name }}</span>
                    <span class="file-size">{{ file.sizeFormatted }}</span>
                  </div>
                </div>
                <button class="add-more-btn" @click.stop="triggerFileInput">
                  <img src="../assets/svg/plus.svg" alt="add" />
                </button>
              </div>

              <input
                type="file"
                ref="fileInput"
                style="display: none"
                @change="handleFileUpload"
                multiple
              />
            </div>
            <!--   <div v-if="attachedFiles.length" class="attached-files">
              <div
                v-for="file in attachedFiles"
                :key="file.name"
                class="file-item"
              >
                <FileOutlined />
                <span>{{ file.name }}</span>
                <button class="remove-btn" @click="removeFile(file)">
                </button>
              </div>
            </div> -->
          </div>
        </div>
        <!-- 输入框部分 -->
        <div class="input-wrapper">
          <button class="attachment-btn" @click="toggleAttachments">
            <img
              src="../assets/svg/attachment.svg"
              alt="attachment"
              class="tab-icon"
            />
          </button>
          <input
            type="text"
            class="message-input"
            v-model="inputContent"
            @keyup.enter="sendMessage"
            placeholder="Type a message..."
          /><!--  @input="handleInputChange"  :disabled="(!inputContent && attachedFiles.length === 0)"-->
          <button
            class="send-btn"
            @click="sendMessage"
           
          >
            <template v-if="isTyping">
              <span class="loading-btn">
                <span class="loading-square"></span>
              </span>
            </template>
            <template v-else>
              <img src="../assets/svg/up.svg" alt="send" />
            </template>
          </button>
        </div>
      </div>

       <!-- 浮动操作按钮 (FAB) -->
       <div class="fab" :class="{ 'open': isFabOpen }" @click="toggleFab">
        <!-- 初始状态：显示三个点 -->
        <div class="fab-dots" v-if="!isFabOpen">
          <span></span>
          <span></span>
          <span></span>
        </div>
        
        <!-- 展开状态：显示三个选项按钮 -->
       <div class="option reply" :class="{ 'open': isFabOpen }" @click.stop="handleReply">
          <div class="option-content option-content--below">
            <CreditCardOutlined class="option-icon" />
            <span class="option-label">查看</span>
          </div>
        </div>

        <div class="option love" :class="{ 'open': isFabOpen }" @click.stop="handleStepClick">
          <div class="option-content option-content--below">
            <AuditOutlined class="option-icon" />
            <span class="option-label">任务</span>
          </div>
        </div>

        <div class="option delete" :class="{ 'open': isFabOpen }" @click.stop="handleDelete">
          <div class="option-content option-content--below">
            <ProfileOutlined class="option-icon" />
            <span class="option-label">命令集</span>
          </div>
        </div>
        
        <!-- 关闭按钮：只在展开状态显示 -->
        <div class="close" v-if="isFabOpen" @click.stop="toggleFab">
          <i class="material-icons">close</i>
        </div>
      </div>
    </div>

    <div  
    v-if="!isMobile"
      class="right_menu" 
      :class="{ 
        collapsed: !isRightMenuVisible
      }" 
      :style="{ width: rightMenuWidth + 'px' }"
    >
    <div v-if="inferenceModel">
        <div style="height: 91vh;overflow: auto;" class="file-list">
          <!-- <div class="panel-header">
                <h3>查询结果</h3>
                <button class="panel-toggle">
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <polyline points="6,9 12,15 18,9" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                    </svg>
                </button>
            </div> -->
          <!-- 步骤显示区域 -->
          <div id="stepsContainer" v-show="showSteps" class="steps-container">
            <h3 class="steps-title" style="margin-left:10px">处理步骤</h3>
            <div id="stepsList" style="margin-left:25px"></div>
          </div>
          <!-- 结果显示区域 -->
          <div id="resultContent" v-html="formatted_data"></div>
        </div>
      </div>
    <!-- 修改收缩按钮的位置和样式 -->
    <!-- <div 
      class="collapse-button" 
      :class="{ 
        'menu-expanded': !isRightMenuCollapsed,
        'menu-collapsed': isRightMenuCollapsed 
      }"
      @click="toggleRightMenu"
    >
      <img
        :src="isRightMenuCollapsed ? leftIcon : rightIcon"
        alt="toggle"
        class="collapse-icon"
      />
    </div> -->
      <!-- 添加拖动条 -->
      <div 
        class="resize-handle"
        @mousedown="startResize"
        @touchstart="startResize"
      ></div>
      
      <div class="right-menu-content">
        <!-- 添加 Tab 切换 -->
       <!--  <div class="right-menu-tabs">
          <div 
            class="tab-item" 
            :class="{ active: activeTab === 'search' }"
            @click="activeTab = 'search'"
          >
            <SearchOutlined />
            <span>搜索结果</span>
          </div>
          <div 
            class="tab-item" 
            :class="{ active: activeTab === 'preview' }"
            @click="activeTab = 'preview'"
          >
            <FileOutlined />
            <span>文档预览</span>
          </div>
          <div 
            class="tab-item" 
            :class="{ active: activeTab === 'knowledge' }"
            @click="activeTab = 'knowledge'"
          >
            <DatabaseOutlined />
            <span>知识库</span>
          </div>
          <div 
            class="tab-item" 
            :class="{ active: activeTab === 'map' }"
            @click="activeTab = 'map'"
          >
            <GlobalOutlined />
            <span>地图</span>
          </div>
        </div> -->
   
        <!-- 搜索面板 -->
        <div v-show="activeTab === 'search'" class="panel-container">
          <!-- <div class="search-header">
            <span>搜索结果</span>
            <div class="web-search-toggle">
              <input
                type="checkbox"
                id="searchToggle"
                v-model="enableWebSearch"
                class="toggle-input"
              />
              <label for="searchToggle" class="toggle-label">
                {{ enableWebSearch ? '搜索已开启' : '搜索已关闭' }}
              </label>
            </div>
          </div> -->
          <!-- v-if="enableWebSearch" -->
          <SearchResults
            :searchResults="searchResults"
            :loading="isSearchLoading"
            :total="searchTotal"
            :enableWebSearch="enableWebSearch"
            :message="currentSearchQuery"
            @update:enableWebSearch="handleSearchToggle"
          />
        </div>

        <!-- 文档预览面板 -->
        <div v-show="activeTab === 'preview'" class="panel-container">
          <div class="preview-header">
            <span>文档预览</span>
          </div>
          <div class="document-preview">
            <div class="preview-container">
              <!-- 文档列表 -->
              <!-- <div class="document-list">
                <div v-if="attachedFiles.length === 0" class="empty-state">
                  <FileOutlined class="empty-icon" />
                  <p>暂无文档</p>
                </div>
                <div v-else v-for="doc in attachedFiles" :key="doc.name" class="document-item" 
                  :class="{ 'active': currentDoc?.name === doc.name }"
                  @click="handleDocClick(doc)">
                  <div class="document-info">
                    <div class="doc-icon">
                      <img 
                        v-if="isImageFile(doc)"
                        :src="doc.url" 
                        class="preview-thumbnail"
                        alt="preview"
                      />
                      <video
                        v-else-if="isVideoFile(doc)"
                        :src="doc.url"
                        class="preview-thumbnail"
                        preload="metadata"
                      />
                      <img 
                        v-else 
                        :src="getFileIcon(doc)" 
                        alt="file"
                        class="file-icon"
                      />
                    </div>
                    <div class="info">
                      <div class="name" :title="doc.name">{{ doc.name }}</div>
                      <div class="size">{{ doc.sizeFormatted || formatFileSize(doc.size) }}</div>
                    </div>
                  </div>
                  <div class="actions">
                    <button class="action-btn" @click.stop="handleDownload(doc)" title="下载">
                      <DownloadOutlined />
                    </button>
                  </div>
                </div>
              </div> -->

              <!-- 直接预览区域 -->
              <div v-if="currentDoc" class="direct-preview">
                <div class="preview-header">
                  <span>{{ currentDoc.name }}</span>
                  <button class="close-btn" @click="closePreview">
                    <CloseOutlined />
                  </button>
                </div>
                <div class="preview-body">
                  <!-- 图片预览 -->
                  <img 
                    v-if="isImageFile(currentDoc)"
                    :src="currentDoc.url" 
                    class="preview-image"
                    alt="preview"
                  />
                  <!-- 视频预览 -->
                  <video
                    v-else-if="isVideoFile(currentDoc)"
                    :src="currentDoc.url"
                    controls
                    class="preview-video"
                  />
                  <!-- Word文档预览 -->
                  <div v-else-if="isWordFile(currentDoc)">
                    <vue-office-docx
                      :src="currentDoc.url"
                      class="doc-preview"
                      @rendered="handleRendered"
                      @error="handleError"
                    />      
                  </div>
                  <!-- Excel文档预览 -->
                  <div v-else-if="isExcelFile(currentDoc)">
                    <vue-office-excel
                      :options="excelOptions"
                      @rendered="handleRendered"
                      @error="handleExcelError"
                      :src="currentDoc.url"
                      class="doc-preview"
                    />
                  </div>
                  <!-- PDF预览-->
                  <iframe v-else-if="isPdfFile(currentDoc)" :src="currentDoc.url" style="width: 100%; height: 100%;" frameborder="0"></iframe>
                  <!-- 其他文件预览 -->
                  <div v-else class="file-preview">
                    <FileOutlined class="large-icon" />
                    <p>该文件类型暂不支持预览</p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 添加知识库结果面板 -->
        <div v-show="activeTab === 'knowledge'" class="panel-container">
          <!-- <div class="search-header">
            <span>知识库搜索结果</span>
          </div> -->
          <!-- v-if="enableKnowledgeSearch" -->
          <KnowledgeResults
            :searchResults="knowledgeResults"
            :loading="isKnowledgeLoading"
            :total="knowledgeTotal"
            :message="currentSearchQuery"
          />
        </div>
        <div  v-show="activeTab === 'map'" class="panel-container">
            <!-- 地图显示区域 -->
            <AmapDisplay 
            v-if="mapDisplay"
            :mapDisplay="mapDisplay"
            :center="mapCenter"
            :polylines="mapPolylines"
          />
        </div>
      </div>

      
    </div>
  </div>
</template>

<script setup>
import SystemGraph from '../components/SystemGraph/index.vue';

import { ref, reactive, nextTick, onUnmounted, onMounted, computed, watch } from "vue";
import {
  PlusOutlined,
  FireOutlined,
  ReadOutlined,
  HeartOutlined,
  SmileOutlined,
  CommentOutlined,
  CloudUploadOutlined,
  PaperClipOutlined,
  ShareAltOutlined,
  EllipsisOutlined,
  CloseOutlined,
  FileOutlined,
  ArrowUpOutlined,
  UploadOutlined,
  FileSearchOutlined,
  GlobalOutlined,
  DatabaseOutlined,
  FolderOutlined,
  SelectOutlined,
  DownloadOutlined,
  CreditCardOutlined,
  AuditOutlined,
  ProfileOutlined,
  SearchOutlined
} from "@ant-design/icons-vue";
import leftIcon from "../assets/svg/left.svg";
import rightIcon from "../assets/svg/right.svg";
import plusIcon from "../assets/svg/plus.svg";
import hotForUxIcon from "../assets/svg/hot-for-ux.svg";
import readIcon from "../assets/svg/read.svg";
import attachmentIcon from "../assets/svg/attachment.svg";
import uploadIcon from "../assets/svg/upload.svg";
import closeIcon from "../assets/svg/close.svg";
import upIcon from "../assets/svg/up.svg";
import wordIcon from "../assets/svg/word.svg";
import pauseIcon from "../assets/svg/pause.svg";
import playIcon from "../assets/svg/play.svg";
import axios from "axios";
import { useStore } from "vuex";
import MarkdownIt from "markdown-it";
import ModelConfig from "../components/ModelConfig/index.vue";
import SearchResults from "../components/SearchResults/index.vue";
import VoiceConfig from "../components/VoiceConfig/index.vue";
import KnowledgeConfig from "../components/KnowledgeConfig/index.vue";
import PermissionConfig from "../components/PermissionConfig/index.vue";
import ExportButton from "../components/ExportButton/index.vue";
import dayjs from 'dayjs';
import DocumentPreview from "../components/DocumentPreview/index.vue";
import KnowledgeResults from "../components/KnowledgeResults/index.vue";
import ChangePasswordDialog from '../components/ChangePasswordDialog.vue'
import AmapDisplay from '../components/AmapDisplay/index.vue';
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue';
import VueOfficeDocx from '@vue-office/docx';
import VueOfficeExcel from '@vue-office/excel';

// import { getRecommendedQuestions } from '../api/report';
/* import '@vue-office/docx/lib/index.css';
import '@vue-office/excel/lib/index.css'; */
// 初始化 markdown-it
const md = new MarkdownIt({
  html: true,
  linkify: true,
  typographer: true,
});

// 响应式状态
const headerOpen = ref(false);
const inputContent = ref("");
const showAttachments = ref(false);
const isRightMenuCollapsed = ref(false);
const fileInput = ref(null);
const attachedFiles = ref([]);
const messages = ref([]);
const isLoading = ref(false);
const currentConversationId = ref(1);
const conversationCounter = ref(1);
const messageList = ref(null);
const store = useStore();
const router = useRouter()

const goToRoleManagement = () => {
  router.push('/role');
};

// 系统图抽屉控制
const systemGraphVisible = ref(false);

const showSystemGraph = () => {
  systemGraphVisible.value = true;
};

const closeSystemGraph = () => {
  systemGraphVisible.value = false;
};

// 保留原有的跳转函数以备用
const goToSystemGraph = () => {
  router.push('/system-graph');
};
// 会话数据
const conversations = ref([]);

// 添加打字效果相关的状态
const typingSpeed = 50; // 打字速度（毫秒/字符）
const isTyping = ref(false);
const typingTimeout = ref(null); // 添加打字超时引用

// 逐字输出一个文本到指定对象的 display 字段
const typeTextTo = (target, fullTextKey = 'content', displayKey = 'displayContent', minDelay = 15, maxDelay = 35) => {
  if (!target) return Promise.resolve();
  const full = target[fullTextKey] || '';
  target[displayKey] = '';
  let index = 0;
  return new Promise((resolve) => {
    const step = () => {
      if (index >= full.length) return resolve();
      const ch = full[index];
      target[displayKey] += ch;
      index += 1;
      const delay = /[\u4e00-\u9fa5]/.test(ch) ? maxDelay : minDelay;
      // 等待 DOM 刷新并在下一帧再调度下一个字符，确保逐字可见
      nextTick(() => {
        requestAnimationFrame(() => {
          setTimeout(step, delay);
        });
      });
    };
    step();
  });
};

// 依次为 message.thinkingSteps 中从 startIndex 开始的各步逐字输出
const animateThinkingStepsForMessage = async (message, startIndex = 0) => {
  try {
    console.log('message',startIndex)
    if (!message || !Array.isArray(message.thinkingSteps)) return;
    for (let i = startIndex; i < message.thinkingSteps.length; i += 1) {
      console.log('message.thinkingSteps',message.thinkingSteps)
      const step = message.thinkingSteps[i];
      if (!step.displayContent) step.displayContent = '';
      await typeTextTo(step);
    }
  } catch (err) {
    console.error('animateThinkingStepsForMessage error:', err);
    // 回退到直接展示
    for (let i = startIndex; i < (message.thinkingSteps?.length || 0); i += 1) {
      const step = message.thinkingSteps[i];
      if (step) step.displayContent = step.content || '';
    }
  }
};

// 添加音频播放相关的响应式变量
const audioPlayer = ref(null);
const isPlaying = ref(false);

// 添加当前播放消息的 ID
const currentPlayingId = ref(null);
const currentAudioSource = ref(null);

// 添加新的响应式变量
const isUploading = ref(false);

// 添加新的响应式状态
const documentSummary = ref(null);
const isLoadingSummary = ref(false);
const currentQaPairs = ref([]);
const currentDesignGuides = ref([]);
let rotationInterval = null;

// 添加新的响应式状态
const searchResults = ref([]);
const isSearchLoading = ref(false);
const searchTotal = ref(0);

// 添加互联网搜索开关状态
const enableWebSearch = ref(false);

// 添加新的响应式变量
const isMenuCollapsed = ref(false);

// 添加移动端检测
const isMobile = ref(false);

//知识库搜索
const enableKnowledgeSearch = ref(false);

// FAB 浮动操作按钮状态
const isFabOpen = ref(false);
const knowledgeResults = ref([]);
const knowledgeTotal = ref(0);
const isKnowledgeLoading = ref(false);
const formatted_data = ref('');
const showSteps = ref(false);
const steps = ref([]);

// 地图相关状态
const mapDisplay = ref(false);
const mapCenter = ref({ });
const mapPolylines = ref([]);

// 进度条弹窗相关状态
const showProgressModal = ref(false);
const progressList = ref([]);

// 推荐问题相关状态
const recommendedQuestions = ref([]);
const showRecommendedQuestions = ref(false);

// SSE消息处理函数
const handleSSEMessage = (event, data) => {
  // 立即处理每个事件
  switch (event) {
    case 'html_start':
      formatted_data.value = '';
      break;
      
    case 'html_chunk':
      if (data && typeof data.html === 'string') {
        // 直接追加新内容到现有内容
        formatted_data.value += data.html;
        // 确保滚动到最新内容
        nextTick(() => {
          const resultContent = document.getElementById('resultContent');
          if (resultContent) {
            resultContent.scrollTop = resultContent.scrollHeight;
          }
        });
      }
      break;
      
    case 'html_end':
      // 完成渲染，可以在这里添加完成的标记
      break;

    case 'init_steps':
      showSteps.value = true;
      // 立即初始化步骤
      initializeSteps(data.steps);
      break;
      
    case 'step_update':
      // 立即更新步骤状态
      updateStepElement(data.step_id, data.status, data.details, data.progress);
      break;
    case 'final_summary':
     /*  // 处理地图数据
      if (data.map_display) {
        mapDisplay.value = true;
        if (data.center) {
          mapCenter.value = data.center;
        }
      } */
      break;
    case 'stream_end':
      showSteps.value = false;
      /* // 立即初始化步骤
      initializeSteps(data.steps); */
      break;
      
    case 'error':
      console.error('SSE错误:', data.message);
    /*   ElMessage.error(data.message || '处理过程中出现错误'); */
      break;
  }
};

// 初始化步骤
const initializeSteps = (stepsData) => {
  const stepsList = document.getElementById('stepsList');
  if (!stepsList) return;
  
  stepsList.innerHTML = '';
  steps.value = stepsData;
  
  stepsData.forEach(step => {
    stepsList.appendChild(createStepElement(step));
  });
};

// 创建步骤元素
const createStepElement = (step) => {
  const stepEl = document.createElement('div');
  stepEl.className = `step ${step.status}`;
  stepEl.id = `step-${step.step_id}`;
 /*  <div class="step-icon">${getStepIcon(step.status)}</div> */
  stepEl.innerHTML = `
    <div class="step-header">
      <div class="step-header-content">
         <div class="step-icon" style="display: none;">${getStepIcon(step.status)}</div> 
        <div class="step-name">${step.name || step.step_id}</div>
      </div>
    </div>
    <div class="step-details" style="margin-bottom:15px;">${step.details || ''}</div>
    <div class="progress-bar">
      <div class="progress-fill" style="width: ${step.progress || 0}%"></div>
    </div>
  `;
  
  return stepEl;
};

// 更新步骤元素
const updateStepElement = (stepId, status, details, progress) => {
  const stepEl = document.getElementById(`step-${stepId}`);
  if (!stepEl) return;
  
  stepEl.className = `step ${status}`;
  stepEl.querySelector('.step-icon').textContent = getStepIcon(status);
  
  if (details) {
    stepEl.querySelector('.step-details').textContent = details;
  }
  
  if (progress !== undefined) {
    stepEl.querySelector('.progress-fill').style.width = `${progress}%`;
  }
};

// 获取步骤图标
const getStepIcon = (status) => {
  switch (status) {
    case 'pending': return '⏳';
    case 'running': return '🔄';
    case 'completed': return '✅';
    case 'error': return '❌';
    default: return '⏳';
  }
};

// 智能体
const inferenceModel = ref(false);

// 检测设备类型
const checkMobile = () => {
  isMobile.value = window.innerWidth <= 768;
  if (isMobile.value) {
    isRightMenuCollapsed.value = true; // 在移动设备下自动收起右侧菜单
    isMenuCollapsed.value = true; 
  }else{
    isRightMenuCollapsed.value = false;
    isMenuCollapsed.value = false;
  }
};

const logo=ref(null);
/* 获取租户信息 */
const init=async()=>{
  const response = await axios.get(`${import.meta.env.VITE_BASE_AI_API}/api/merchant/info`, {
    headers: {
      'Authorization': `JWT ${localStorage.getItem('token')}`
    }
  });
  
  logo.value=response.data.data.logo_url;
  console.log(logo.value);
}

// 添加窗口大小改变事件监听
onMounted(() => {
  checkMobile(); // 初始检查
  window.addEventListener('resize', checkMobile);
  fetchChatHistory(); // 获取聊天历史
  init()
});

const showDropdown = ref(false);
const toggleDropdown = () => {
  console.log(showDropdown.value);
  showDropdown.value = !showDropdown.value;
};

// 添加遮罩层点击处理
const handleOverlayClick = () => {
  if (isMobile.value) {
    isMenuCollapsed.value = true;
    isRightMenuCollapsed.value = true;
    document.body.style.overflow = 'auto';
  }
};

// 修改菜单切换逻辑
const toggleMenu = () => {
  isMenuCollapsed.value = !isMenuCollapsed.value;
  if (isMobile.value) {
    document.body.style.overflow = isMenuCollapsed.value ? 'auto' : 'hidden';
    if (!isMenuCollapsed.value) {
      isRightMenuCollapsed.value = true; // 确保右侧菜单关闭
    }
  }
  
  // 更新聊天区域的位置
  if (document.querySelector('.chat')) {
    document.querySelector('.chat').style.left = isMenuCollapsed.value ? '460px' : '260px';
  }
};

// 修改右侧菜单切换逻辑
const toggleRightMenu = () => {
  isRightMenuCollapsed.value = false;
  
  if (isRightMenuCollapsed.value) {
    // 收起菜单时的处理
    if (document.querySelector('.chat')) {
      document.querySelector('.chat').style.right = '0';
    }
  } else {
    enableWebSearch.value = true;
    // 展开菜单时的处理
    if (document.querySelector('.chat')) {
      document.querySelector('.chat').style.right = `${rightMenuWidth.value}px`;
    }
  }

  if (isMobile.value) {
    document.body.style.overflow = isRightMenuCollapsed.value ? 'auto' : 'hidden';
    if (!isRightMenuCollapsed.value) {
      isMenuCollapsed.value = true;
    }
  }
};

// 修改自动展开右侧菜单的方法
const expandRightMenu = () => {
  isRightMenuCollapsed.value = false;
  if (document.querySelector('.chat')) {
    document.querySelector('.chat').style.right = `${rightMenuWidth.value}px`;
  }
};

// 修改获取文档摘要的方法
const fetchDocumentSummary = async () => {
  isLoadingSummary.value = true;
  try {
    const response = await axios.get(
      `${import.meta.env.VITE_BASE_AI_API}/api/document/summary?limit=2`,
      {
        headers: {
          'Authorization': `JWT ${localStorage.getItem('token')}`
        }
      }
    );
    console.log("API Response:", response.data);

    if (response.data.status === 200) {
      documentSummary.value = response.data.data;
      console.log("Document Summary:", documentSummary.value);
      startRotation();
    }
  } catch (error) {
    console.error("获取文档摘要失败:", error);
  } finally {
    isLoadingSummary.value = false;
  }
};

// 获取聊天历史
const fetchChatHistory = async () => {
  try {
    // 从个人信息中获取 user_id 和 merchant_id
    const userInfo = JSON.parse(localStorage.getItem('userInfo'));
    const userId = userInfo.user_id || userInfo.id || 1; // 备用默认值
    const merchantId = userInfo.merchant?.merchant_id || 1;
    
    // 使用 FormData 传参
    const formData = new FormData();
    formData.append('user_id', userId);
    formData.append('merchant_id', merchantId);
    
    const response = await axios.get(
      `${import.meta.env.VITE_BASE_AI_API}/api/chat/history?merchant_id=${merchantId}&user_id=${userId}&full_content=1`,
      {
        headers: {
          'Authorization': `JWT ${localStorage.getItem('token')}`
        }
      }
    );
    console.log("Chat History Response:", response.data);

    if (response.data.code === 2000) {
      // 将API返回的sessions数据转换为conversations格式
      conversations.value = response.data.data.sessions.map(session => ({
        id: session.session_id,
        title: session.user_message.content, // 使用用户消息内容作为标题
        messages: [],
        sessionData: session // 保存完整的session数据
      }));
      
      // 如果有会话数据，设置第一个为当前会话
      if (conversations.value.length > 0) {
        currentConversationId.value = conversations.value[0].id;
      }
    }
  } catch (error) {
    console.error("获取聊天历史失败:", error);
  }
};

// 格式化时间
const formatTime = (timeString) => {
  if (!timeString) return '';
  try {
    const date = new Date(timeString);
    const now = new Date();
    const diffInHours = (now - date) / (1000 * 60 * 60);
    
    if (diffInHours < 24) {
      return date.toLocaleTimeString('zh-CN', {year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' });
    } else if (diffInHours < 48) {
      return '昨天';
    } else {
      return date.toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' });
    }
  } catch (error) {
    return '';
  }
};

// 获取会话类型显示文本
const getConversationType = (type) => {
  const typeMap = {
    'chat': '对话',
    'document_chat': '文档对话',
    'streaming_demo': '演示'
  };
  return typeMap[type] || '对话';
};

// 处理知识源点击事件
const handleKnowledgeSourceClick = (item) => {
  // 可以在这里实现跳转到具体文档或显示更多详情
  console.log('点击知识源:', item);
  
  // 示例：可以打开一个新窗口显示文档详情
  if (item.doc_id) {
    // 这里可以根据实际需求实现跳转逻辑
    // 比如打开文档详情页面或显示文档内容
    ElMessage.info(`查看文档 ${item.doc_id} 的详细信息`);
  }
};

// 处理文档预览点击事件
const previewDocument = (source) => {
  console.log('预览文档:', source);
  
  if (source.minio_url) {
    // 使用新的文档预览页面
    const url = encodeURIComponent(source.minio_url);
    const title = encodeURIComponent(source.name || '文档预览');
    const previewUrl = `${window.location.origin}/#/document-preview?url=${url}&title=${title}`;
    
    // 在新窗口中打开文档预览页面
    window.open(previewUrl, '_blank');
  } else {
    ElMessage.warning('该文档暂无预览链接');
  }
};

// 处理特定URL的文档预览
const previewSpecificDocument = (url, title = '文档预览') => {
  console.log('预览特定文档:', url);
  
  if (url) {
    // 使用新的文档预览页面
    const encodedUrl = encodeURIComponent(url);
    const encodedTitle = encodeURIComponent(title);
    const previewUrl = `/document-preview?url=${encodedUrl}&title=${encodedTitle}`;
    
    // 在新窗口中打开文档预览页面
    window.open(previewUrl, '_blank');
  } else {
    ElMessage.warning('缺少文档链接');
  }
};

// 预览您提供的特定链接
const previewSprayPaintGuide = () => {
  console.log(window.location.origin)
};

// 处理步骤点击事件
const handleStepClick = (step) => {
  // 显示进度条弹窗
  showProgressModal.value = true;
  
  // 创建模拟任务数据
  const mockTasks = [
    {
      id: Date.now(),
      title: '数据分析任务',
      value: 0,
      status: '准备中...',
      subTasks: [
        { 
          title: '数据收集', 
          value: 0, 
          isActive: true,
          subSubTasks: [
            { title: '连接数据源', value: 0, isActive: true },
            { title: '验证数据格式', value: 0, isActive: false },
            { title: '下载数据文件', value: 0, isActive: false }
          ]
        },
        { 
          title: '数据清洗', 
          value: 0, 
          isActive: false,
          subSubTasks: [
            { title: '检测异常值', value: 0, isActive: false },
            { title: '处理缺失值', value: 0, isActive: false },
            { title: '数据标准化', value: 0, isActive: false },
            { title: '去重处理', value: 0, isActive: false }
          ]
        },
        { 
          title: '特征提取', 
          value: 0, 
          isActive: false,
          subSubTasks: [
            { title: '特征选择', value: 0, isActive: false },
            { title: '特征工程', value: 0, isActive: false },
            { title: '降维处理', value: 0, isActive: false }
          ]
        },
        { 
          title: '模型训练', 
          value: 0, 
          isActive: false,
          subSubTasks: [
            { title: '参数初始化', value: 0, isActive: false },
            { title: '训练迭代', value: 0, isActive: false },
            { title: '模型验证', value: 0, isActive: false },
            { title: '超参数调优', value: 0, isActive: false }
          ]
        },
        { 
          title: '结果验证', 
          value: 0, 
          isActive: false,
          subSubTasks: [
            { title: '交叉验证', value: 0, isActive: false },
            { title: '性能评估', value: 0, isActive: false },
            { title: '结果输出', value: 0, isActive: false }
          ]
        }
      ]
    },
    {
      id: Date.now() + 1,
      title: '报告生成任务',
      value: 0,
      status: '等待中...',
      subTasks: [
        { 
          title: '模板加载', 
          value: 0, 
          isActive: false,
          subSubTasks: [
            { title: '读取模板文件', value: 0, isActive: false },
            { title: '解析模板结构', value: 0, isActive: false },
            { title: '初始化变量', value: 0, isActive: false }
          ]
        },
        { 
          title: '数据填充', 
          value: 0, 
          isActive: false,
          subSubTasks: [
            { title: '获取分析结果', value: 0, isActive: false },
            { title: '格式化数据', value: 0, isActive: false },
            { title: '填充模板', value: 0, isActive: false }
          ]
        },
        { 
          title: '图表生成', 
          value: 0, 
          isActive: false,
          subSubTasks: [
            { title: '创建统计图表', value: 0, isActive: false },
            { title: '生成趋势图', value: 0, isActive: false },
            { title: '制作对比图', value: 0, isActive: false },
            { title: '优化图表样式', value: 0, isActive: false }
          ]
        },
        { 
          title: '格式化处理', 
          value: 0, 
          isActive: false,
          subSubTasks: [
            { title: '调整页面布局', value: 0, isActive: false },
            { title: '设置字体样式', value: 0, isActive: false },
            { title: '添加页眉页脚', value: 0, isActive: false }
          ]
        },
        { 
          title: '文件导出', 
          value: 0, 
          isActive: false,
          subSubTasks: [
            { title: '生成PDF文件', value: 0, isActive: false },
            { title: '创建Excel文件', value: 0, isActive: false },
            { title: '压缩文件包', value: 0, isActive: false }
          ]
        }
      ]
    },
    {
      id: Date.now() + 2,
      title: '系统优化任务',
      value: 0,
      status: '等待中...',
      subTasks: [
        { 
          title: '性能检测', 
          value: 0, 
          isActive: false,
          subSubTasks: [
            { title: 'CPU使用率检测', value: 0, isActive: false },
            { title: '内存占用分析', value: 0, isActive: false },
            { title: '磁盘IO监控', value: 0, isActive: false },
            { title: '网络延迟测试', value: 0, isActive: false }
          ]
        },
        { 
          title: '缓存清理', 
          value: 0, 
          isActive: false,
          subSubTasks: [
            { title: '清理临时文件', value: 0, isActive: false },
            { title: '清空浏览器缓存', value: 0, isActive: false },
            { title: '清理系统缓存', value: 0, isActive: false }
          ]
        },
        { 
          title: '数据库优化', 
          value: 0, 
          isActive: false,
          subSubTasks: [
            { title: '索引重建', value: 0, isActive: false },
            { title: '查询优化', value: 0, isActive: false },
            { title: '数据压缩', value: 0, isActive: false },
            { title: '备份清理', value: 0, isActive: false }
          ]
        },
        { 
          title: '内存整理', 
          value: 0, 
          isActive: false,
          subSubTasks: [
            { title: '垃圾回收', value: 0, isActive: false },
            { title: '内存碎片整理', value: 0, isActive: false },
            { title: '进程优化', value: 0, isActive: false }
          ]
        }
      ]
    }
  ];
  
  // 添加到进度列表
  progressList.value = mockTasks;
  
  // 开始模拟进度
  simulateProgress();
};

// 模拟复杂的三级进度处理
const simulateProgress = () => {
  let currentTaskIndex = 0;
  let currentSubTaskIndex = 0;
  let currentSubSubTaskIndex = 0;
  
  const progressInterval = setInterval(() => {
    if (currentTaskIndex >= progressList.value.length) {
      clearInterval(progressInterval);
      return;
    }
    
    const currentTask = progressList.value[currentTaskIndex];
    const currentSubTask = currentTask.subTasks[currentSubTaskIndex];
    
    if (!currentSubTask) return;
    
    const currentSubSubTask = currentSubTask.subSubTasks[currentSubSubTaskIndex];
    
    // 更新当前子子任务状态
    if (currentSubSubTask) {
      currentSubSubTask.isActive = true;
      currentSubSubTask.value = Math.min(currentSubSubTask.value + Math.random() * 20 + 10, 100);
      
      // 更新子任务进度
      const completedSubSubTasks = currentSubTask.subSubTasks.filter(subSub => subSub.value >= 100).length;
      const totalSubSubTasks = currentSubTask.subSubTasks.length;
      currentSubTask.value = Math.floor((completedSubSubTasks / totalSubSubTasks) * 100);
      
      // 更新主任务进度
      const completedSubTasks = currentTask.subTasks.filter(sub => sub.value >= 100).length;
      const totalSubTasks = currentTask.subTasks.length;
      currentTask.value = Math.floor((completedSubTasks / totalSubTasks) * 100);
      
      // 更新主任务状态
      if (currentTask.value === 0) {
        currentTask.status = '准备中...';
      } else if (currentTask.value < 100) {
        currentTask.status = `进行中... (${completedSubTasks}/${totalSubTasks})`;
      } else {
        currentTask.status = '已完成';
      }
      
      // 子子任务完成，移动到下一个
      if (currentSubSubTask.value >= 100) {
        currentSubSubTask.isActive = false;
        currentSubSubTaskIndex++;
        
        // 当前子任务的所有子子任务完成，移动到下一个子任务
        if (currentSubSubTaskIndex >= currentSubTask.subSubTasks.length) {
          currentSubTask.isActive = false;
          currentSubTaskIndex++;
          currentSubSubTaskIndex = 0;
          
          // 开始下一个子任务
          if (currentSubTaskIndex < currentTask.subTasks.length) {
            currentTask.subTasks[currentSubTaskIndex].isActive = true;
          } else {
            // 当前任务的所有子任务完成，移动到下一个主任务
            currentTaskIndex++;
            currentSubTaskIndex = 0;
            
            // 开始下一个任务
            if (currentTaskIndex < progressList.value.length) {
              progressList.value[currentTaskIndex].status = '准备中...';
              progressList.value[currentTaskIndex].subTasks[0].isActive = true;
            }
          }
        }
      }
    }
  }, 150);
};

// 获取进度图标
const getProgressIcon = (progress) => {
  if (progress.status === '错误') return '❌';
  if (progress.value >= 100) return '✅';
  if (progress.value > 0) return '🔄';
  return '⏳';
};

// 获取子进度图标
const getSubProgressIcon = (subTask) => {
  if (subTask.value >= 100) return '✓';
  if (subTask.isActive) return '▶';
  return '○';
};

// 获取子子进度图标
const getSubSubProgressIcon = (subSubTask) => {
  if (subSubTask.value >= 100) return '●';
  if (subSubTask.isActive) return '▸';
  return '◦';
};

// 获取进度样式类
const getProgressClass = (progress) => {
  if (progress.status === '错误') return 'error';
  if (progress.value >= 100) return 'completed';
  if (progress.value > 0) return 'active';
  return 'pending';
};

// 获取进度条样式类
const getProgressBarClass = (progress) => {
  if (progress.status === '错误') return 'error-bar';
  if (progress.value >= 100) return 'completed-bar';
  return 'active-bar';
};

// 关闭进度弹窗
const closeProgressModal = () => {
  showProgressModal.value = false;
  progressList.value = [];
};

// 修改轮换显示逻辑
const startRotation = () => {
  if (rotationInterval) {
    clearInterval(rotationInterval);
  }

  const updateItems = () => {
    if (!documentSummary.value?.length) {
      console.log("没有可用的文档摘要数据");
      return;
    }

    // 处理第一篇文档的问题（如：热门话题）
    try {
      const firstDocData = documentSummary.value[0];
      if (firstDocData?.questions) {
        // 直接使用questions数组中的问题
        const formattedQaPairs = firstDocData.questions.map((question) => ({
          question,
        }));
        // 随机抽取3个问题显示
        const shuffled = [...formattedQaPairs].sort(() => 0.5 - Math.random());
        currentQaPairs.value = shuffled.slice(0, 3);
      }
    } catch (error) {
      console.error("处理第一篇文档问题失败:", error);
    }

    // 处理第二篇文档的问题（如：设计指南）
    try {
      const secondDocData = documentSummary.value[1];
      if (secondDocData?.questions) {
        // 直接使用questions数组中的问题
        const formattedGuides = secondDocData.questions.map((question) => ({
          question,
        }));
        // 随机抽取3个问题显示
        const shuffled = [...formattedGuides].sort(() => 0.5 - Math.random());
        currentDesignGuides.value = shuffled.slice(0, 3);
      }
    } catch (error) {
      console.error("处理第二篇文档问题失败:", error);
    }
  };

  // 初始更新
  updateItems();

  // 每5秒更新一次
  rotationInterval = setInterval(updateItems, 5000);
};

// 处理QA点击事件
const handleQaClick = (qa) => {
  console.log("QA clicked:", qa); // 添加日志
  if (qa?.question) {
    inputContent.value = qa.question || qa.title;
    sendMessage();
  }
};

// 获取推荐问题列表
const fetchRecommendedQuestions = async () => {
  try {
    const response = await axios.get(
      `${import.meta.env.VITE_BASE_AI_API}/api/agents/commands/`,
      {
        headers: {
          'Authorization': `JWT ${localStorage.getItem('token')}`
        }
      }
    );
    console.log(response.data);
    if (response.data) {
      recommendedQuestions.value = response.data.data.commands;
      showRecommendedQuestions.value = true;
    }
  } catch (error) {
    console.error('获取推荐问题失败:', error);
    showRecommendedQuestions.value = false;
  }
};

// 处理推荐问题点击事件
const handleQuestionClick = (question) => {
  inputContent.value = question;
  sendMessage();
};

// 在组件卸载时清理定时器
onUnmounted(() => {
  if (rotationInterval) {
    clearInterval(rotationInterval);
  }
});


// 方法
const toggleAttachments = () => {
  showAttachments.value = !showAttachments.value;
};

const removeFile = (file) => {
  attachedFiles.value = attachedFiles.value.filter((f) => f !== file);
  if(attachedFiles.value.length === 0){
    rightMenuWidth.value = 0;
    if(document.querySelector('.chat')){
      document.querySelector('.chat').style.right = `0px`;
    }
  }else{
    rightMenuWidth.value = 450;
    if(document.querySelector('.chat')){
      document.querySelector('.chat').style.right = `${rightMenuWidth.value}px`;
    }
  }
  console.log(attachedFiles.value.length);
};

const triggerFileInput = () => {
  // 如果正在上传，不触发新的上传
  if (isUploading.value) return;
  fileInput.value?.click();
};

const uploadFile = async (file) => {
  try {
    const formData = new FormData();
    formData.append("file", file);

    const response = await axios.post(
      `${import.meta.env.VITE_BASE_AI_API}/upload/file`,
      formData,
      {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      }
    );

    if (response.data.status === 2000) {
      return response.data.data.fileUrl; // 返回文件上传后的URL
    } else {
      throw new Error(response.data.message || "文件上传失败");
    }
  } catch (error) {
    console.error("文件上传失败:", error);
    throw error;
  }
};

const handleFileUpload = async (event) => {
  const files = Array.from(event.target.files);
  if (files.length === 0) return;
  // 添加文件大小检查
  const MAX_VIDEO_SIZE = 10 * 1024 * 1024; // 10MB in bytes
  const invalidFiles = files.filter((file) => {
    if (isVideoFile(file) && file.size > MAX_VIDEO_SIZE) {
      return true;
    }
    return false;
  });

  if (invalidFiles.length > 0) {
    // 如果有超出大小限制的视频文件，显示错误提示
    alert("Video files must not exceed 10MB");
    event.target.value = ""; // 清空input
    return;
  }
  isUploading.value = true;
  rightMenuWidth.value = 450;

  try {
    for (const file of files) {
      // 创建一个带有上传状态的文件对象
      const fileWithStatus = {
        name: file.name,
        size: file.size,
        sizeFormatted: formatFileSize(file.size),
        type: file.type,
        isUploading: true,
      };

      // 先添加到文件列表中
      attachedFiles.value.push(fileWithStatus);

      try {
        const url = await uploadFile(file);
        // 直接修改数组中的对象
        const index = attachedFiles.value.findIndex(
          (f) => f.name === file.name
        );
        if (index !== -1) {
          // 使用数组替换方式更新，确保响应式更新
          attachedFiles.value.splice(index, 1, {
            ...fileWithStatus,
            url,
            isUploading: false,
          });
        }
      } catch (error) {
        // 如果上传失败，从列表中移除该文件
        attachedFiles.value = attachedFiles.value.filter(
          (f) => f.name !== file.name
        );
        console.error("单个文件上传失败:", error);
      }
    }
  } catch (error) {
    console.error("文件上传失败:", error);
  } finally {
    isUploading.value = false;
    event.target.value = ""; // 清空input以允许重复上传相同文件
    
    // 修改文件上传后的处理逻辑
    if (attachedFiles.value.length > 0) {
      // 切换到预览标签页
      activeTab.value = 'preview';
      // 展开右侧菜单
      isRightMenuCollapsed.value = false;
      // 如果在移动端，调整布局
      if (document.querySelector('.chat')) {
        document.querySelector('.chat').style.right = `${rightMenuWidth.value}px`;
      }
    }
  }

  if (files.length > 0 && enableWebSearch.value) {
    enableWebSearch.value = false; // 如果有文件上传，自动关闭互联网搜索
  }
};

const formatFileSize = (bytes) => {
  if (!bytes || isNaN(bytes)) 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 getFileIcon = (file) => {
  // 如果文件已经有 URL 且是图片类型，返回 URL
  if (file.url && isImageFile(file)) {
    return file.url;
  }

  // 其他所有情况返回文档图标
  return wordIcon;
};

const isImageFile = (file) => {
  const imageTypes = ["jpg", "jpeg", "png", "gif", "webp"];
  const ext = file.name?.split(".")?.pop()?.toLowerCase() || "";
  return imageTypes.includes(ext);
};

const isVideoFile = (file) => {
  const videoTypes = ["mp4", "webm", "ogg"];
  const ext = file.name?.split(".")?.pop()?.toLowerCase() || "";
  return videoTypes.includes(ext);
};

const getFileType = (file) => {
  const ext = file.name.split(".").pop().toLowerCase();
  const imageTypes = ["jpg", "jpeg", "png", "gif", "webp"];
  const videoTypes = ["mp4", "webm", "ogg"];
  if (imageTypes.includes(ext)) return "image";
  if (videoTypes.includes(ext)) return "video";
  return "document";
};

// 添加滚动到底部的方法
const scrollToBottom = () => {
  if (messageList.value) {
    nextTick(() => {
      messageList.value.scrollTop = messageList.value.scrollHeight;
    });
  }
};

// 添加 session_id 的响应式引用
const session_id = ref("");
// 添加取消控制器
const abortController = ref(null);

// 修改发送消息方法
const sendMessage = async () => {
  // 检查登录状态
  const token = localStorage.getItem('token');
  if (!token) {
    router.push('/login');
    return;
  }
  if(isTyping.value){
    isTyping.value = false;
    // 如果存在正在进行的请求，取消它
    if (abortController.value) {
      abortController.value.abort();
      abortController.value = null;
    }
    // 清除打字效果的定时器
    if (typingTimeout.value) {
      clearTimeout(typingTimeout.value);
      typingTimeout.value = null;
    }
    return;
  }
  if (
    (!inputContent.value.trim() && attachedFiles.value.length === 0) ||
    isTyping.value
  )
    return;
  isTyping.value = true;
  scrollToBottom()
  // 保存当前输入内容
  const currentMessage = inputContent.value.trim();

  // 立即清空输入框
  inputContent.value = '';

    
  // 根据开启的搜索类型执行相应的搜索
  if (enableWebSearch.value) {
    currentSearchQuery.value = currentMessage;
    // 执行互联网搜索
    sendMessageS(currentMessage).catch((error) => {
      console.error("Web search failed:", error);
    });
  } else if (enableKnowledgeSearch.value) {
    currentSearchQuery.value = currentMessage;
    // 执行知识库搜索
    handleKnowledgeSearch({
      query: currentMessage,
      page: 1,
      pageSize: 20
    });
  }

  // 构建消息内容，包含文件信息
  let messageContent = currentMessage;

  // 收集文件URLs
  const imageUrls = [];
  const videoUrls = [];
  const documentUrls = [];

  attachedFiles.value.forEach((file) => {
    const fileType = getFileType(file);
    if (fileType === "image") {
      imageUrls.push(file.url);
    } else if (fileType === "video") {
      videoUrls.push(file.url);
    } else {
      documentUrls.push(file.url);
    }
  });
  
  // 添加用户消息
  const userMessage = {
    id: Date.now(),
    role: "user",
    content: currentMessage,
    displayContent: currentMessage,
    files: attachedFiles.value.map((file) => ({
      name: file.name,
      size: file.sizeFormatted,
      type: file.type,
      url: file.url,
    })),
  };
  messages.value.push(userMessage);
const summaryHtml=ref('')
  // 添加临时AI消息
  const tempAiMessage = reactive({
    id: Date.now() + 1,
    role: "assistant",
    content: "思考中...",
    displayContent: "思考中...",
    isLoading: true,
  });
  messages.value.push(tempAiMessage);

  try {
      recommended.value=false
      showAttachments.value=false
    // 创建新的 AbortController
    abortController.value = new AbortController();
    if(!inferenceModel.value){
       // 构建请求参数
    /* const requestData = {
      message: currentMessage,
      chat_config_id: "2",
      user_id: "13365429324",
      session_id: session_id.value || "",
      source: "pc",
      image_urls: attachedFiles.value.filter(f => isImageFile(f)).map(f => f.url),
      video_urls: attachedFiles.value.filter(f => isVideoFile(f)).map(f => f.url),
      documents: attachedFiles.value.filter(f => !isImageFile(f) && !isVideoFile(f)).map(f => f.url),
      merchant_id: JSON.parse(localStorage.getItem('userInfo')).merchant.merchant_id||1,
      model_type: selectedModelInfo.value.type,
      model_name: selectedModelInfo.value.name
    }; */
 
    const apiEndpoint = enableWebSearch.value
      ? `${import.meta.env.VITE_BASE_AI_API}/api/chat/web-search-llm/`
      : enableKnowledgeSearch.value
      ? `${import.meta.env.VITE_BASE_AI_API}/api/chat/knowledge-only`
      : `${import.meta.env.VITE_BASE_AI_API}/api/chat/online/multimodal`;
      const response = await axios.post(apiEndpoint, {
      message: currentMessage,
      chat_config_id: "2",
      user_id: JSON.parse(localStorage.getItem('userInfo')).user_id||"13365429324",
      session_id: session_id.value,
      source: "pc",
      image_urls: imageUrls,
      video_urls: videoUrls,
      documents: documentUrls,
      merchant_id:JSON.parse(localStorage.getItem('userInfo')).merchant.merchant_id,
      model_type: selectedModelInfo.value.type,
      model_name: selectedModelInfo.value.name
    },
    {
      headers: {
        'Authorization': `JWT ${localStorage.getItem('token')}`
      },
      signal: abortController.value.signal
    }
  );

    // 移除临时消息
    messages.value = messages.value.filter(
      (msg) => msg.id !== tempAiMessage.id
    );

    // 统一处理响应数据
    const responseData = enableWebSearch.value ? response.data.data : response.data;
    const messageContent = enableWebSearch.value ? responseData.answer : responseData.choices[0].message.content;
    const audioInfo = enableWebSearch.value ? responseData.audio_info?.audio : responseData.audio_info?.audio;
    const sessionId = enableWebSearch.value ? responseData.session_id : responseData.session_id;
           // 处理地图数据
     if (responseData.map_display) {
          rightMenuWidth.value = 800;
          isRightMenuCollapsed.value = false;
          if (document.querySelector('.chat')) {
            document.querySelector('.chat').style.right = `${rightMenuWidth.value}px`;
          }
        mapDisplay.value = true;
        activeTab.value='map'
        if (responseData.map_display.center) {
          mapCenter.value = responseData.map_display.center;
        }
        // 处理路线数据
        if (responseData.map_display.polylines) {
          mapPolylines.value = responseData.map_display.polylines;
        }
      }
    // 更新 session_id
    if (sessionId) {
      session_id.value = sessionId;
    }

    // 创建新的AI消息
    const aiMessage = reactive({
      id: Date.now() + 2,
      role: "assistant",
      content: messageContent,
      displayContent: "",
      audioData: audioInfo || null,
      knowledgeSources: responseData.knowledge_sources ? 
        responseData.knowledge_sources.reduce((unique, current) => {
          const existing = unique.find(item => item.doc_id === current.doc_id);
          if (!existing) {
            unique.push(current);
          }
          return unique;
        }, []) : null, // 添加知识源数据，根据doc_id去重
    });
    messages.value.push(aiMessage);

    // 如果有音频数据，自动播放
    if (aiMessage.audioData && !isPlaying.value) {
      await playAudioMessage(aiMessage.audioData, aiMessage.id);
    }

    // 显示打字效果
    await typeMessage(aiMessage);

    }else{
  // 构建请求参数
      const requestData = {
        query: currentMessage,
       /*  user_id: "13365429324",
        session_id: session_id.value || "", */
      };

      // 发送初始请求获取SSE URL
      let reader = null;
       formatted_data.value=''
      try {
        // 只发送SSE请求
        const sseResponse = await fetch(`${import.meta.env.VITE_BASE_AI_API}/api/agents/database/streaming/`, {
          method: 'POST',
          headers: {
            'Authorization': `JWT ${token}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(requestData)
        });

        if (!sseResponse.ok) {
          throw new Error('SSE请求失败');
        }

        // 处理SSE响应
        
        reader = sseResponse.body.getReader();
        const decoder = new TextDecoder();
        let buffer = '';
        let currentEvent = '';
        let streamContent = '';

        // 读取流数据
        while (true) {
          const { done, value } = await reader.read();
          if (done) break;
          
          buffer += decoder.decode(value, { stream: true });
          const lines = buffer.split('\n');
          
          // 保留最后一行（可能不完整）
          buffer = lines.pop() || '';
          
            for (const line of lines) {
             if (line.startsWith('event:')) {
               currentEvent = line.substring(6).trim();
             } else if (line.startsWith('data:')) {
               try {
                 const dataStr = line.substring(5).trim();
                 if (dataStr) {
                   const data = JSON.parse(dataStr);
                   // 立即处理每条消息
                    
                     handleSSEMessage(currentEvent || 'message', data);
                     if(currentEvent==='thinking_process'){
                      console.log(data)
                      // 将思考过程添加到当前AI消息中（启用逐字输出）
                        tempAiMessage.thinkingSteps = [
                          ...(Array.isArray(data.alternative_approaches) ? data.alternative_approaches : []),
                          ...(Array.isArray(data.key_insights) ? data.key_insights : []),
                          ...(Array.isArray(data.reasoning_steps) ? data.reasoning_steps : [])
                        ].map(step => ({ content: step, displayContent: '' }));
                        // 等待渲染后再开始动画，避免首帧聚合
                        
                        // nextTick(() => {
                        //   requestAnimationFrame(() => {
                        //     animateThinkingStepsForMessage(tempAiMessage, 0);
                        //   });
                        // });
                        // 合并其他字段到思考过程
                        const __extraSteps = [];
                        if (typeof data.analysis_approach === 'string' && data.analysis_approach.trim()) {
                          __extraSteps.push({ content: `${data.analysis_approach}`, displayContent: '' });
                        }
                        if (typeof data.business_impact === 'string' && data.business_impact.trim()) {
                          __extraSteps.push({ content: `${data.business_impact}`, displayContent: '' });
                        }
                        // if (typeof data.confidence_level === 'number') {
                        //   __extraSteps.push({ content: `${data.confidence_level}` });
                        // }
                        if (data.model_version != null && `${data.model_version}`.trim() !== '') {
                          __extraSteps.push({ content: `${data.model_version}`, displayContent: '' });
                        }
                        if (data.processing_time != null && `${data.processing_time}`.trim() !== '') {
                          __extraSteps.push({ content: `${data.processing_time}`, displayContent: '' });
                        }
                        if (typeof data.query_intent === 'string' && data.query_intent.trim()) {
                          __extraSteps.push({ content: `${data.query_intent}`, displayContent: '' });
                        }
                        if (typeof data.risk_assessment === 'string' && data.risk_assessment.trim()) {
                          __extraSteps.push({ content: `${data.risk_assessment}`, displayContent: '' });
                        }
                        if (data.technical_constraints != null && `${data.technical_constraints}`.trim() !== '') {
                          __extraSteps.push({ content: `${data.technical_constraints}`, displayContent: '' });
                        }
                        const _prevLen = tempAiMessage.thinkingSteps.length;
                        tempAiMessage.thinkingSteps = [
                          ...tempAiMessage.thinkingSteps,
                          ...__extraSteps
                        ];
                        // 对新增的步骤做逐字打字（同样等待一帧）
                        if (__extraSteps.length > 0) {
                          console.log('tempAiMessage',tempAiMessage)
                          nextTick(() => {
                            requestAnimationFrame(() => {
                              animateThinkingStepsForMessage(tempAiMessage, 0);
                            });
                          });
                        }
                     }
                     if(currentEvent === 'final_summary'){
                        // 检查summary是否以"命令集提示："开头
                        if (data.summary && data.summary.startsWith('命令集提示：')) {
                          // 调用推荐问题接口
                          await fetchRecommendedQuestions();
                        } else {
                          // 隐藏推荐问题
                          showRecommendedQuestions.value = false;
                        }
                        
                        // 移除临时消息
                        messages.value = messages.value.filter(
                          (msg) => msg.id !== tempAiMessage.id
                        );

                                                     // 创建新的AI消息
                            const aiMessage = reactive({
                              id: Date.now() + 2,
                              role: "assistant",
                              content: data.summary,
                              summaryHtml:data.html_content,
                              analysis_result:data.analysis_result,
                              automation_plan:data.automation_plan,
                              thinkingSteps:  [], // 保留思考过程tempAiMessage?.thinkingSteps ||
                              displayContent: "",
                              audioData: null,
                              showRecommendedQuestions:showRecommendedQuestions.value || false
                            });
                            isTyping.value = true;
                            summaryHtml.value=data.html_content
                            messages.value.push(aiMessage);
                           
                            // 显示打字效果
                            try {
                              await typeMessage(aiMessage);
                            } catch (error) {
                              console.error('打字效果出错:', error);
                              // 如果打字效果失败，直接显示完整内容
                              aiMessage.displayContent = aiMessage.content;
                            } finally {
                              isTyping.value = false;
                            }
                     }      
                 }
               } catch (e) {
                 console.error('Failed to parse SSE data:', line, e);
               }
             } else if (line === '') {
               // 空行表示事件结束，重置当前事件
               currentEvent = '';
             }
           }
                 }

        
        
        // 设置初始的formatted_data（如果流式数据还没开始更新）
       /*  if (!streamContent) {
          formatted_data.value = responseData.result.html;
        } */
      } catch (error) {
        console.error('请求或处理过程出错:', error);
        //ElMessage.error('请求失败，请稍后重试');
        throw error;
      } finally {
        // 确保在结束时关闭reader
        if (reader) {
          try {
            await reader.cancel();
          } catch (error) {
            console.error('关闭reader时出错:', error);
          }
        }
      }
    }
    
    

  } catch (error) {
    console.error("发送消息失败:", error);
    // 移除临时消息
    messages.value = messages.value.filter(msg => msg.id !== tempAiMessage.id);
    
    // 添加错误消息
    messages.value.push({
      id: Date.now() + 2,
      role: "assistant",
      content: "发送消息失败，请重试",
      displayContent: "发送消息失败，请重试",
    });
  } finally {
    isTyping.value = false;
    abortController.value = null;
  }
};

// 修改 sendMessageS 方法
const sendMessageS = async (query) => {
  isSearchLoading.value = true;
  try {
    const response = await axios.post(
      `${import.meta.env.VITE_BASE_AI_API}/api/web-search-results/`,
      {
        query: query,
        num_results: 20,
        page: 1,
        page_size: 20,
        engine: "tavily",
      }
    );
      console.log(response)
    if (response.data && response.data.code === 200) {
      searchResults.value = response.data.data.result || [];
      console.log(searchResults.value)
      searchTotal.value = response.data.data.total || 0;
    }
  } catch (error) {
    console.error("Web search failed:", error);
    searchResults.value = [];
    searchTotal.value = 0;
  } finally {
    isSearchLoading.value = false;
  }
};

// 修改打字效果方法
const typeMessage = async (message) => {
  if (!message || !message.content) {
    console.error("Invalid message or content is missing");
    return;
  }

  return new Promise((resolve) => {
    const minDelay = 20; // 最小打字延迟
    const maxDelay = 50; // 最大打字延迟
    let i = 0;
    message.displayContent = ""; // 确保开始时是空的

    const typeChar = () => {
      if (i < message.content.length && isTyping.value) {
        // 处理特殊字符和标点符号
        let chunk = "";
        const char = message.content[i];
        
        // 如果是中文字符，整个字符一起显示
        if (/[\u4e00-\u9fa5]/.test(char)) {
          chunk = char;
        } 
        // 如果是标点符号，与前面的字符一起显示
        else if (/[.,!?;，。！？；]/.test(char)) {
          chunk = char;
        }
        // 如果是空格，与下一个单词一起显示
        else if (char === " " && i + 1 < message.content.length) {
          let j = i + 1;
          while (j < message.content.length && !/[\s\n]/.test(message.content[j])) {
            j++;
          }
          chunk = message.content.substring(i, j);
        }
        // 其他情况，单个字符显示
        else {
          chunk = char;
        }

        message.displayContent = message.content.substring(0, i) + chunk;
        i += chunk.length;

        // 根据字符类型动态调整延迟
        const delay = chunk.length > 1 ? maxDelay : minDelay;
        typingTimeout.value = setTimeout(typeChar, delay);
      } else {
        if (!isTyping.value) {
          // 如果打字被取消，直接显示完整内容
          message.displayContent = message.content;
        }
        resolve();
      }
    };

    typeChar();
  });
};

// 模拟API请求
const mockApiRequest = async (message) => {
  await new Promise((resolve) => setTimeout(resolve, 1000));
  return `This is a response to: ${message}`;
};

// 会话管理
const addNewConversation = () => {
  conversationCounter.value++;
  const newConversation = {
    id: Date.now(),
    title: `New Conversation ${conversationCounter.value}`,
    messages: [],
  };
  conversations.value.push(newConversation);
  session_id.value = ""; // 重置 session_id
  switchConversation(newConversation.id);
};

const switchConversation = (conversationId) => {
  currentConversationId.value = conversationId;
  const conversation = conversations.value.find((c) => c.id === conversationId);
  
  if (conversation) {
    // 如果会话有缓存的消息，直接使用
    if (conversation.messages && conversation.messages.length > 0) {
      messages.value = conversation.messages;
    } 
    // 如果会话有 sessionData，从中提取消息
    else if (conversation.sessionData) {
      const sessionData = conversation.sessionData;
      const extractedMessages = [];
      
      // 添加用户消息
      if (sessionData.user_message) {
        extractedMessages.push({
          id: `user_${sessionData.user_message.created_at}`,
          role: 'user',
          content: sessionData.user_message.content,
          timestamp: sessionData.user_message.created_at,
          type: 'text'
        });
      }
      
      // 添加助手消息
      if (sessionData.last_message && sessionData.last_message.role === 'assistant') {
        extractedMessages.push({
          id: `assistant_${sessionData.last_message.created_at}`,
          role: 'assistant',
          content: sessionData.last_message.content,
          displayContent: sessionData.last_message.content, // 添加 displayContent 用于显示
          timestamp: sessionData.last_message.created_at,
          type: 'text'
        });
      }
      
      messages.value = extractedMessages;
      // 将提取的消息保存到会话中，避免重复提取
      conversation.messages = extractedMessages;
    } else {
      messages.value = [];
    }
    
    // 设置 session_id
    session_id.value = conversationId;
  } else {
    messages.value = [];
    session_id.value = "";
  }
};

const handleFileDrop = async (event) => {
  if (isUploading.value) return;

  const files = Array.from(event.dataTransfer.files);
  if (files.length === 0) return;
  // 添加文件大小检查
  const MAX_VIDEO_SIZE = 10 * 1024 * 1024; // 10MB in bytes
  const invalidFiles = files.filter((file) => {
    if (isVideoFile(file) && file.size > MAX_VIDEO_SIZE) {
      return true;
    }
    return false;
  });

  isUploading.value = true;

  try {
    for (const file of files) {
      const fileWithStatus = {
        name: file.name,
        size: file.size,
        sizeFormatted: formatFileSize(file.size),
        type: file.type,
        isUploading: true,
      };

      attachedFiles.value.push(fileWithStatus);

      try {
        const url = await uploadFile(file);
        // 直接修改数组中的对象
        const index = attachedFiles.value.findIndex(
          (f) => f.name === file.name
        );
        if (index !== -1) {
          // 使用数组替换方式更新，确保响应式更新
          attachedFiles.value.splice(index, 1, {
            ...fileWithStatus,
            url,
            isUploading: false,
          });
        }
      } catch (error) {
        attachedFiles.value = attachedFiles.value.filter(
          (f) => f.name !== file.name
        );
        console.error("单个文件上传失败:", error);
      }
    }
  } catch (error) {
    console.error("文件上传失败:", error);
  } finally {
    isUploading.value = false;
    
    // 修改文件上传后的处理逻辑
    if (attachedFiles.value.length > 0) {
      // 切换到预览标签页
      activeTab.value = 'preview';
      // 展开右侧菜单
      isRightMenuCollapsed.value = false;
      // 如果在移动端，调整布局
      if (document.querySelector('.chat')) {
        document.querySelector('.chat').style.right = `${rightMenuWidth.value}px`;
      }
    }
  }

  if (files.length > 0 && enableWebSearch.value) {
    enableWebSearch.value = false; // 如果有文件上传，自动关闭互联网搜索
  }
};

// 添加音频点击处理方法
const handleAudioClick = (message) => {
  if(message.audioData){
    if (currentPlayingId.value === message.id) {
      stopAudio();
    } else {
      playAudioMessage(message.audioData, message.id);
    }  
  }else{
    // 用户消息的文本转语音处理
    if (currentPlayingId.value === message.id) {
      stopAudio();
    } else {
      playUserMessage(message.content, message.id);
    }
  }
};

// 添加播放用户消息的方法
const playUserMessage = async (text, messageId) => {
  try {
    // 如果当前有其他音频在播放，先停止
    if (currentPlayingId.value && currentPlayingId.value !== messageId) {
      stopAudio();
    }

    // 如果已经在播放这条消息，直接返回（这种情况应该不会发生，因为会被上面的 handleAudioClick 处理）
    if (currentPlayingId.value === messageId) {
      return;
    }

    const response = await axios.post(`${import.meta.env.VITE_BASE_AI_API}/api/voices/play_text`, {
      text: text
    }, {
      headers: {
        'Authorization': `JWT ${localStorage.getItem('token')}`
      },
    });
    
    if(response.data.code === 200){
      // 创建音频元素
      const audio = new Audio(`${import.meta.env.VITE_BASE_AI_API}${response.data.audio_url}`);
      
      // 保存当前播放的音频和ID
      currentAudioSource.value = audio;
      currentPlayingId.value = messageId;
      isPlaying.value = true;
      
      // 播放结束时清理
      audio.onended = () => {
        currentPlayingId.value = null;
        currentAudioSource.value = null;
        isPlaying.value = false;
      };

      // 播放错误时清理
      audio.onerror = (e) => {
        console.error('播放文本失败:', e);
        message.error('播放失败，请稍后重试');
        currentPlayingId.value = null;
        currentAudioSource.value = null;
        isPlaying.value = false;
      };
      
      // 开始播放
      await audio.play();
    }
  } catch (error) {
    console.error('播放文本失败:', error);
    message.error('播放失败，请稍后重试');
    currentPlayingId.value = null;
    currentAudioSource.value = null;
    isPlaying.value = false;
  }
};

// 修改停止播放方法
const stopAudio = () => {
  if (audioPlayer.value) {
    audioPlayer.value.pause();
    audioPlayer.value.currentTime = 0;
    audioPlayer.value = null;
  }
  if (currentAudioSource.value) {
    currentAudioSource.value.pause();
    currentAudioSource.value.currentTime = 0;
    currentAudioSource.value = null;
  }
  isPlaying.value = false;
  currentPlayingId.value = null;
};

// 在组件卸载时清理
onUnmounted(() => {
  stopAudio();
});

// 添加 renderMarkdown 方法
const renderMarkdown = (content) => {
  if (!content) return "";
  
  // 先处理think标签，将其从markdown内容中分离出来
  const thinkTagRegex = /<think>([\s\S]*?)<\/think>/gi;
  const thinkMatches = [];
  let processedContent = content;
  
  // 提取所有think标签内容
  processedContent = processedContent.replace(thinkTagRegex, (match, thinkContent) => {
    const thinkId = `think-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
    thinkMatches.push({
      id: thinkId,
      content: thinkContent.trim()
    });
    return `<div class="think-placeholder" data-think-id="${thinkId}"></div>`;
  });
  
  // 使用markdown-it渲染处理后的内容
  let renderedContent = md.render(processedContent);
  
  // 将think标签内容重新插入到渲染后的HTML中
  /*   <div class="think-header">
          <span class="think-icon">🤔</span>
          <span class="think-title">思考过程</span>
        </div> */
  thinkMatches.forEach(thinkMatch => {
    const placeholder = `<div class="think-placeholder" data-think-id="${thinkMatch.id}"></div>`;
    const thinkHtml = `
      <div class="think-container" data-think-id="${thinkMatch.id}">
        <div class="think-content">${md.render(thinkMatch.content)}</div>
      </div>
    `;
    renderedContent = renderedContent.replace(placeholder, thinkHtml);
  });
  
  return renderedContent;
};

// 添加新的响应式变量
const rightMenuWidth = ref(0); // 默认宽度
const minWidth = 0; // 最小宽度
const maxWidth = 800; // 最大宽度

// 添加拖动相关方法
const startResize = (e) => {
  e.preventDefault();
  
  const startX = e.type === 'mousedown' ? e.clientX : e.touches[0].clientX;
  const startWidth = rightMenuWidth.value;
  
  const handleMove = (e) => {
    if (isRightMenuCollapsed.value) return;
    
    const currentX = e.type === 'mousemove' ? e.clientX : e.touches[0].clientX;
    const diff = startX - currentX;
    
    let newWidth = Math.min(Math.max(startWidth + diff, minWidth), maxWidth);
    rightMenuWidth.value = newWidth;
    
    // 更新聊天区域的右边距和按钮位置
    if (document.querySelector('.chat')) {
      document.querySelector('.chat').style.right = `${newWidth}px`;
       if(newWidth==800){
         document.querySelector('.input-container').style.width = `97%`;
       }else{
         document.querySelector('.input-container').style.width = `98%`;
       }
    }
  };
  
  const handleEnd = () => {
    document.removeEventListener('mousemove', handleMove);
    document.removeEventListener('mouseup', handleEnd);
    document.removeEventListener('touchmove', handleMove);
    document.removeEventListener('touchend', handleEnd);
  };
  
  document.addEventListener('mousemove', handleMove);
  document.addEventListener('mouseup', handleEnd);
  document.addEventListener('touchmove', handleMove);
  document.addEventListener('touchend', handleEnd);
};

// 添加搜索开关状态
const isSearchEnabled = ref(true);

// 添加切换搜索方法 
const toggleSearch = () => {
  isSearchEnabled.value = !isSearchEnabled.value;
};

// 修改 toggleWebSearch 方法
const toggleWebSearch = () => {
  enableWebSearch.value = !enableWebSearch.value;
  isSearchEnabled.value = enableWebSearch.value;
  
  // 只有当当前标签是搜索标签时才折叠面板
  if (!enableWebSearch.value && activeTab.value === 'search') {
    isRightMenuCollapsed.value = true;
    currentSearchQuery.value = '';
    if (document.querySelector('.chat')) {
      document.querySelector('.chat').style.right = '0';
    }
  } else if (enableWebSearch.value && inputContent.value.trim()) {
    isRightMenuCollapsed.value = false;
    currentSearchQuery.value = inputContent.value;
    if (document.querySelector('.chat')) {
      document.querySelector('.chat').style.right = `${rightMenuWidth.value}px`;
    }
  }
};

// 添加新的响应式变量
const currentSearchQuery = ref('');

// 添加输入变化处理方法
const handleInputChange = () => {
  if (inputContent.value.trim()) {
    currentSearchQuery.value = inputContent.value;
    
    // 根据当前选中的搜索类型执行相应的搜索
    if (enableWebSearch.value) {
     /*  sendMessageS(inputContent.value).catch((error) => {
        console.error("Web search failed:", error);
      }); */
    } else if (enableKnowledgeSearch.value) {
      handleKnowledgeSearch({
        query: inputContent.value,
        page: 1,
        pageSize: 20
      });
    }
  }
};

// 添加处理搜索开关的方法
const handleSearchToggle = (value) => {
  console.log(enableWebSearch);
  enableWebSearch.value = value;
  if (value) {
    // 开启搜索时，确保右侧面板展开
    expandRightMenu();
    activeTab.value = 'search';
  }
};

// 添加新的响应式变量
const activeTab = ref('search'); // 默认显示搜索面板

// 处理文档选择
const handleDocumentSelect = (document) => {
  // 处理文档选择逻辑
  console.log('Selected document:', document);
};

  // 添加收缩状态控制
  const isCollapsed = ref(false);

// 监听屏幕宽度变化
const updateCollapsedState = () => {
  isCollapsed.value = window.innerWidth <= 480;
};


  onUnmounted(() => {
    window.removeEventListener('resize', updateCollapsedState);
  });

  // 添加收缩状态控制
  const isCompact = ref(false);

  // 监听屏幕宽度变化
  const updateCompactState = () => {
    isCompact.value = window.innerWidth <= 768;
  };


  onUnmounted(() => {
    window.removeEventListener('resize', updateCompactState);
  });

  // 添加计算属性
  const isRightMenuVisible = computed(() => {
    // 移除搜索开关对菜单显示的影响
    checkMobile();
    return !isRightMenuCollapsed.value;
    /* return (!isRightMenuCollapsed.value && (
      (enableWebSearch.value && activeTab.value === 'search') ||
      (enableKnowledgeSearch.value && activeTab.value === 'knowledge') ||
      (activeTab.value === 'preview' && attachedFiles.value.length > 0)
    )); */
  });
 /*  // 智能体
  const handleInferenceModel = () => {
    inferenceModel.value = !inferenceModel.value;
  }; */
  const currentQaPairsList = ref([]);
  watch(inferenceModel, async(newValue) => {
    console.log('智能体状态:', newValue);
    if (newValue) {
      // 打开右侧窗口
      rightMenuWidth.value = 800;
      isRightMenuCollapsed.value = false;
      if (document.querySelector('.chat')) {
        document.querySelector('.chat').style.right = `${rightMenuWidth.value}px`;
      }

      //获取智能体显示参数
      const response = await axios.get(
            `${import.meta.env.VITE_BASE_AI_API}/api/agents/notifications/stream/`,
            {
              headers: {
                'Authorization': `JWT ${localStorage.getItem('token')}`
              }
            }
          );
          console.log("API Response:", response.data);
          currentQaPairsList.value=response.data.notifications
      // currentQaPairs
      await fetchRecommendedQuestions();
     enableKnowledgeSearch.value=false
     enableWebSearch.value = false;
    } else {
      // 关闭右侧窗口
      
      isRightMenuCollapsed.value = true;
      if(enableKnowledgeSearch.value){
       
      }else{
        rightMenuWidth.value = 0;
         if (document.querySelector('.chat')) {
          document.querySelector('.chat').style.right = `460px`;
          document.querySelector('.input-container').style.width = `98%`;
        }
      }
      
    }
  });
  // 修改知识库搜索开关处理方法
  const handleKnowledgeToggle = async (event) => {
    if (event.target.checked) {
      rightMenuWidth.value = 450;
      // 使用 nextTick 确保 DOM 更新后再操作
      await nextTick();
      const chatElement = document.querySelector('.chat');
      if (chatElement) {
        chatElement.style.right = `${rightMenuWidth.value}px`;
      } else {
        console.warn('未找到聊天容器元素');
      }
      
      // 开启知识库搜索时关闭互联网搜索
      enableWebSearch.value = false;
      inferenceModel.value = false;
      
      // 切换到知识库标签页
      activeTab.value = 'knowledge';
      
      // 如果有输入内容，执行知识库搜索
      if (inputContent.value.trim()) {
        handleKnowledgeSearch({
          query: inputContent.value,
          page: 1,
          pageSize: 20
        });
      }
    } else {
      rightMenuWidth.value = 0;
      await nextTick();
      const chatElement = document.querySelector('.chat');
       document.querySelector('.input-container').style.width = `98%`;
      if (chatElement) {
        chatElement.style.right = `460px`;
      } else {
        console.warn('未找到聊天容器元素');
      }
    }
  };

  // 修改知识库搜索方法
  const handleKnowledgeSearch = async (params) => {
    if (!params.query.trim() || !enableKnowledgeSearch.value) return;

    isKnowledgeLoading.value = true;
    try {
      const response = await axios.post(
        `${import.meta.env.VITE_BASE_AI_API}/chataids/mysql_fuzzy_search/`,
        {
         // collection_names: ["25"], // 固定使用 "25" 作为 collection name
          keywords: params.query, // 使用查询关键词
          documents: [], // 保持空数组
          document_ids: [], // 保持空数组
          limit: 5 // 固定返回5条结果
        },
        {
          headers: {
            'Authorization': `JWT ${localStorage.getItem('token')}`
          }
        }
      );
        console.log(response);
      if (response.data && response.data.status === 200) {
        knowledgeResults.value = response.data.data.data || [];
        knowledgeTotal.value = response.data.data.data.total || 0;
      }
    } catch (error) {
      console.error('Knowledge search failed:', error);
      knowledgeResults.value = [];
      knowledgeTotal.value = 0;
    } finally {
      isKnowledgeLoading.value = false;
    }
  }

  // 修改处理互联网搜索开关的方法
  const handleWebSearchToggle = (event) => {
    if (event.target.checked) {
      rightMenuWidth.value = 450;
      if (document.querySelector('.chat')) {
        document.querySelector('.chat').style.right = `${rightMenuWidth.value}px`;
      }
      // 开启互联网搜索时关闭知识库搜索
      enableKnowledgeSearch.value = false;
      inferenceModel.value = false;
      // 切换到搜索标签页
      activeTab.value = 'search';
      
      // 如果有输入内容，执行互联网搜索
      if (inputContent.value.trim()) {
        currentSearchQuery.value = inputContent.value;
       /*  sendMessageS(inputContent.value).catch((error) => {
          console.error("Web search failed:", error);
        }); */
      }
    }else{
      rightMenuWidth.value = 0;
      if (document.querySelector('.chat')) {
        document.querySelector('.chat').style.right = `460px`;
      }
    }
  };

  // 添加新的响应式变量
  const API_BASE_URL = import.meta.env.VITE_BASE_AI_API;
  const models = ref([]);
  const selectedModel = ref(null);
  const isLoadingModels = ref(false);

  // 添加计算属性获取选中的模型信息
  const selectedModelInfo = computed(() => {
    if (!selectedModel.value || !models.value.length) return { type: '', name: '' };
    const model = models.value.find(m => m.id == selectedModel.value);
    return {
      type: model?.type || '',
      name: model?.name || ''
    };
  });

  // 添加获取模型列表的方法
  const fetchModels = async () => {
    isLoadingModels.value = true;
    try {
      const response = await fetch(`${API_BASE_URL}/api/models?merchant_id=${JSON.parse(localStorage.getItem('userInfo')).merchant.merchant_id}`);
      const data = await response.json();
      console.log(data);
      if (data.code === 2000) {
        // 确保每个模型对象都有必要的字段
        models.value = (data.data.models || []).map(model => ({
          id: model.id,
          name: model.name,
          type: model.type || model.model_type || 'default' // 确保有type字段
        }));
        if (models.value.length > 0) {
          selectedModel.value = models.value[0].id; // 默认选择第一个模型
        }
      }
    } catch (error) {
      console.error('Failed to fetch models:', error);
    } finally {
      isLoadingModels.value = false;
    }
  };

  // 添加模型选择改变的处理方法
  const handleModelChange = (modelId) => {
   
    selectedModel.value = modelId;
     console.log(selectedModel.value);
  };
 // 用户信息
  const userInfo = ref({
    name: '',
    role: ''
  });
  const getUserInfo = () => {
    const storedUserInfo = localStorage.getItem('userInfo');
    if (storedUserInfo) {
      userInfo.value = JSON.parse(storedUserInfo);
    }
  }

  // 在组件挂载时获取模型列表
  onMounted(() => {
    updateCompactState();
    window.addEventListener('resize', updateCompactState);
    updateCollapsedState();
    window.addEventListener('resize', updateCollapsedState);

    checkMobile();
  window.addEventListener('resize', checkMobile);

    fetchModels();

    fetchDocumentSummary();

     const storedUserInfo = localStorage.getItem('userInfo');
    if (storedUserInfo) {
      try {
        userInfo.value = JSON.parse(storedUserInfo);
      } catch (error) {
        console.error('解析用户信息失败:', error);
      }
    }
    
  });

  const showPasswordDialog = ref(false)
  const handleModifyPassword = () => {
    showPasswordDialog.value = true
    showDropdown.value = false // 关闭下拉菜单
  }

  const handleLogout = async () => {
    try {
      // 调用退出登录接口
      await axios.post(`${import.meta.env.VITE_BASE_AI_API}/user/logout`, {}, {
        headers: {
          'Authorization': `JWT ${localStorage.getItem('token')}`
        }
      });

      // 清除本地存储的信息
      localStorage.removeItem('token');
      localStorage.removeItem('userInfo');
      localStorage.removeItem('permissions');
      localStorage.removeItem('username');
      localStorage.removeItem('mobile');

      // 清除 Vuex store 中的用户信息
      store.commit('app/setUser', {
        user: {},
        permission: [],
        auth: {}
      });

      // 关闭下拉菜单
      showDropdown.value = false;

      // 跳转到登录页面
      router.push('/login');
    } catch (error) {
      console.error('退出登录失败:', error);
      // 即使接口调用失败，也清除本地信息并跳转
      localStorage.clear();
      router.push('/login');
    }
  };

  const handleCreateInvitation = async () => {
    try {
      const response = await axios.post(`${import.meta.env.VITE_BASE_AI_API}/user/create_invitation`, {}, {
        headers: {
          'Authorization': `JWT ${localStorage.getItem('token')}`
        }
      });
      console.log(response);
      if (response.data.code === 200) {
        message.success('创建邀请成功');
        // 从当前窗口location获取基础URL
        const baseUrl = `${window.location.protocol}//${window.location.host}`;
        // 跳转到完整URL
        window.location.href = `${baseUrl}#${response.data.data.invitation_link}`;
      } else {
        message.error(response.data.message || '创建邀请失败');
      }
    } catch (error) {
      console.error('创建邀请失败:', error);
      message.error(error.response?.data?.message || '创建邀请失败，请稍后重试');
    }
    showDropdown.value = false; // 关闭下拉菜单
  };

/*   return {
    loginForm,
    formData,
    rules,
    loading,
    rememberMe,
    loginType,
    countdown,
    handleLogin,
    sendVerificationCode,
    switchToMobileLogin,
    switchToAccountLogin,
    switchToWechatLogin,
    wechatLoginModal,
    wechatQrCode,
    getWechatQrCode,
    handleWechatLoginCancel,
    handleCreateInvitation
  }; */

  // These variables are already declared above
  /* const currentAudioSource = ref(null);
  const currentPlayingId = ref(null); */

  // 添加播放音频消息的方法
  const playAudioMessage = async (audioData, messageId) => {
    try {
      // 如果当前有其他音频在播放，先停止
      if (currentPlayingId.value && currentPlayingId.value !== messageId) {
        stopAudio();
      }

      // 如果已经在播放这条消息，直接返回
      if (currentPlayingId.value === messageId) {
        return;
      }

      // 创建新的音频元素
      const audio = new Audio(audioData);
      
      // 保存当前播放的音频和ID
      currentAudioSource.value = audio;
      currentPlayingId.value = messageId;
      isPlaying.value = true;
      
      // 播放结束时清理
      audio.onended = () => {
        currentPlayingId.value = null;
        currentAudioSource.value = null;
        isPlaying.value = false;
      };

      // 播放错误时清理
      audio.onerror = (e) => {
        console.error('播放音频失败:', e);
        message.error('播放失败，请稍后重试');
        currentPlayingId.value = null;
        currentAudioSource.value = null;
        isPlaying.value = false;
      };
      
      // 开始播放
      await audio.play();
    } catch (error) {
      console.error('播放音频失败:', error);
      message.error('播放失败，请稍后重试');
      currentPlayingId.value = null;
      currentAudioSource.value = null;
      isPlaying.value = false;
    }
  };

  // 主题状态
  const isDarkTheme = ref(false);

  // 应用主题
  const applyTheme = (isDark) => {
    document.documentElement.classList.toggle('dark-theme', isDark);
  };

  // 切换主题
  const toggleTheme = () => {
    isDarkTheme.value = !isDarkTheme.value;
    localStorage.setItem('theme', isDarkTheme.value ? 'dark' : 'light');
    applyTheme(isDarkTheme.value);
  };

  // FAB 浮动操作按钮相关方法
  const toggleFab = () => {
    // 添加动画类来启用transition
    const fabElement = document.querySelector('.fab');
    if (fabElement) {
      fabElement.classList.add('animated');
    }
    
    isFabOpen.value = !isFabOpen.value;
  };

  const handleReply = () => {
    console.log('回复功能');
    // 这里可以添加回复逻辑
    message.info('回复功能');
  };

  const handleLove = () => {
    console.log('收藏功能');
    // 这里可以添加收藏逻辑
    message.info('收藏功能');
  };
 const recommended=ref(false)
  const handleDelete = async () => {
    inferenceModel.value = true;
    recommended.value=!recommended.value
    await fetchRecommendedQuestions();
  };

  // 初始化主题
  onMounted(() => {
    if (document.querySelector('.chat')) {
        document.querySelector('.chat').style.right = `460px`;
    }
    checkMobile();
    // 优先使用存储的主题设置
    const savedTheme = localStorage.getItem('theme');
    if (savedTheme) {
      isDarkTheme.value = savedTheme === 'dark';
    } else {
      // 如果没有存储的主题，则使用系统主题
      isDarkTheme.value = window.matchMedia('(prefers-color-scheme: dark)').matches;
    }
    applyTheme(isDarkTheme.value);

    // 监听系统主题变化
    const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
    mediaQuery.addEventListener('change', (e) => {
      if (!localStorage.getItem('theme')) {
        isDarkTheme.value = e.matches;
        applyTheme(e.matches);
      }
    });
  });

  /* return {
    isDarkTheme,
    toggleTheme,
    // ... existing return values ...
  }; */

  const excelOptions = ref({
    xls: false,       // 预览xlsx文件设为false；预览xls文件设为true
    minColLength: 15,  // excel最少渲染列数
    minRowLength: 50,  // excel最少渲染行数，增加以确保显示更多内容
    widthOffset: 50,  // 增加列宽偏移量，使内容显示更完整
    heightOffset: 30, // 增加行高偏移量
    forceRender: true, // 强制渲染
    maxSheetLength: 10, // 最多渲染工作表数量
    showGridLines: true, // 显示网格线
    defaultFontSize: 12, // 默认字体大小
    defaultRowHeight: 24, // 默认行高
    autoFitColumn: true, // 自动适应列宽
    overflowColumns: true, // 允许列内容溢出
    showToolbar: true, // 显示工具栏
  });

  // 添加Excel渲染完成的处理函数
  const handleRendered = () => {
    console.log('Excel文件渲染完成');
    nextTick(() => {
      // 手动触发一次重新计算大小
      window.dispatchEvent(new Event('resize'));
    });
  };

  // 添加Excel错误处理函数的详细信息
  const handleExcelError = (error) => {
    console.error('Excel文件渲染失败:', error);
    message.error('Excel预览失败：' + (error.message || '请尝试下载后查看'));
  };

  const isWordFile = (file) => {
  if (!file) return false;
  const wordTypes = ['doc', 'docx'];
  const ext = file.name?.split('.')?.pop()?.toLowerCase() || '';
  const isWord = wordTypes.includes(ext);
  if (isWord && file.type) {
    return file.type === 'application/msword' || 
           file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
  }
  return isWord;
};

  const isExcelFile = (file) => {
    if (!file) return false;
    const excelTypes = ['xls', 'xlsx'];
    const ext = file.name?.split('.')?.pop()?.toLowerCase() || '';
    return excelTypes.includes(ext);
  };

  const isPdfFile = (file) => {
    if (!file) return false;
    return file.name?.toLowerCase()?.endsWith('.pdf') || false;
  };

  const currentDoc = ref(null);

  // 监听文档列表变化
  watch(() => attachedFiles.value, (newFiles) => {
    if (newFiles && newFiles.length > 0) {
      currentDoc.value = newFiles[newFiles.length - 1]; // 预览最新上传的文档
    } else {
      currentDoc.value = null;
    }
  }, { 
    immediate: true, 
    deep: true
  });

  const handleDownload = (doc) => {
    if (doc.url) {
      const link = document.createElement('a');
      link.href = doc.url;
      link.download = doc.name;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }
  };

  const closePreview = () => {
    currentDoc.value = null;
  };

  // 添加文档点击事件处理
  const handleDocClick = (doc) => {
    currentDoc.value = doc;
  };

 /*  

 */

  // 添加流式思考步骤
  const currentThinkingSteps = ref([]);

  // 添加流式思考步骤
  const addThinkingStep = (step) => {
    const s = {
      type: step.type || 'default',
      content: step.content,
      displayContent: '',
      timestamp: Date.now()
    };
    currentThinkingSteps.value.push(s);
    // 渲染后启动逐字动画，避免瞬时显示
    nextTick(() => {
      requestAnimationFrame(() => {
        typeTextTo(s);
      });
    });
  };

  // 清除当前思考步骤
  const clearThinkingSteps = () => {
    currentThinkingSteps.value = [];
  };

  // 在消息发送完成后将思考步骤添加到消息中
  const finalizeThinkingSteps = (messageId) => {
    const message = messages.value.find(m => m.id === messageId);
    if (message) {
      message.thinkingSteps = [...currentThinkingSteps.value];
      clearThinkingSteps();
    }
  };

  // 获取思考步骤类型的中文名称
  const getStepTypeName = (stepType) => {
    const typeNames = {
      'query_understanding': '查询理解',
      'context_analysis': '上下文分析',
      'data_scope': '数据范围',
      'business_value': '业务价值',
      'start': '开始',
      'text_analysis': '文本分析',
      'planning': '规划',
      'execution': '执行',
      'result': '结果',
      'conclusion': '结论'
    };
    return typeNames[stepType] || stepType;
  };
 </script>

<style scoped>
.layout {
  display: flex;
  width: 100%;
  height: 100vh;
  overflow: hidden;
  position: relative;
}

.header {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 64px;
  background: #f7f7f8;
  border-bottom: 1px solid rgba(0, 0, 0, 0.06);
  z-index: 999;
}

.user-profile-bar {
  margin: 0 auto;
  position: relative;
  display: flex;
  align-items: center;
  justify-content:  space-between;
  cursor: pointer;
 
 
}
.user-info-bar {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  width: auto;
  height: 100%;
  background-color: var(--primary-bg);
  border-radius: 10px;
  padding: 4px 12px;
  margin-right: 12px;
  box-shadow: var(--shadow-sm);
}
.avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  overflow: hidden;
  margin-left: 12px;
  cursor: pointer;
  transition: transform 0.2s ease;
}

.avatar:hover {
  transform: scale(1.05);
}

.avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.user-info {
  display: flex;
  /* flex-direction: column; */
  margin-right: 8px;
  cursor: pointer;
}

.user-name {
  font-size: 13px;
  font-weight: 400;
  color: var(--primary-text);
  line-height: 1.4;
}

.dropdown-menu {
  position: absolute;
  top: 100%;
  right: 0;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
  min-width: 160px;
  z-index: 1000;
  margin-top: 4px;
}

.dropdown-item {
  padding: 12px 16px;
  display: flex;
  align-items: center;
  color: var(--primary-text);
  transition: background-color 0.2s;
}

.dropdown-item:hover {
  background-color: #f5f5f5;
}

/* 进度条弹窗样式 - 优化版本 */
.progress-modal-overlay {
  position: fixed;
  bottom: 180px;
  right: 5%;
  width: auto;
  height: auto;
  background-color: transparent;
  display: block;
  z-index: 9998;
  animation: slideInUp 0.3s ease-out;
}

/* 响应式定位 - 确保在不同屏幕尺寸下都在任务按钮上方 */
@media (max-width: 768px) {
  .progress-modal-overlay {
    bottom: 160px;
    right: 5%;
  }
}

@media (max-width: 480px) {
  .progress-modal-overlay {
    bottom: 140px;
    right: 15%;
  }
}

/* 大屏幕优化 */
@media (min-width: 1200px) {
  .progress-modal-overlay {
    bottom: 200px;
    right: 5%;
  }
}

/* 超宽屏幕优化 */
@media (min-width: 1920px) {
  .progress-modal-overlay {
    bottom: 220px;
    right: 5%;
  }
}

@keyframes slideInUp {
  from {
    transform: translateY(100%);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}

.progress-modal {
  background: #ffffff;
  border-radius: 12px;
  padding: 24px;
  min-width: 320px;
  max-width: 400px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.08);
  text-align: left;
  border: 1px solid #f0f0f0;
}

.progress-modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.progress-modal-header h3 {
  margin: 0;
  color: #1a1a1a;
  font-size: 18px;
  font-weight: 600;
  background: linear-gradient(135deg, #1890ff, #722ed1);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.close-btn {
  background: rgba(0, 0, 0, 0.05);
  border: none;
  font-size: 18px;
  color: #666;
  cursor: pointer;
  padding: 0;
  width: 28px;
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.2s ease;
  font-weight: bold;
}

.close-btn:hover {
  background: rgba(255, 0, 0, 0.1);
  color: #ff4d4f;
  transform: scale(1.1);
}

.progress-list {
  max-height: 350px;
  overflow-y: auto;
  scrollbar-width: thin;
  scrollbar-color: #d9d9d9 transparent;
}

.progress-list::-webkit-scrollbar {
  width: 4px;
}

.progress-list::-webkit-scrollbar-track {
  background: transparent;
}

.progress-list::-webkit-scrollbar-thumb {
  background: #d9d9d9;
  border-radius: 2px;
}

.progress-item {
  margin-bottom: 16px;
  padding: 16px;
  border: 1px solid rgba(0, 0, 0, 0.06);
  border-radius: 12px;
  background: linear-gradient(135deg, #ffffff 0%, #fafbfc 100%);
  transition: all 0.2s ease;
  position: relative;
  overflow: hidden;
}

.progress-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 2px;
  background: linear-gradient(90deg, #1890ff, #722ed1);
  opacity: 0.8;
}

.progress-item:last-child {
  margin-bottom: 0;
}

.progress-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
}

.progress-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.progress-title {
  font-size: 14px;
  color: #262626;
  font-weight: 500;
  flex: 1;
  margin-right: 12px;
}

.progress-percentage {
  font-size: 13px;
  color: #1890ff;
  font-weight: 600;
  background: rgba(24, 144, 255, 0.1);
  padding: 2px 8px;
  border-radius: 12px;
  min-width: 45px;
  text-align: center;
}

.progress-bar-container {
  width: 100%;
  height: 8px;
  background: linear-gradient(90deg, #f0f0f0, #e8e8e8);
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 10px;
  position: relative;
}

.progress-bar {
  height: 100%;
  background: linear-gradient(90deg, #1890ff 0%, #40a9ff 50%, #722ed1 100%);
  border-radius: 4px;
  transition: width 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
}

.progress-bar::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
  animation: shimmer 2s infinite;
}

@keyframes shimmer {
  0% { transform: translateX(-100%); }
  100% { transform: translateX(100%); }
}

.progress-status {
  font-size: 12px;
  color: #8c8c8c;
  text-align: right;
  font-style: italic;
}

/* 进度项状态样式 */
.progress-item.completed {
  background: linear-gradient(135deg, #f6ffed 0%, #f0f9ff 100%);
  border-color: #52c41a;
}

.progress-item.error {
  background: linear-gradient(135deg, #fff2f0 0%, #fff1f0 100%);
  border-color: #ff4d4f;
}

.progress-title-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
}

.progress-icon {
  font-size: 16px;
  min-width: 20px;
}

/* 进度百分比状态样式 */
.progress-percentage.completed {
  background: rgba(82, 196, 26, 0.1);
  color: #52c41a;
}

.progress-percentage.error {
  background: rgba(255, 77, 79, 0.1);
  color: #ff4d4f;
}

.progress-percentage.active {
  background: rgba(24, 144, 255, 0.1);
  color: #1890ff;
}

/* 进度条状态样式 */
.progress-bar.completed-bar {
  background: linear-gradient(90deg, #52c41a 0%, #73d13d 100%);
}

.progress-bar.error-bar {
  background: linear-gradient(90deg, #ff4d4f 0%, #ff7875 100%);
}

/* 子进度项样式 */
.sub-progress-list {
  margin-top: 12px;
  padding-left: 16px;
  border-left: 2px solid #f0f0f0;
}

.sub-progress-item {
  margin-bottom: 8px;
  padding: 8px 12px;
  background: rgba(0, 0, 0, 0.02);
  border-radius: 6px;
  border: 1px solid transparent;
  transition: all 0.2s ease;
}

.sub-progress-item.active {
  background: rgba(24, 144, 255, 0.05);
  border-color: rgba(24, 144, 255, 0.2);
  transform: translateX(4px);
}

.sub-progress-item.completed {
  background: rgba(82, 196, 26, 0.05);
  border-color: rgba(82, 196, 26, 0.2);
}

.sub-progress-item:last-child {
  margin-bottom: 0;
}

.sub-progress-info {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 6px;
}

.sub-progress-icon {
  font-size: 12px;
  min-width: 16px;
  color: #666;
}

.sub-progress-item.active .sub-progress-icon {
  color: #1890ff;
}

.sub-progress-item.completed .sub-progress-icon {
  color: #52c41a;
}

.sub-progress-title {
  font-size: 12px;
  color: #595959;
  flex: 1;
}

.sub-progress-item.active .sub-progress-title {
  color: #1890ff;
  font-weight: 500;
}

.sub-progress-item.completed .sub-progress-title {
  color: #52c41a;
}

.sub-progress-percentage {
  font-size: 11px;
  color: #8c8c8c;
  font-weight: 600;
  min-width: 35px;
  text-align: right;
}

.sub-progress-item.active .sub-progress-percentage {
  color: #1890ff;
}

.sub-progress-item.completed .sub-progress-percentage {
  color: #52c41a;
}

.sub-progress-bar-container {
  width: 100%;
  height: 4px;
  background: #f5f5f5;
  border-radius: 2px;
  overflow: hidden;
}

.sub-progress-bar {
  height: 100%;
  background: linear-gradient(90deg, #d9d9d9 0%, #bfbfbf 100%);
  border-radius: 2px;
  transition: width 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.sub-progress-item.active .sub-progress-bar {
  background: linear-gradient(90deg, #1890ff 0%, #40a9ff 100%);
}

.sub-progress-item.completed .sub-progress-bar {
  background: linear-gradient(90deg, #52c41a 0%, #73d13d 100%);
}

/* 子子进度项样式 */
.sub-sub-progress-list {
  margin-top: 8px;
  padding-left: 12px;
  border-left: 1px solid #e8e8e8;
}

.sub-sub-progress-item {
  margin-bottom: 6px;
  padding: 6px 8px;
  background: rgba(0, 0, 0, 0.01);
  border-radius: 4px;
  border: 1px solid transparent;
  transition: all 0.15s ease;
  font-size: 11px;
}

.sub-sub-progress-item.active {
  background: rgba(24, 144, 255, 0.03);
  border-color: rgba(24, 144, 255, 0.15);
  transform: translateX(2px);
}

.sub-sub-progress-item.completed {
  background: rgba(82, 196, 26, 0.03);
  border-color: rgba(82, 196, 26, 0.15);
}

.sub-sub-progress-item:last-child {
  margin-bottom: 0;
}

.sub-sub-progress-info {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-bottom: 4px;
}

.sub-sub-progress-icon {
  font-size: 10px;
  min-width: 12px;
  color: #999;
}

.sub-sub-progress-item.active .sub-sub-progress-icon {
  color: #1890ff;
}

.sub-sub-progress-item.completed .sub-sub-progress-icon {
  color: #52c41a;
}

.sub-sub-progress-title {
  font-size: 11px;
  color: #8c8c8c;
  flex: 1;
  line-height: 1.2;
}

.sub-sub-progress-item.active .sub-sub-progress-title {
  color: #1890ff;
  font-weight: 500;
}

.sub-sub-progress-item.completed .sub-sub-progress-title {
  color: #52c41a;
}

.sub-sub-progress-percentage {
  font-size: 10px;
  color: #bfbfbf;
  font-weight: 600;
  min-width: 30px;
  text-align: right;
}

.sub-sub-progress-item.active .sub-sub-progress-percentage {
  color: #1890ff;
}

.sub-sub-progress-item.completed .sub-sub-progress-percentage {
  color: #52c41a;
}

.sub-sub-progress-bar-container {
  width: 100%;
  height: 3px;
  background: #f8f8f8;
  border-radius: 1.5px;
  overflow: hidden;
}

.sub-sub-progress-bar {
  height: 100%;
  background: linear-gradient(90deg, #e8e8e8 0%, #d9d9d9 100%);
  border-radius: 1.5px;
  transition: width 0.2s cubic-bezier(0.4, 0, 0.2, 1);
}

.sub-sub-progress-item.active .sub-sub-progress-bar {
  background: linear-gradient(90deg, #69c0ff 0%, #91d5ff 100%);
}

.sub-sub-progress-item.completed .sub-sub-progress-bar {
  background: linear-gradient(90deg, #95de64 0%, #b7eb8f 100%);
}

/* 层级缩进视觉效果 */
.progress-item {
  position: relative;
}

.progress-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 2px;
  background: linear-gradient(90deg, #1890ff, #722ed1);
  opacity: 0.8;
}

.sub-progress-item {
  position: relative;
}

.sub-progress-item::before {
  content: '';
  position: absolute;
  left: -16px;
  top: 50%;
  width: 8px;
  height: 1px;
  background: #d9d9d9;
  transform: translateY(-50%);
}

.sub-progress-item.active::before {
  background: #1890ff;
}

.sub-progress-item.completed::before {
  background: #52c41a;
}

.sub-sub-progress-item {
  position: relative;
}

.sub-sub-progress-item::before {
  content: '';
  position: absolute;
  left: -12px;
  top: 50%;
  width: 6px;
  height: 1px;
  background: #e8e8e8;
  transform: translateY(-50%);
}

.sub-sub-progress-item.active::before {
  background: #69c0ff;
}

.sub-sub-progress-item.completed::before {
  background: #95de64;
}

.dropdown-item i {
  margin-right: 8px;
  font-size: 14px;
  color: #666;
}

.menu {
  margin-top: 64px;
  padding-top: 15px;
  background: #f7f7f8;
  width: 260px;
  height: 93%;
  display: flex;
  flex-direction: column;
  border-right: 1px solid rgba(0, 0, 0, 0.06);
  position: absolute;
  left: 0;
  /* transform: translateX(0); */
  transition: all 0.3s ease;
  z-index: 2;
}

.menu.collapsed {
  display: none;
  transform: translateX(-260px);
  width: 0;
}

.conversations {
  padding: 0 12px;
  flex: 1;
  overflow-y: auto;
}

.chat {
  flex: 1;
  margin: 75px 24px 24px;
  display: flex;
  flex-direction: column;
  gap: 24px;
  overflow-y: auto;
  overflow-x: hidden;
  transition: all 0.3s ease;
  position: absolute;
  left: 0;
  right: 260px;
  top: 0;
  bottom: 0;
  justify-content: space-between;
  background-color: var(--primary-bg);
 /*  margin: 16px; */
  border-radius: 16px;
  box-shadow:  0 5px 10px rgba(0, 0, 0, 0.05);
}

.chat-header {
    padding: 20px 24px;
    border-bottom: 1px solid var(--border-color);
    display: flex;
    align-items: center;
    justify-content: space-between;
    background: var(--secondary-bg);
}

.chat-header h2 {
    font-size: 18px;
    font-weight: 600;
    color: var(--text-primary);
    margin: 0;
}

.chat-status {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 14px;
    color: var(--text-secondary);
}

.status-indicator {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background: var(--success-color);
    animation: pulse 2s infinite;
}

.menu:not(.collapsed) + .chat {
  left: 260px;
}

.chat {
  right: 0;
  transition: all 0.3s ease;
}

.layout:has(.right_menu:not(.collapsed)) .chat {
  right: 450px;
}

.right_menu:not(.collapsed) ~ .chat {
  right: 450px;
}

.messages {
  flex: 1;
  overflow-y: auto;
  padding-right: 16px;
}

.sender {
  box-shadow: none;
  border: 1px solid #e5e6eb;
  border-radius: 8px;
  padding: 8px;
}

.logo {
  height: 64px;
  display: flex;
  align-items: center;
  padding: 0 20px;
}

.logo-img {
  /* width: 24px; */
  height: 40px;
}

.logo span {
  margin-left: 12px;
  font-size: 16px;
  font-weight: 600;
  color: rgba(0, 0, 0, 0.88);
}

.new-conversation-btn {
  margin: 0 12px 12px;
  height: 40px;
  background: rgba(235, 245, 255, 0.7);
  border: none;
  border-radius: 8px;
  color: #1677ff;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.new-conversation-btn:hover {
  background: rgba(235, 245, 255, 0.9);
}

.conversation-list {
  background: var(--secondary-bg);
  flex: 1;
  color: var(--primary-text);
  padding: 0 8px;
  overflow-y: auto;
}

.conversation-item {
  padding: 5px 12px;
  margin: 4px 0;
/*   border-radius: 8px; */
  color: var(--primary-text);
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.2s;
  display: flex;
  flex-direction: column;
  gap: 4px;
  border-bottom: 1px dashed #e5e6eb;
}

.conversation-title {
  font-weight: 500;
  color: #333;
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  white-space:nowrap;
	overflow:hidden;
	text-overflow:ellipsis;
}

.conversation-meta {
  display: flex;

  align-items: center;
  font-size: 12px;
  color: #666;
}

.conversation-time {
  color: var(--secondary-text);
  font-size: 11px;
}

.conversation-type {
  background: var(--accent-bg);
  color: var(--accent-text);
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 11px;
}

.conversation-item:hover {
  background: rgba(0, 0, 0, 0.04);
}

.conversation-item.active {
  background: var(--secondary-bg);
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06);
}

.conversation-list::-webkit-scrollbar {
  width: 4px;
}

.conversation-list::-webkit-scrollbar-thumb {
  background: rgba(0, 0, 0, 0.15);
  border-radius: 2px;
}

.conversation-list::-webkit-scrollbar-track {
  background: transparent;
}

:deep(.welcome-message) {
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  display: flex;
  align-items: flex-start;
  gap: 16px;
}

:deep(.welcome-message .title) {
  font-size: 16px;
  font-weight: 500;
  color: rgba(0, 0, 0, 0.88);
  margin-bottom: 4px;
}

:deep(.welcome-message .description) {
  color: rgba(0, 0, 0, 0.45);
  font-size: 14px;
}

:deep(.prompt-card) {
  background: #f7f8fa;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 12px;
}

:deep(.prompt-card-title) {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  gap: 8px;
}

:deep(.prompt-option) {
  background: #f5f5f5;
  padding: 8px 12px;
  border-radius: 4px;
  margin-top: 8px;
  cursor: pointer;
  transition: background 0.3s;
}

:deep(.prompt-option:hover) {
  background: #e8e8e8;
}

.input-container {
  padding: 15px;
  width: 98%;
  /* margin: auto auto 0;
  display: flex;
  flex-direction: column; */
  background-color: var(--secondary-bg);
  border-radius: 5px;
}

.tabs-wrapper {
  display: flex;
  gap: 8px;
  margin-bottom: 4px;
}

.tab-item {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 4px 12px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  color: rgba(0, 0, 0, 0.88);
  background: transparent;
  transition: background-color 0.2s;
}

.tab-item:hover {
  background: rgba(0, 0, 0, 0.04);
}

.tab-item.active {
  background: #f5f5f5;
}

.tab-item .anticon {
  font-size: 14px;
}

.input-wrapper {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  border: 1px solid var(--border-color);
  border-radius: 8px;
  background: var(--secondary-bg);
  color: var(--primary-text);
}

.message-input {
  flex: 1;
  border: none;
  outline: none;
  padding: 8px;
  font-size: 14px;
  background: transparent;
  color: var(--primary-text);
}

.message-input::placeholder {
  color: var(--primary-text);
}

.attachment-btn,
.send-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border: none;
  background: transparent;
  cursor: pointer;
  color: rgba(0, 0, 0, 0.45);
  border-radius: 4px;
  padding: 0;
}

.attachment-btn:hover,
.send-btn:hover {
  background: rgba(0, 0, 0, 0.04);
  color: var(--primary-text);
}

.attachments-panel {
  background: var(--primary-bg);
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

.panel-content {
  background: var(--primary-bg);
}

.attachments-header {
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.attachments-header span {
  font-size: 14px;
  font-weight: 500;
  color: var(--primary-text);
}

.close-btn {
  border: none;
  background: transparent;
  cursor: pointer;
  padding: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: rgba(0, 0, 0, 0.45);
}

.upload-area {
  padding: 24px;
  border-radius: 8px;
  text-align: center;
  cursor: pointer;
  color: var(--primary-text);
  transition: all 0.3s;
}

.upload-area.has-files {
  padding: 12px;
  background: var(--primary-bg);
}

.upload-icon {
  width: 32px;
  height: 32px;
  margin-bottom: 8px;
}

.upload-text {
  font-size: 14px;
  color: var(--primary-text);
  margin-bottom: 4px;
}

.upload-hint {
  font-size: 12px;
  color: var(--primary-text);
}

.file-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  padding: 10px;
}

.file-item {
  position: relative;
  width: 260px;
  padding: 8px 12px;
  margin: 4px 0;
  background: var(--secondary-bg);
  border-radius: 8px;
}

.file-item.is-image {
  width: 68px;
  padding: 0;
  margin: 4px 0;
}

.file-wrapper {
  position: relative;
  width: 100%;
  height: 100%;
}

.file-icon {
  width: 68px;
  height: 68px;
  object-fit: cover;
  border-radius: 4px;
}

.file-wrapper video.file-icon {
  background: #000;
}

.remove-btn {
  position: absolute;
  top: -8px;
  right: -8px;
  width: 16px;
  height: 16px;
  padding: 0;
  border: none;
  background: #545454;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  line-height: 1;
  color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.remove-btn:hover {
  opacity: 0.8;
}

.file-info {
  margin-top: 8px;
}

.file-name {
  display: block;
  max-width: 150px;
  color: var(--primary-text);
  font-size: 14px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.file-info .file-name {
  max-width: 150px;
  color: var(--primary-text);
}

.file-name:hover {
  cursor: pointer;
}

.file-size {
  display: block;
  color: var(--primary-text);
  font-size: 12px;
  margin-top: 4px;
}

.add-more-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 68px;
  height: 68px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  background: transparent;
  cursor: pointer;
  transition: all 0.3s;
  margin: 4px 0;
}

.add-more-btn:hover {
  border-color: #1677ff;
  background: #f0f7ff;
}

/* 欢迎区域样式 */
.welcome-section {
  max-width: 800px;
  margin: 0 auto;
  width: 50%;
}

.welcome-header {
  display: flex;
  align-items: flex-start;
  gap: 16px;
  margin-bottom: 24px;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
}
.avatar img{
  width: 100%;
  height: 100%;
  border-radius: 50%;
}
.welcome-info {
  flex: 1;
}

.welcome-info h2 {
  font-size: 20px;
  font-weight: 500;
  color: rgba(0, 0, 0, 0.88);
  margin: 0 0 4px 0;
}

.welcome-info p {
  font-size: 14px;
  color: rgba(0, 0, 0, 0.45);
  margin: 0;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.icon-btn {
  padding: 8px;
  border: none;
  background: transparent;
  cursor: pointer;
  color: rgba(0, 0, 0, 0.45);
}

/* 建议区域样式 */
.suggestion-section {
  margin-top: 70px;
}

.suggestion-section h3 {
  font-size: 14px;
  color: rgba(0, 0, 0, 0.45);
  margin-bottom: 16px;
}

.cards-container {
  display: flex;
  gap: 16px;
}

.suggestion-card {
  flex: 1;
  border-radius: 8px;
  padding: 16px;
  background: #ffffff; /* 替换 var(--ant-color-bg-container) */
  border-radius: 8px; /* 替换 var(--ant-border-radius-lg) */
  transition: border 0.3s, background 0.3s; /* 替换 var(--ant-motion-duration-slow) */
  border: 1px solid #f0f0f0; /* 替换合的 border 属性 */
}

.loading-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 32px;
    height: 32px;
    background: #4d7cff;
    border-radius: 50%;
    position: relative;
  }

  .loading-square {
    width: 14px;
    height: 14px;
    background: #fff;
    border-radius: 3px;
    display: block;
    animation: loading-square-blink 1s infinite;
  }

  @keyframes loading-square-blink {
    0%, 100% { opacity: 1; }
    50% { opacity: 0.5; }
  }

:root {
  --ant-color-bg-container: #ffffff;
  --ant-border-radius-lg: 8px;
  --ant-motion-duration-slow: 0.3s;
  --ant-line-width: 1px;
  --ant-line-type: solid;
  --ant-color-border-secondary: #f0f0f0;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.card-header h4 {
  font-size: 16px;
  font-weight: 500;
  color: rgba(0, 0, 0, 0.88);
  margin: 0;
}

.icon.red {
  color: #ff4d4f;
}

.icon.blue {
  color: #1890ff;
}

.card-subtitle {
  font-size: 14px;
  color: rgba(0, 0, 0, 0.45);
  margin-bottom: 16px;
}

.suggestion-items {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.suggestion-item {
  padding: 8px 12px;
  background: #f5f5f5;
  border-radius: 4px;
  font-size: 12px;
  color: rgba(0, 0, 0, 0.88);
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  transition: opacity 0.3s ease;
}

.suggestion-item:hover {
  background: #e8e8e8;
}

.tab-icon {
  width: 16px;
}

.attached-files {
  padding: 16px;
}

.file-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px;
  border-radius: 4px;
}

.file-item:hover {
  background: var(--secondary-bg);
}

.remove-btn {
  margin-left: auto;
  padding: 4px;
  border: none;
  background: transparent;
  cursor: pointer;
  color: var(--primary-text);
}

.remove-btn:hover {
  color: var(--primary-text);
}

.send-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.upload-area {
  /*   border: 2px dashed #d9d9d9; */
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  cursor: pointer;
  transition: border-color 0.3s;
}

/* .upload-area:hover,
.upload-area.drag-over {
  border-color: #1677ff;
} */

.file-item {
  display: flex;
  align-items: center;
  width: 236px;
  height: 68px;
  padding: 0;
  margin: 4px 0;
  background: var(--secondary-bg);
  color: var(--primary-text);
  border-radius: 4px;
}

.file-item .remove-btn {
  margin-left: auto;
  padding: 4px 8px;
  background: transparent;
  border: none;
  cursor: pointer;
}

/* 聊天内容显示框 */
.message-list {
  width: 60%;
  overflow-y: auto;
  overflow-x: hidden;
  padding: 0 20px;
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin: 0px auto 0;
}

.message-item {
  display: flex;
  margin-bottom: 12px;
}

/* 用户消息靠右显示 */
.user {
  display: flex;
  justify-content: flex-end;
}

.message-bubble {
  max-width: 80%;
  padding: 12px 16px;
  border-radius: 12px;
  background: #fff;
 /*  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06); */
}

/* 用户消息的气泡样式 */
.user .message-bubble {
  background: #edf2f7;
  color: rgba(0, 0, 0, 0.88);
}
.assistant{
  flex-direction: column;
}

/* AI消息的气泡样式 */
.assistant .message-bubble {
  background: #f7f7f8;
  color: rgba(0, 0, 0, 0.88);
}

.message-content {
  font-size: 14px;
  line-height: 1.5;
  white-space: pre-wrap;
  word-break: break-word;
}

.right_menu {
  /* 修改现有样式 */
 /*  position: absolute;
  right: 0; */
  margin-top: 64px;
  height: 93%;
  background: #f7f7f8;
  border-left: 1px solid rgba(0, 0, 0, 0.06);
  transform: translateX(0);
  transition: transform 0.3s ease, width 0.3s ease;
  z-index: 2;
  position: relative;
}

.right_menu.collapsed {
  transform: translateX(100%);
  width: 0;
}

/* 当右侧菜单展开时，给聊天区域添加右边距 */
.right_menu:not(.collapsed) + .chat {
  margin-right: 450px;
}

.collapse-left-button{
  position: absolute;
  left: 260px;
  top: 50%;
  transform: translateY(-50%);
  width: 20px;
  height: 40px;
  background: var(--secondary-bg);
  border: 1px solid var(--border-color);
  border-right: none;
  border-radius: 4px 0 0 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  z-index: 2;
  transition: all 0.3s ease;
}

.menu-collapsed {
  left: 0px;
  border-right: 1px solid var(--border-color);
  border-left: none;
  border-radius: 0 4px 4px 0;
}

/* .collapse-button {
  position: absolute;
  left: -20px;
  top: 50%;
  transform: translateY(-50%);
  width: 20px;
  height: 40px;
  background: #fff;
  border: 1px solid rgba(0, 0, 0, 0.06);
  border-right: none;
  border-radius: 4px 0 0 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  z-index: 3;
  transition: left 0.3s ease;
} */

/* .collapse-button.menu-expanded {
  border-right: 1px solid rgba(0, 0, 0, 0.06);
  border-left: none;
  border-radius: 0 4px 4px 0;
} */

/* .collapse-button:hover {
  background: #f5f5f5;
} */

/* .collapse-icon {
  width: 12px;
  height: 12px;
} */

.right-menu-content {
  height: 100%;
  overflow-y: auto;
}

.right_menu.collapsed .right-menu-content {
  display: none;
}

/* 添加打字效果的光标样式 */
/* .assistant .message-content {
  position: relative;
} 

.assistant .message-content::after {
  content: '|';
  position: absolute;
  margin-left: 2px;
  animation: cursor-blink 1s infinite;
}

@keyframes cursor-blink {
  0%, 100% { opacity: 1; }
  50% { opacity: 0; }
}*/

.file-message {
  background: #f7f7f8;
  border-radius: 8px;
  padding: 12px;
  margin-bottom: 8px;
}

.file-info-display {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
}

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

.file-details {
  display: flex;
  flex-direction: column;
}

/* .file-name {
  font-size: 14px;
  color: rgba(0, 0, 0, 0.88);
  margin-bottom: 4px;
} */

.file-size {
  font-size: 12px;
  color: rgba(0, 0, 0, 0.45);
}

.file-action {
  font-size: 12px;
  color: rgba(0, 0, 0, 0.45);
  padding-left: 36px;
}

/* 修改用户消息气泡样式，确保文件信息正确显示 */
.user .message-bubble {
  background: #edf2f7;
  color: rgba(0, 0, 0, 0.88);
}

.user .file-message {
  background: #f7f7f8;
}

/* 图片预览样式 */
.image-preview {
  position: relative;
  width: 200px;
  border-radius: 8px;
  overflow: hidden;
  background: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.preview-image {
  width: 100%;
  height: auto;
  display: block;
}

.image-info {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 8px;
  background: rgba(255, 255, 255, 0.9);
  font-size: 12px;
  color: rgba(0, 0, 0, 0.45);
  text-align: center;
  border-top: 1px solid rgba(0, 0, 0, 0.06);
}

/* 文档显示样式保持不变 */
.file-info-display {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
}

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

.file-details {
  display: flex;
  flex-direction: column;
}

/* .file-name {
  font-size: 14px;
  color: rgba(0, 0, 0, 0.88);
  margin-bottom: 4px;
} */

.file-size {
  font-size: 12px;
  color: rgba(0, 0, 0, 0.45);
}

.file-action {
  font-size: 12px;
  color: rgba(0, 0, 0, 0.45);
  padding-left: 36px;
}

/* 添加音频控制相关样式 */
.audio-controls {
  margin-top: 8px;
}

.audio-btn {
  background: transparent;
  border: none;
  padding: 4px 8px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  transition: background-color 0.2s;
  min-width: 32px;
  height: 32px;
}

.audio-btn:hover {
  background: rgba(0, 0, 0, 0.04);
}

.audio-icon {
  width: 20px;
  height: 20px;
}

/* 音频波形动画样式 */
.wave-animation {
  display: flex;
  align-items: center;
  height: 20px;
  gap: 2px;
}

.wave-bar {
  display: inline-block;
  width: 3px;
  height: 100%;
  background: #1677ff;
  border-radius: 1px;
  animation: wave 1s ease-in-out infinite;
}

.wave-bar:nth-child(1) {
  animation-delay: 0s;
}

.wave-bar:nth-child(2) {
  animation-delay: 0.2s;
}

.wave-bar:nth-child(3) {
  animation-delay: 0.4s;
}

.wave-bar:nth-child(4) {
  animation-delay: 0.6s;
}

@keyframes wave {
  0%,
  100% {
    height: 6px;
  }
  50% {
    height: 18px;
  }
}

.audio-btn {
  background: transparent;
  border: none;
  padding: 4px 8px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  transition: background-color 0.2s;
  min-width: 32px;
  height: 32px;
}

.audio-btn:hover {
  background: rgba(0, 0, 0, 0.04);
}

.audio-icon {
  width: 20px;
  height: 20px;
}
.message-text {
  margin: 0;
  white-space: normal; /* 确保文本会换行 */
  word-wrap: break-word; /* 长单词或 URL 会被断开以适应容器宽度 */
  overflow: auto;
  font-size: 12px;
  line-height: 20px;
}
.message-text ::v-deep p {
  font-size: 12px !important;
  margin: 5px 0 10px;
  padding: 0;
  font-size: inherit;
  line-height: 22px;
  font-weight: inherit;
}
.message-text ::v-deep ol {
  padding-bottom: 10px;
}
.message-text ::v-deep .source-section h3 {
  margin: 20px 0 3px;
  color: #333;
  font-size: 16px;
}
.message-text ::v-deep ol li {
  padding-top: 3px;
}
.message-text ::v-deep ol li a {
  font-size: 14px;
  color: #1296db;
}
.message-text ::v-deep table {
  border-collapse: collapse;
} 
.message-text ::v-deep table th,
.message-text ::v-deep table td {
  border: 1px solid #ddd;
  padding: 8px;
}
.message-text ::v-deep table th {
  background-color: #f2f2f2;  
}
.message-text ::v-deep table td {
  background-color: #fff;
}
.message-text ::v-deep table tr:nth-child(even) {
  background-color: #f2f2f2;
}

/* think标签样式 */
.message-text ::v-deep .think-container {
  margin: 15px 0;
  border-left: 2px solid #e1e5ea;
  border-radius: 0 8px 8px 0;
  background: #fff;
  overflow: hidden;
  position: relative;
}

.message-text ::v-deep .think-header {
  background: #f0f4f8;
  color: #2c3e50;
  padding: 8px 12px;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 13px;
  font-weight: 500;
  border-bottom: 1px solid #e1e8ed;
}

.message-text ::v-deep .think-icon {
  font-size: 14px;
  color: #4a90e2;
}

.message-text ::v-deep .think-title {
  font-weight: 600;
  color: #2c3e50;
}

.message-text ::v-deep .think-content {
  padding:0 10px;
  background: white;
  color: #2c3e50;
  font-size: 12px;
  line-height: 1.7;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial, sans-serif;
}

.message-text ::v-deep .think-content p {
  margin: 6px 0;
  font-size: 12px !important;
  line-height: 1.7;
  color: #61666b;
}

.message-text ::v-deep .think-content h1,
.message-text ::v-deep .think-content h2,
.message-text ::v-deep .think-content h3,
.message-text ::v-deep .think-content h4,
.message-text ::v-deep .think-content h5,
.message-text ::v-deep .think-content h6 {
  margin: 12px 0 8px 0;
  color: #1a365d;
  font-size: 14px;
  font-weight: 600;
}

.message-text ::v-deep .think-content ul,
.message-text ::v-deep .think-content ol {
  margin: 8px 0;
  padding-left: 20px;
}

.message-text ::v-deep .think-content li {
  margin: 4px 0;
  font-size: 13px;
  line-height: 1.6;
  color: #2c3e50;
}

.message-text ::v-deep .think-content code {
  background: #e2e8f0;
  padding: 2px 6px;
  border-radius: 3px;
  font-size: 12px;
  color: #2d3748;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
}

.message-text ::v-deep .think-content pre {
  background: #f7fafc;
  border: 1px solid #e2e8f0;
  border-radius: 4px;
  padding: 12px;
  margin: 8px 0;
  overflow-x: auto;
  font-size: 12px;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
}

.message-text ::v-deep .think-content blockquote {
  border-left: 3px solid #4a90e2;
  margin: 8px 0;
  padding: 8px 12px;
  background: #f0f4f8;
  color: #4a5568;
  font-style: italic;
  border-radius: 0 4px 4px 0;
}

/* 知识源样式 */
.knowledge-sources {
  margin-top: 12px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 8px;
 
}

.knowledge-sources-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
  font-size: 14px;
  font-weight: 500;
  color: #1890ff;
}

.knowledge-sources-header .anticon {
  font-size: 16px;
}


.knowledge-source-group:last-child {
  margin-bottom: 0;
}

.knowledge-source-type {
  font-size: 12px;
  color: #666;
  margin-bottom: 8px;
  padding: 4px 8px;
  background: #e6f7ff;
  border-radius: 4px;
  display: inline-block;
}

.knowledge-source-items {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

/* .knowledge-source-item {
  background: #fff;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
  padding: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
}

.knowledge-source-item:hover {
  border-color: #1890ff;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.15);
  transform: translateY(-1px);
} */

.knowledge-source-content {
  position: relative;
}

.knowledge-source-title {
  font-size: 14px;
  font-weight: 500;
  color: #1890ff;
  margin-bottom: 6px;
  line-height: 1.4;
  cursor: pointer;
  text-decoration: underline;
  transition: color 0.3s ease;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.knowledge-source-title:hover {
  color: #40a9ff;
  text-decoration: underline;
}

.knowledge-source-text {
  font-size: 12px;
  color: #666;
  line-height: 1.5;
  margin-bottom: 8px;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.knowledge-source-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 11px;
  color: #999;
}

.knowledge-source-doc {
  background: #f0f0f0;
  padding: 2px 6px;
  border-radius: 3px;
}

.knowledge-source-score {
  color: #52c41a;
  font-weight: 500;
}

/* 知识源点击效果 */
.knowledge-source-item:active {
  transform: translateY(0);
  box-shadow: 0 1px 4px rgba(24, 144, 255, 0.2);
}
.video-preview {
  position: relative;
  width: 300px;
  border-radius: 8px;
  overflow: hidden;
  background: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  margin-bottom: 8px;
}

.preview-video {
  width: 100%;
  height: auto;
  display: block;
  max-height: 300px;
}

/* 添加 loading 相关样式 */
.upload-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
}

.loading-spinner {
  width: 24px;
  height: 24px;
  border: 2px solid #f3f3f3;
  border-top: 2px solid #1677ff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.file-loading {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1;
}

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

/* 上传区域在上传时的样式 */
.upload-area {
  position: relative;
  cursor: pointer; /* 始终保持指针样式 */
}

.upload-area.uploading {
  opacity: 0.7;
}

/* 添加配置容器的样式 */
.config-container {
  margin-top: 50px;
  border-top: 1px solid rgba(0, 0, 0, 0.06);
}
.config-header {
  padding: 12px 20px;
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.config-header:hover {
  background: rgba(0, 0, 0, 0.02);
}

.config-icon {
  width: 16px;
  height: 16px;
}

.toggle-icon {
  width: 12px;
  height: 12px;
  margin-left: auto;
}


.web-search-toggle {
  display: flex;
  align-items: center;
 /*  margin-left: auto; */
  padding: 0 12px;
}

.toggle-input {
  position: relative;
  width: 36px;
  height: 20px;
  margin-right: 8px;
  appearance: none;
  background: #ccc;
  border-radius: 10px;
  cursor: pointer;
  transition: background 0.3s;
}

.toggle-input:checked {
  background: #1677ff;
}

.toggle-input::before {
  content: "";
  position: absolute;
  top: 2px;
  left: 2px;
  width: 16px;
  height: 16px;
  background: white;
  border-radius: 50%;
  transition: transform 0.3s;
}

.toggle-input:checked::before {
  transform: translateX(16px);
}

.toggle-label {
  font-size: 14px;
  color: var(--primary-text);
  cursor: pointer;
}

.toggle-input:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.toggle-label.disabled {
  color: var(--primary-text);
  cursor: not-allowed;
}

.disabled-hint {
  font-size: 12px;
  color: var(--primary-text);
  margin-left: 4px;
}

/* 添加菜单收缩相关样式 */
.menu {
  /* 现有样式保持不变 */
  transition: width 0.3s ease;
  position: relative;
}

.menu.collapsed {
  width: 0;
  padding: 0;
}

/* 添加收缩按钮样式 */
.collapse-button {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  width: 20px;
  height: 40px;
  background: var(--secondary-bg);
  border: 1px solid var(--border-color);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  z-index: 3;
  transition: right 0.3s ease, left 0.3s ease;
}

.collapse-button:hover {
  background: var(--secondary-bg);
}

.collapse-icon {
  width: 12px;
  height: 12px;
}

/* 添加响应式布局样式 */
@media screen and (max-width: 768px) {
  .layout {
    /* 移动端布局调整 */
    flex-direction: column;
  }

  .menu {
    /* 移动端菜单调整 */
    position: fixed;
    width: 100%;
    height: 93%;
    z-index: 1000;
    transform: translateX(-100%);
  }

  .menu.collapsed {
    transform: translateX(-100%);
  }

  .collapse-left-button {
    z-index: 999;
    /* 移动端收缩按钮调整 */
   /*  display: none; */
  }

  .chat {
    /* 移动端聊天区域调整 */
    width: 100%;
    margin: 0;
    padding: 16px;
    left: 0 !important;
    right: 0 !important;
  }

  .message-list {
    /* 移动端消息列表调整 */
    width: 100%;
    padding: 10px;
  }

  .input-container {
    /* 移动端输入区域调整 */
    width: 98%;
    padding: 10px;
  }

  .cards-container {
    /* 移动端卡片容器调整 */
    flex-direction: column;
  }

  .suggestion-card {
    /* 移动端建议卡片调整 */
    width: 100%;
  }

  .welcome-section {
    /* 移动端欢迎区域调整 */
    width: 100%;
    padding: 0;
  }

  .right_menu {
    /* 移动端右侧菜单调整 */
    position: fixed;
    width: 100%;
    height: 100%;
    z-index: 998;
  }

  .right_menu.collapsed {
    transform: translateX(100%);
  }

  /* 移动端文件预览调整 */
  .image-preview, 
  .video-preview {
    width: 100%;
    max-width: 300px;
  }

  /* 移动端文件列表调整 */
  .file-list {
    justify-content: center;
  }

  .file-item {
    width: 100%;
    max-width: 300px;
  }

  /* 移动端标签栏调整 */
  .tabs-wrapper {
    flex-wrap: wrap;
    gap: 4px;
  }

  .web-search-toggle {
    width: 100%;
    justify-content: flex-start;
    margin-top: 8px;
  }

  /* 移动端消息气泡调整 */
  .message-bubble {
    max-width: 90%;
  }

  .collapse-button {
    left: -20px !important;
  }

  .collapse-button.menu-expanded {
    left: auto !important;
    right: 0;
  }
}

/* 添加移动端手势支持 */
@media (hover: none) and (pointer: coarse) {
  .menu {
    /* 支持触摸滑动 */
    touch-action: pan-y;
  }

  .message-list {
    /* 支持触摸滚动 */
    -webkit-overflow-scrolling: touch;
  }
}

/* 优化移动端字体大小 */
@media screen and (max-width: 480px) {
  .message-content {
    font-size: 14px;
  }

  .suggestion-item {
    font-size: 13px;
  }

  .file-name {
    font-size: 13px;
  }
}

/* 修改现有的响应式样式 */
@media screen and (max-width: 768px) {
  .layout {
    overflow-x: hidden;
  }

  .chat {
    /* 调整聊天区域以保持一致的宽度 */
    padding: 16px 0 ;
    margin: 0;
    width: 100%;
  }

  .message-list {
    /* 保持消息列表的宽度一致 */
    width: 100%;
    max-width: 800px;
    margin: 60px auto 0;
    padding: 0 10px;
  }

  .input-container {
    /* 保持输入区域的宽度一致 */
    width: 95%;
    max-width: 800px;
    margin: 0 auto;
    padding: 0;
  }

  .welcome-section {
    /* 保持欢迎区域的宽度一致 */
    width: 100%;
    max-width: 800px;
    margin: 0 auto;
    /* padding: 0 16px; */
  }

  .cards-container {
    /* 保持卡片布局 */
    flex-direction: row;
    flex-wrap: wrap;
    gap: 16px;
  }

  .suggestion-card {
    /* 调整卡片大小 */
    flex: 1 1 300px;
    min-width: 300px;
  }

  .message-bubble {
    /* 保持消息气泡的样式 */
    max-width: 80%;
    padding: 12px 16px;
  }

  /* 调整文件预览区域 */
  .image-preview,
  .video-preview {
    width: 200px;
    margin: 0 auto;
  }

  /* 调整文件列表布局 */
  .file-list {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    justify-content: flex-start;
  }

  .file-item {
    width: calc(50% - 8px);
    min-width: 200px;
  }

  /* 调整标签栏布局 */
  .tabs-wrapper {
    flex-wrap: nowrap;
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
    padding-bottom: 8px;
  }

  /* 调整搜索开关位置 */
  .web-search-toggle {
    position: relative;
    width: auto;
  }

  /* 调整菜单样式 */
  .menu {
    position: fixed;
    left: 0;
    top: 0;
    bottom: 0;
    width: 260px;
    transform: translateX(-100%);
    transition: transform 0.3s ease;
    z-index: 1000;
  }

  .menu.collapsed {
    transform: translateX(-100%);
  }

  .menu:not(.collapsed) {
    transform: translateX(0);
  }

  /* 调整右侧菜单样式 */
/*   .right_menu {
    position: fixed;
    right: 0;
    top: 0;
    bottom: 0;
    width: 300px;
    transform: translateX(100%);
    transition: transform 0.3s ease;
    z-index: 998;
  } */

  .right_menu.collapsed {
    transform: translateX(100%);
  }

  .right_menu:not(.collapsed) {
    transform: translateX(0);
  }

  /* 添加遮罩层样式 */
  .menu-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    z-index: 999;
    display: none;
  }

  .menu:not(.collapsed) ~ .menu-overlay,
  .right_menu:not(.collapsed) ~ .menu-overlay {
    display: block;
  }
}

/* 添加更细致的断点控制 */
@media screen and (max-width: 480px) {
  .message-content {
    font-size: 14px;
    line-height: 1.5;
  }

  .suggestion-item {
    font-size: 14px;
    padding: 10px;
  }

  .input-wrapper {
    padding:5px;
  }

  .message-input {
    font-size: 14px;
  }
}

/* 确保滚动流畅 */
* {
  -webkit-overflow-scrolling: touch;
}

/* 防止页面横向滚动 */
body {
  overflow-x: hidden;
  width: 100%;
}

/* 优化触摸体验 */
button,
.suggestion-item,
.conversation-item {
  touch-action: manipulation;
}

/* 添加拖动条样式 */
.resize-handle {
  position: absolute;
  left: -5px;
  top: 0;
  width: 10px;
  height: 100%;
  cursor: col-resize;
  background: transparent;
  z-index: 3;
}

.resize-handle:hover {
  background: rgba(0, 0, 0, 0.1);
}

/* 确保拖动时不会选中文本 */
.resize-handle:active {
  user-select: none;
}

/* 移动端样式调整 */
@media screen and (max-width: 768px) {
  .resize-handle {
    display: none;
  }
  
  .right_menu {
    width: 100% !important;
  }
}

.search-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid var(--border-color);
}

.search-header span {
  font-size: 16px;
  font-weight: bold;
}

/* 添加开关样式 */
.web-search-toggle {
  display: flex;
  align-items: center;
  color: var(--primary-text);
}

.toggle-input {
  position: relative;
  width: 36px;
  height: 20px;
  margin-right: 8px;
  appearance: none;
  background: #ccc;
  border-radius: 10px;
  cursor: pointer;
  transition: background 0.3s;
}

.toggle-input:checked {
  background: #1677ff;
}

.toggle-input::before {
  content: "";
  position: absolute;
  top: 2px;
  left: 2px;
  width: 16px;
  height: 16px;
  background: white;
  border-radius: 50%;
  transition: transform 0.3s;
}

.toggle-input:checked::before {
  transform: translateX(16px);
}

.toggle-label {
  font-size: 14px;
  color: rgba(0, 0, 0, 0.88);
  cursor: pointer;
}

/* 添加 Tab 样式 */
.right-menu-tabs {
  display: flex;
  border-bottom: 1px solid #f0f0f0;
  background: var(--secondary-bg);
}

.tab-item {
  flex: 1;
  padding: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  cursor: pointer;
  transition: all 0.3s;
  border-bottom: 2px solid transparent;
  color: rgba(0, 0, 0, 0.65);
}

.tab-item:hover {
  color: #1677ff;
}

.tab-item.active {
  color: #1677ff;
  border-bottom-color: #1677ff;
  background: #f6f9fe;
}

.panel-container {
  height: calc(100% - 45px); /* 减去 tab 的高度 */
  overflow-y: auto;
}

/* 修改右侧菜单内容样式 */
.right-menu-content {
  height: 100%;
  display: flex;
  flex-direction: column;
}

/* 预览面板样式 */
.preview-header {
  padding: 16px;
  border-bottom: 1px solid var(--border-color);
  color: var(--primary-text);
  font-size: 16px;
  font-weight: bold;
}

.search-toggles {
  display: flex;
  gap: 12px;
  padding: 8px 12px;
  /* background: var(--secondary-bg); */
  border-radius: 8px;
  transition: all 0.3s ease;
  justify-content: space-between;

  &.compact {
    .search-toggle-item {
      padding: 6px;
      min-width: auto;
      width: auto;
    }

    .toggle-content {
      gap: 4px;
      justify-content: center;
    }

    .toggle-text {
     /*  display: none; */
    }

    .toggle-switch {
      margin-left: 8px;
    }
  }
}

.search-toggle-item {
  position: relative;
  display: flex;
  align-items: center;
 
  color: var(--primary-text);
  border-radius: 6px;
  padding: 6px;
  transition: all 0.3s;
/*   width: 140px; */

  @media screen and (max-width: 768px) {
    width: auto;
    padding: 6px 8px;
  }

  &:hover {
    background: rgba(0, 0, 0, 0.02);
  }
}

.toggle-content {
  display: flex;
  align-items: center;
  gap: 8px;
  color: rgba(0, 0, 0, 0.65);
  transition: all 0.3s;
  width: 100%;

  .anticon {
    font-size: 16px;
    flex-shrink: 0;
  }

  .toggle-text {
    font-size: 14px;
    transition: all 0.3s;
    white-space: nowrap;
    color: var(--primary-text);
  }
}

.toggle-switch {
  position: relative;
  display: flex;
  align-items: center;
}

.toggle-input {
  position: absolute;
  opacity: 0;
  width: 0;
  height: 0;

  &:checked + .toggle-label {
    .toggle-slider {
      background: #1677ff;
      &:before {
        transform: translateX(16px);
      }
    }
  }

  &:disabled + .toggle-label {
    cursor: not-allowed;
    
    .toggle-slider {
      background: #d9d9d9;
      &:before {
        background: #f5f5f5;
      }
    }
  }
}

.toggle-label {
  display: flex;
  align-items: center;
  cursor: pointer;

  .toggle-slider {
    position: relative;
    width: 36px;
    height: 20px;
    background: #d9d9d9;
    border-radius: 10px;
    transition: all 0.3s;

    &:before {
      content: '';
      position: absolute;
      top: 2px;
      left: 2px;
      width: 16px;
      height: 16px;
      background: white;
      border-radius: 50%;
      transition: transform 0.3s;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    }
  }

  &.disabled {
    cursor: not-allowed;
  }
}

/* 移动端适配 */
@media screen and (max-width: 480px) {
  .search-toggles {
    padding: 6px;
    gap: 6px;
  }

  .search-toggle-item {
    padding: 6px;
  }

  .toggle-content {
    gap: 4px;
  }
}

@media screen and (max-width: 768px) {
  .search-toggles {
    &:not(.compact) {
      .search-toggle-item {
        padding: 6px 8px;
      }

      .toggle-content {
        gap: 4px;
      }

      .toggle-text {
        font-size: 12px;
      }
    }
  }
}

@media screen and (max-width: 480px) {
  .search-toggles {
    padding: 0px;
    gap: 6px;

    &:not(.compact) {
      .toggle-text {
       /*  display: none; */
      }

      .search-toggle-item {
        padding: 6px;
      }
    }
  }
}

/* 深色模式支持 */
@media (prefers-color-scheme: dark) {
  .search-toggle-item {
    background: rgba(255, 255, 255, 0.04);

    &:hover {
      background: rgba(255, 255, 255, 0.08);
    }
  }

  .toggle-content {
    color: rgba(255, 255, 255, 0.65);
  }

  .toggle-label {
    .toggle-slider {
      background: #424242;

      &:before {
        background: #8c8c8c;
      }
    }
  }

  .toggle-input:checked + .toggle-label {
    .toggle-slider {
      background: #1677ff;
      &:before {
        background: white;
      }
    }
  }

  .toggle-input:disabled + .toggle-label {
    .toggle-slider {
      background: #1f1f1f;
      &:before {
        background: #434343;
      }
    }
  }
}

/* 修改右侧菜单面板样式 */
.right_menu {
  position: fixed;
  right: 0;
  top: 0;
  bottom: 0;
  width: 450px;
  background: #fff;
  border-left: 1px solid rgba(0, 0, 0, 0.06);
  display: flex;
  flex-direction: column;
  transition: transform 0.3s ease;
  z-index: 998;
}

.right_menu.collapsed {
  transform: translateX(100%);
}

.right-menu-content {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* Tab 样式调整 */
.right-menu-tabs {
  display: flex;
  background: var(--secondary-bg);
  color: var(--primary-text);
  border-bottom: 1px solid #f0f0f0;
  padding: 0;
  height: 46px;
  flex-shrink: 0;
}

.tab-item {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 12px;
  color: var(--primary-text);
  cursor: pointer;
  transition: all 0.3s;
  border-bottom: 2px solid transparent;
  font-size: 14px;
}

.tab-item.active {
  color: #1677ff;
  border-bottom-color: #1677ff;
  background: rgba(22, 119, 255, 0.04);
}

.tab-item:hover {
  color: #1677ff;
}

/* 面板容器样式 */
.panel-container {
  flex: 1;
  overflow-y: auto;
  background: var(--secondary-bg);
  display: flex;
  flex-direction: column;
}

/* 搜索头部样式 */
.search-header {
  padding: 16px;
  border-bottom: 1px solid var(--border-color);
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: var(--secondary-bg);
  flex-shrink: 0;
}

.search-header span {
  font-size: 16px;
  font-weight: 500;
  color: var(--primary-text);
}

/* 知识库结果面板样式 */
.knowledge-results {
  flex: 1;
  padding: 16px 5px;
  overflow-y: auto;
}

/* 调整聊天区域的右边距 */
.chat {
  transition: right 0.3s ease;
}

.right_menu:not(.collapsed) ~ .chat {
  right: 450px;
}

/* 移动端适配 */
@media screen and (max-width: 768px) {
  .right_menu {
    width: 93%;
  }

  .right_menu:not(.collapsed) ~ .chat {
    right: 100%;
  }

  .tab-item {
    padding: 8px;
  }

  .tab-item .anticon {
    font-size: 16px;
  }

  .tab-item span {
    font-size: 12px;
  }

  .search-header {
    padding: 12px;
  }

  .search-header span {
    font-size: 14px;
  }
}

/* 优化滚动条样式 */
.panel-container::-webkit-scrollbar {
  width: 4px;
}

.panel-container::-webkit-scrollbar-thumb {
  background: rgba(0, 0, 0, 0.1);
  border-radius: 2px;
}

.panel-container::-webkit-scrollbar-track {
  background: transparent;
}

/* 添加阴影效果 */
.right_menu {
  box-shadow: -2px 0 8px rgba(0, 0, 0, 0.06);
}

/* 优化过渡动画 */
.right_menu,
.chat,
.tab-item,
.panel-container {
  transition: all 0.3s ease;
}

/* 确保内容不会溢出 */
.right-menu-content {
  max-height: 100%;
  background-color: var(--secondary-bg) !important;
}

.panel-container {
  max-height: calc(100% - 46px); /* 减去 tab 的高度 */
}

/* 菜单展开时的按钮样式 */
.collapse-button.menu-expanded {
  left: -20px;
  border-right: none;
  border-radius: 4px 0 0 4px;
}

/* 菜单收起时的按钮样式 */
.collapse-button.menu-collapsed {
  left: -20px;
  border-left: none;
  border-radius: 0 4px 4px 0;
}

/* 确保右侧菜单收起时按钮仍然可见 */
.right_menu.collapsed .collapse-button {
  right: auto;
  left: -20px;
}

/* 添加模型选择框样式 */
.model-select {
  background: transparent;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  padding: 4px 8px;
  font-size: 14px;
  color: var(--primary-text);
  cursor: pointer;
  transition: all 0.3s;
  outline: none;
  margin-left: auto;
  width:100%;

  &:hover {
    border-color: #1677ff;
  }

  &:focus {
    border-color: #1677ff;
    box-shadow: 0 0 0 2px rgba(22, 119, 255, 0.1);
  }

  &:disabled {
    background: #f5f5f5;
    cursor: not-allowed;
    color: rgba(0, 0, 0, 0.25);
  }

  option {
    background: white;
    color: rgba(0, 0, 0, 0.88);
  }
}

@media screen and (max-width: 768px) {
  .model-select {
    /* width: 80px; */
    font-size: 12px;
    padding: 2px 4px;
  }
}

/* 全局主题变量 */
:root {
  /* 浅色主题变量 */
  --primary-bg: #f7fafc;
  --secondary-bg: #ffffff;
  --primary-text: #333333;
  --secondary-text: #666666;
  --border-color: #e0e0e0;
  --hover-bg: #f0f0f0;
  --card-bg: #ffffff;
  --shadow-color: rgba(0, 0, 0, 0.1);
  --highlight-color: #1890ff;
  --accent-bg: #e6f7ff;
  --accent-text: #1890ff;
  
  /* 动画时间 */
  --theme-transition: 0.3s ease;
}

/* 深色主题变量 */
:root.dark-theme {
  --primary-bg: #1a1a1a;
  --secondary-bg: #2d2d2d;
  --primary-text: #ffffff;
  --secondary-text: #b3b3b3;
  --border-color: #404040;
  --hover-bg: #363636;
  --card-bg: #2d2d2d;
  --shadow-color: rgba(0, 0, 0, 0.3);
  --highlight-color: #40a9ff;
  --accent-bg: #1f1f1f;
  --accent-text: #40a9ff;
}

/* 主题过渡动画 */
.layout * {
  transition: background-color var(--theme-transition),
              color var(--theme-transition),
              border-color var(--theme-transition),
              box-shadow var(--theme-transition);
}

/* 文档预览测试按钮样式 */
.test-preview-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 6px 12px;
  background: linear-gradient(135deg, #4096ff, #1677ff);
  color: white;
  border-radius: 16px;
  cursor: pointer;
  margin-right: 12px;
  transition: all 0.3s ease;
  font-size: 12px;
  font-weight: 500;
  box-shadow: 0 2px 6px rgba(64, 150, 255, 0.3);
}

.test-preview-btn:hover {
  background: linear-gradient(135deg, #1677ff, #0958d9);
  transform: translateY(-1px);
  box-shadow: 0 4px 10px rgba(64, 150, 255, 0.4);
}

.test-preview-btn .btn-text {
  font-size: 11px;
  white-space: nowrap;
}

/* 主题切换按钮样式 */
.theme-switch {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 28px;
  height: 28px;
  margin-right: 8px;
  padding: 6px;
  border-radius: 50%;
  cursor: pointer;
  transition: all var(--theme-transition);
}

.panel-header {
  width: 100%;
    padding: 10px;
    border-bottom: 1px solid var(--border-color);
    height: 30px;
   /*  display: flex;
    align-items: center;
    justify-content: space-between; */
    background: var(--bg-primary);
}

.panel-header h3 {
    font-size: 16px;
    font-weight: 600;
    color: var(--text-primary);
    margin: 0;
}

.theme-switch:hover {
  background-color: var(--hover-bg);
}

.theme-icon {
  width: 18px;
  height: 18px;
  color: var(--primary-text);
  transition: transform 0.2s ease;
}

.theme-switch:hover .theme-icon {
  transform: scale(1.1);
}

/* 主题图标切换动画 */
.theme-icon-enter-active,
.theme-icon-leave-active {
  transition: transform 0.3s ease, opacity 0.3s ease;
}

.theme-icon-enter-from,
.theme-icon-leave-to {
  opacity: 0;
  transform: scale(0.8) rotate(-45deg);
}

.theme-icon-enter-to,
.theme-icon-leave-from {
  opacity: 1;
  transform: scale(1) rotate(0);
}

/* 应用主题样式到现有组件 */
:deep(.layout) {
  background-color: var(--primary-bg);
  color: var(--primary-text);
}

:deep(.header) {
  background-color: var(--secondary-bg);
  /* border-bottom: 1px solid var(--border-color); */
  box-shadow: var(--shadow-sm)
}

:deep(.menu) {
  background-color: var(--secondary-bg);
  border-right: 1px solid var(--border-color);
}

:deep(.user-info-bar) {
 /*  background-color: var(--secondary-bg); */
  color: var(--primary-text);
}

:deep(.dropdown-menu) {
  background-color: var(--card-bg);
  border: 1px solid var(--border-color);
  box-shadow: 0 2px 8px var(--shadow-color);
}

:deep(.dropdown-item) {
  color: var(--primary-text);
}

:deep(.dropdown-item:hover) {
  background-color: var(--hover-bg);
}

:deep(.suggestion-card) {
  background-color: var(--card-bg);
  border: 1px solid var(--border-color);
}

:deep(.suggestion-item) {
  color: var(--primary-text);
}

:deep(.suggestion-item:hover) {
  background-color: var(--hover-bg);
}

:deep(.message-bubble) {
  background-color: var(--card-bg);
  border: 1px solid var(--border-color);
}

/* 确保主题样式应用到聊天消息 */
:deep(.message-item.user .message-bubble) {
/*   background-color: var(--highlight-color); */
  color: var(--primary-text);
}

:deep(.message-item.assistant .message-bubble) {
  background-color: var(--card-bg);
  color: var(--primary-text);
}

/* 搜索区域样式 */
:deep(.search-section) {
  background-color: var(--card-bg);
  border: 1px solid var(--border-color);
  padding: 20px;
  border-radius: 8px;
}

:deep(.search-input) {
  background-color: var(--primary-bg);
  border: 1px solid var(--border-color);
  color: var(--primary-text);
}

:deep(.search-input:hover),
:deep(.search-input:focus) {
  border-color: var(--highlight-color);
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

/* 提示问题区域样式 */
:deep(.suggestion-section) {
  background-color: var(--card-bg);
  border-radius: 8px;
  padding: 20px;
  margin-top: 35px;
}

:deep(.suggestion-section h3) {
  color: var(--primary-text);
  margin-bottom: 16px;
}

:deep(.cards-container) {
  /* display: grid;
  gap: 16px;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); */
}

:deep(.suggestion-card) {
  background-color: var(--secondary-bg);
  border: 1px solid var(--border-color);
  border-radius: 8px;
  padding: 16px;
  transition: all var(--theme-transition);
}

:deep(.suggestion-card:hover) {
  border-color: var(--highlight-color);
  box-shadow: 0 2px 8px var(--shadow-color);
}

:deep(.card-header) {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

:deep(.card-header h4) {
  color: var(--primary-text);
  margin: 0;
}

:deep(.card-subtitle) {
  color: var(--secondary-text);
  margin-bottom: 12px;
}

:deep(.suggestion-items) {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

:deep(.suggestion-item) {
  padding: 8px 12px;
  border-radius: 4px;
  background-color: var(--primary-bg);
  color: var(--primary-text);
  cursor: pointer;
  transition: all var(--theme-transition);
}

:deep(.suggestion-item:hover) {
  background-color: var(--hover-bg);
  color: var(--highlight-color);
}

/* 保存问题区域样式 */
:deep(.save-question) {
  background-color: var(--card-bg);
  border: 1px solid var(--border-color);
  border-radius: 8px;
  padding: 20px;
  margin-top: 20px;
}

:deep(.save-question-title) {
  color: var(--primary-text);
  margin-bottom: 16px;
  font-weight: bold;
}

:deep(.save-question-input) {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid var(--border-color);
  border-radius: 4px;
  background-color: var(--primary-bg);
  color: var(--primary-text);
  margin-bottom: 8px;
}

:deep(.save-question-input:focus) {
  border-color: var(--highlight-color);
  outline: none;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

/* 搜索结果区域样式 */
:deep(.search-results) {
  background-color: var(--secondary-bg);
  /* border: 1px solid var(--border-color); */
  border-radius: 8px;
 /*  padding: 20px; */
 /*  margin-top: 20px; */
}

:deep(.search-results-title) {
  color: var(--primary-text);
  margin-bottom: 16px;
}

:deep(.no-results) {
  color: var(--secondary-text);
  text-align: center;
  padding: 40px 0;
}

/* 输入框和按钮样式 */
:deep(.ant-input),
:deep(.ant-input-search-button) {
  background-color: var(--primary-bg);
  border-color: var(--border-color);
  color: var(--primary-text);
}

:deep(.ant-input:hover),
:deep(.ant-input:focus) {
  border-color: var(--highlight-color);
}

:deep(.ant-input-search-button) {
  background-color: var(--highlight-color);
  border-color: var(--highlight-color);
  color: #ffffff;
}

:deep(.ant-input-search-button:hover) {
  background-color: var(--highlight-color);
  opacity: 0.9;
}

/* 标签页样式 */
:deep(.ant-tabs-tab) {
  color: var(--secondary-text);
}

:deep(.ant-tabs-tab-active) {
  color: var(--highlight-color) !important;
}

:deep(.ant-tabs-ink-bar) {
  background-color: var(--highlight-color);
}

/* 图标样式适配 */
:deep(.tab-icon) {
  filter: var(--icon-filter);
}

/* 其他已有的样式保持不变 */
</style>

<style>
/* 添加图标滤镜变量 */
:root {
  --icon-filter: none;
}

:root.dark-theme {
  --icon-filter: brightness(0) invert(1);
}
</style>

<style lang="less" scoped>
// ... existing code ...

/* 文档预览样式 */
.document-preview {
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.preview-container {
  display: flex;
  height: 100%;
  gap: 16px;
}

.document-list {
  width: 300px;
  flex-shrink: 0;
  overflow-y: auto;
  padding: 16px;
  border-right: 1px solid var(--border-color);
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 48px 0;
  color: var(--primary-text);

  .empty-icon {
    font-size: 48px;
    margin-bottom: 16px;
  }

  p {
    font-size: 14px;
    margin: 0;
  }
}

.document-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px;
  border-radius: 8px;
  margin-bottom: 8px;
  background: var(--secondary-bg);
  transition: all 0.3s;
  cursor: pointer;

  &:hover {
    background: var(--hover-bg);
  }

  &.active {
    background: var(--primary-bg);
    border: 1px solid var(--primary-color);
  }
}

.document-info {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
}

.doc-icon {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.preview-thumbnail {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

/* .file-icon {
  width: 24px;
  height: 24px;
} */

.info {
  flex: 1;
  min-width: 0;

  .name {
    font-size: 14px;
    color: var(--primary-text);
    margin-bottom: 4px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .size {
    font-size: 12px;
    color: var(--secondary-text);
  }
}

.actions {
  display: flex;
  gap: 8px;
}

.action-btn {
  width: 32px;
  height: 32px;
  border: none;
  background: transparent;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--primary-text);
  transition: all 0.3s;

  &:hover {
    background: rgba(0, 0, 0, 0.04);
    color: var(--primary-color);
  }
}

.direct-preview {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background: var(--secondary-bg);
  border-radius: 8px;
}

.preview-header {
  padding: 16px;
  border-bottom: 1px solid var(--border-color);
  display: flex;
  justify-content: space-between;
  align-items: center;

  span {
    font-size: 16px;
    font-weight: 500;
    color: var(--primary-text);
  }

  .close-btn {
    border: none;
    background: transparent;
    cursor: pointer;
    color: var(--primary-text);
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 8px;
    border-radius: 4px;
    transition: all 0.3s;

    &:hover {
      background: rgba(0, 0, 0, 0.04);
      color: var(--primary-color);
    }
  }
}

.preview-body {
  flex: 1;
  overflow: auto;
  padding: 24px;
  display: flex;
  align-items: flex-start;
  justify-content: center;
}

.preview-image {
  max-width: 100%;
  max-height: 70vh;
  object-fit: contain;
}

.preview-video {
  max-width: 100%;
  max-height: 70vh;
}

.doc-preview {
  width: 100%;
  height: 100%;
  min-height: 500px;
}

:deep(.docx-wrapper) {
  width: 100%;
  height: 100%;
  .docx{
    width: 100% !important;
  }
}

:deep(.excel-wrapper) {
  width: 100%;
  height: 100%;
  overflow: auto;
  
  .excel-container {
    min-width: 100%;
    min-height: 100%;
  }

  .excel-toolbar {
    position: sticky;
    top: 0;
    z-index: 1;
    background: #fff;
    padding: 8px;
    border-bottom: 1px solid #e8e8e8;
  }

  table {
    width: 100%;
    border-collapse: collapse;
    
    th, td {
      padding: 8px;
      border: 1px solid #e8e8e8;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
}

.file-preview {
  text-align: center;
  color: var(--primary-text);

  .large-icon {
    font-size: 64px;
    margin-bottom: 16px;
  }

  p {
    margin: 0;
    font-size: 14px;
  }
}

// 响应式布局
@media screen and (max-width: 768px) {
  .preview-container {
    flex-direction: column;
  }

  .document-list {
    width: 100%;
    border-right: none;
    border-bottom: 1px solid var(--border-color);
  }
}

// ... existing code ...
</style>

<style>
/* 移动端适配样式 */
@media screen and (max-width: 768px) {
  .suggestion-section{
    padding: 20px 0 !important;
  }
  .layout {
    flex-direction: column;
  }

  .header {
    /* padding: 10px; */
  }

  .user-profile-bar {
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    padding: 0 10px;
    flex-wrap: nowrap;
  }

  .logo {
    flex-shrink: 0;
    max-width: 120px;
  }

  .user-info-bar {
    display: flex;
    align-items: center;
    gap: 8px;
    flex: 1;
    justify-content: flex-end;
    min-width: 0;
  }

  .theme-switch {
    flex-shrink: 0;
  }

  .user-info {
    display: flex;
    flex-direction: column;
    font-size: 12px;
    min-width: 0;
    flex: 1;
  }

  .user-name {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    margin: 0;
    line-height: 1.2;
  }

  .avatar {
    flex-shrink: 0;
    width: 32px;
    height: 32px;
    margin-left: 8px;
  }
  .suggestion-item{
    width: 85%;
    margin: 0 auto;
  }

  @media screen and (max-width: 480px) {
    .user-info-bar {
      gap: 4px;
    }
    
    .logo {
      max-width: 150px;
    }

    .avatar {
      width: 28px;
      height: 28px;
      margin-left: 4px;
    }
  }

  .logo {
    margin-bottom: 10px;
  }

  .logo-img {
    width: 60px;
  }

  .user-info-bar {
    width: 100%;
    justify-content: space-between;
  }

  .menu {
    position: fixed;
    top: 60px;
    left: -100%;
    width: 80%;
    height: calc(100vh - 60px);
    z-index: 1000;
    transition: left 0.3s ease;
  }

  .menu.collapsed {
    left: 0;
  }

  .chat {
    width: 100%;
    margin-left: 0;
    padding: 0;
  }

  .message-list {
    padding: 10px;
  }

  .message-bubble {
    max-width: 90%;
  }

  .config-container {
    padding: 10px;
  }

  .cards-container {
    flex-direction: column;
  }

  .suggestion-card {
    width: 90% !important;
    padding: 16px 2px !important;
    margin: 10px  auto !important;
  }

  .collapse-left-button {
    position: fixed;
    top: 70px;
    left: 10px;
    z-index: 1001;
  }
}

/* 针对更小屏幕的优化 */
@media screen and (max-width: 480px) {
  .user-info {
    font-size: 12px;
  }

  .theme-icon {
    width: 20px;
    height: 20px;
  }

  .avatar img {
    width: 30px;
    height: 30px;
  }

  .message-content {
    font-size: 14px;
  }

  .new-conversation-btn {
    padding: 8px;
    font-size: 14px;
  }
}

/* 移动端样式调整 */
@media screen and (max-width: 768px) {
  .layout {
    height: 100vh; /* 使用视口高度 */
    overflow: hidden; /* 防止页面滚动 */
    display: flex;
    flex-direction: column;
  }

  .header {
    flex-shrink: 0; /* 防止header被压缩 */
  }

  .chat {
    flex: 1; /* 占据剩余空间 */
    height: calc(100vh - 60px); /* 减去header高度 */
    overflow-y: auto; /* 内容过多时在chat区域内滚动 */
    -webkit-overflow-scrolling: touch; /* 优化iOS滚动 */
  }

  .message-list {
    height: calc(100% - 120px); /* 减去输入框高度 */
    overflow-y: auto;
  }

  .input-wrapper {
    position: sticky;
    bottom: 0;
    background: var(--primary-bg);
    padding: 10px;
    border-top: 1px solid var(--border-color);
  }

  .resize-handle {
    display: none;
  }
  
  .right_menu {
    width: 100% !important;
  }
}

/* PC端样式保持不变 */
@media screen and (min-width: 769px) {
  .layout {
    height: 100vh;
    display: flex;
    flex-direction: column;
  }

  .chat {
    flex: 1;
    display: flex;
    flex-direction: column;
  }

  .message-list {
    flex: 1;
    overflow-y: auto;
  }
}

.thinking-steps {
    margin-bottom: 15px;
    font-size: 12px;
    color: #666;
/*     border: 1px solid #e8e8e8; */
    border-radius: 8px;
    overflow: hidden;
  }

  .thinking-steps-header {
    background: #f8f9fa;
    padding: 8px 12px;
  /*   border-bottom: 1px solid #e8e8e8; */
  }

  .thinking-title {
    font-weight: 600;
    color: #333;
    font-size: 13px;
  }

  .thinking-step {
 /*    padding: 8px 12px; */
    margin-bottom: 0;
    border-radius: 0;
/*     background: #f5f5f5; */
    transition: all 0.3s ease;
 /*    border-bottom: 1px solid #e8e8e8; */
  }

  .thinking-step:last-child {
    border-bottom: none;
  }

  .step-content {
    margin-bottom: 6px;
    line-height: 1.4;
    color: #333;
    font-style:oblique
  }

  .step-meta {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 11px;
    color: #666;
  }

  .step-type {
    background: #e3f2fd;
    color: #1976d2;
    padding: 2px 6px;
    border-radius: 4px;
    font-weight: 500;
  }

  .step-confidence {
    color: #666;
  }

  .thinking-step.start {
    background: #e8f5e9;
  }

  .thinking-step.text_analysis {
    background: #e3f2fd;
  }

  .thinking-step.planning {
    background: #fff3e0;
  }

  .thinking-step.execution {
    background: #f3e5f5;
  }

  .thinking-step.result {
    background: #e8eaf6;
  }

  .thinking-step.conclusion {
    background: #e0f7fa;
    font-weight: 500;
  }

  /* 新增的思考步骤类型样式 */
  .thinking-step.query_understanding {
    background: #e8f5e9;
    border-left: 3px solid #4caf50;
  }

  .thinking-step.context_analysis {
    background: #e3f2fd;
    border-left: 3px solid #2196f3;
  }

  .thinking-step.data_scope {
    background: #fff3e0;
    border-left: 3px solid #ff9800;
  }

  .thinking-step.business_value {
    background: #f3e5f5;
    border-left: 3px solid #9c27b0;
  }
  .step-header {
            position: relative;
            display: flex;
            align-items: center;
            gap: 12px;
            margin-bottom: 8px;
            padding-left: 12px;
        }

        .step-header::before {
            content: '';
            position: absolute;
            left: 0;
            top: 50%;
            transform: translateY(-50%);
            width: 4px;
            height: 16px;
            background: var(--highlight-color);
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 2px;
        }
        
        .step-icon {
            width: 24px;
            height: 24px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            font-weight: 600;
        }
        
       /*  .step.pending .step-icon {
            background: #e5e7eb;
            color: #6b7280;
        }
        
        .step.running .step-icon {
            background: #3b82f6;
            color: white;
        } */
        
     /*    .step.completed .step-icon {
        
            color: white;
        }
        
        .step.error .step-icon {
            
            color: white;
        } */
        
        .step-name {
            font-weight: 600;
            font-size: 16px;
        }
        
        .step-details {
            color: #6b7280;
            font-size: 14px;
            
        }
        
       /*  .progress-bar {
            width: 100%;
            height: 4px;
            background: #e5e7eb;
            border-radius: 2px;
            margin-top: 8px;
            overflow: hidden;
            margin-left: 36px;
        }
        
        .progress-fill {
            height: 100%;
            background: #10b981;
            transition: width 0.3s ease;
            width: 0%;
        } */

</style>

<style  scoped>
.thinking-steps-stream {
  position: sticky;
  top: 0;
  z-index: 100;
  background: rgba(255, 255, 255, 0.95);
  padding: 10px;
  margin: 10px 0;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

  .thinking-step-stream {
    padding: 8px 12px;
    margin: 4px 0;
    border-radius: 6px;
    background: #f5f5f5;
    font-size: 14px;
    line-height: 1.5;
    opacity: 0;
    transform: translateY(-10px);
    
    &.fade-in {
      animation: fadeInDown 0.3s ease forwards;
    }

    .typing-indicator {
      display: inline-flex;
      align-items: center;
      margin-left: 8px;
      
      span {
        width: 4px;
        height: 4px;
        margin: 0 2px;
        background: #666;
        border-radius: 50%;
        animation: typing 1s infinite ease-in-out;
        
        &:nth-child(1) { animation-delay: 0.2s; }
        &:nth-child(2) { animation-delay: 0.3s; }
        &:nth-child(3) { animation-delay: 0.4s; }
      }
    }
  }
}

@keyframes fadeInDown {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes typing {
  0%, 60%, 100% { transform: translateY(0); }
  30% { transform: translateY(-4px); }
}

/* 推荐问题组件样式 */
.recommended-questions {
  background: #ffffff;
  border: 1px solid #e1f5fe;
  border-radius: 8px;
  padding: 16px;
  margin: 16px 0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.questions-header {
  margin-bottom: 16px;
}

.questions-header .hot-icon {
  width: 16px;
  height: 16px;
  margin-right: 8px;
  vertical-align: middle;
}

.questions-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-right: 8px;
  vertical-align: middle;
}

.questions-subtitle {
  font-size: 12px;
  color: #666;
  margin-top: 4px;
}

.questions-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.question-item {
  padding: 5px 16px;
  background: #f8f9fa;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 14px;
  color: #333;
  line-height: 1.4;
}

.question-item:hover {
  background: #e3f2fd;
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.question-item:nth-child(odd) {
  background: #f1f3f4;
}

.question-item:nth-child(odd):hover {
  background: #e8f5e8;
}

/* FAB 浮动操作按钮样式 */
.fab {
  position: fixed;
  bottom: 10%;
  right: 5%;
  width: 45px;
  height: 45px;
  background: #4096ff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  z-index: 1000;
   opacity: 0.6;
}

/* 响应式定位 - 确保在不同屏幕尺寸下都在合适位置 */
@media (max-width: 768px) {
  .fab {
    bottom: 10%;
    right: 5%;
    width: 45px;
    height: 45px;
     opacity: 0.6;
  }
}

@media (max-width: 480px) {
  .fab {
    bottom: 25%;
    right: 15%;
    width: 40px;
    height: 40px;
     opacity: 0.6;
  }
}

/* 大屏幕优化 */
@media (min-width: 1200px) {
  .fab {
  bottom: 10%;
  right: 5%;
    width: 45px;
    height: 45px;
    opacity: 0.6;
  }
 
}

/* 超宽屏幕优化 */
@media (min-width: 1920px) {
  .fab {
   bottom: 10%;
  right: 5%;
   width: 45px;
    height: 45px;
    opacity: 0.6;
  }
}

.fab:hover {
  transform: scale(1.1);
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.4);
}

/* 三个点的样式 */
.fab .fab-dots {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
  width: 100%;
  height: 100%;
}

.fab .fab-dots span {
  width: 6px;
  height: 6px;
  background: #FFF;
  border-radius: 50%;
  transition: all 0.3s ease;
}

.fab .close {
  position: absolute;
  width: 40px;
  height: 40px;
  background: #4096ff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 1;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  top: 10px;
  left: 50%;
  transform: translateX(-50%);
/*   box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2); */
}

/* 响应式关闭按钮位置调整 */
@media (max-width: 768px) {
  .fab .close {
    width: 35px;
    height: 35px;
    top: 8px;
  }
}

@media (max-width: 480px) {
  .fab .close {
    width: 30px;
    height: 30px;
    top: 6px !important;
  }
}

.fab .close i {
  font-size: 20px;
  color: #FFF;
  transition: transform 0.3s ease;
}

/* 响应式关闭按钮图标尺寸调整 */
@media (max-width: 768px) {
  .fab .close i {
    font-size: 18px;
  }
}

@media (max-width: 480px) {
  .fab .close i {
    font-size: 16px;
  }
}

.fab .option {
  position: absolute;
  width: 40px;
  height: 40px;
  background: #0080cc;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  opacity: 0;
  transform: scale(0) translate(0, 0);
  transition: none; /* 初始化时不使用transition */
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  /* 初始位置在中心 */
  top: 50%;
  left: 50%;
  margin-top: -20px;
  margin-left: -20px;
}

/* 响应式选项按钮尺寸调整 */
@media (max-width: 768px) {
  .fab .option {
    width: 35px;
    height: 35px;
    margin-top: -17.5px;
    margin-left: -17.5px;
  }
}

@media (max-width: 480px) {
  .fab .option {
    width: 30px;
    height: 30px;
    margin-top: -15px;
    margin-left: -15px;
  }
}

/* 当FAB有动画类时启用transition */
.fab.animated .option {
  transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
}

.fab .option i {
  font-size: 20px;
  color: white;
}

/* 响应式图标尺寸调整 */
@media (max-width: 768px) {
  .fab .option i {
    font-size: 18px;
  }
}

@media (max-width: 480px) {
  .fab .option i {
    font-size: 16px;
  }
}

/* .fab .option:hover {
  transform: scale(1.1);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
} */

.open{
  width: 40px;
  height: 40px;
  
}

.open .close{
  top: 0;
}

/* 展开状态 */
.fab.open .close {
  opacity: 1;
  transform: translateX(-50%) scale(1);
  animation: fadeInClose 0.3s ease-out 0.2s both;
}

.fab.open .option {
  opacity: 1;
  transform: scale(1);
}

.fab.open .option.reply {
  transform: translate(-60px, -25px) scale(1);
  animation: expandReply 0.5s cubic-bezier(0.25, 0.46, 0.45, 0.94) 0.1s both;
}

.fab.open .option.love {
  transform: translate(0px, -60px) scale(1);
  animation: expandLove 0.5s cubic-bezier(0.25, 0.46, 0.45, 0.94) 0.2s both;
}

.fab.open .option.delete {
  transform: translate(55px, -25px) scale(1);
  animation: expandDelete 0.5s cubic-bezier(0.25, 0.46, 0.45, 0.94) 0.3s both;
}

/* 响应式展开位置调整 */
@media (max-width: 768px) {
  .fab.open .option.reply {
    transform: translate(-50px, -20px) scale(1);
  }
  
  .fab.open .option.love {
    transform: translate(0px, -50px) scale(1);
  }
  
  .fab.open .option.delete {
    transform: translate(45px, -20px) scale(1);
  }
}

@media (max-width: 480px) {
  .fab.open .option.reply {
    transform: translate(-40px, -15px) scale(1);
  }
  
  .fab.open .option.love {
    transform: translate(0px, -40px) scale(1);
  }
  
  .fab.open .option.delete {
    transform: translate(35px, -15px) scale(1);
  }
}

/* 收缩动画 - 从外向内收缩 */
.fab:not(.open) .option.reply {
  animation: collapseReply 0.4s cubic-bezier(0.55, 0.055, 0.675, 0.19) both;
}

.fab:not(.open) .option.love {
  animation: collapseLove 0.4s cubic-bezier(0.55, 0.055, 0.675, 0.19) 0.1s both;
}

.fab:not(.open) .option.delete {
  animation: collapseDelete 0.4s cubic-bezier(0.55, 0.055, 0.675, 0.19) both;
}
.option-content {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
}
.option-content--below { flex-direction: column; }
.option-content--above { flex-direction: column-reverse; }

.option-icon { font-size: 18px; color: #fff; }
.option-label { font-size: 10px; color: #fff; line-height: 1; }



/* 动画关键帧定义 */
@keyframes expandReply {
  0% {
    transform: scale(0) translate(0, 0);
    opacity: 0;
  }
  20% {
    transform: scale(0.3) translate(-12px, -5px);
    opacity: 0.5;
  }
  40% {
    transform: scale(0.6) translate(-24px, -10px);
    opacity: 0.7;
  }
  60% {
    transform: scale(0.8) translate(-36px, -15px);
    opacity: 0.9;
  }
  80% {
    transform: scale(0.95) translate(-48px, -20px);
    opacity: 1;
  }
  100% {
    transform: scale(1) translate(-60px, -25px);
    opacity: 1;
  }
}

@keyframes expandLove {
  0% {
    transform: scale(0) translate(0, 0);
    opacity: 0;
  }
  20% {
    transform: scale(0.3) translate(0, -12px);
    opacity: 0.5;
  }
  40% {
    transform: scale(0.6) translate(0, -24px);
    opacity: 0.7;
  }
  60% {
    transform: scale(0.8) translate(0, -36px);
    opacity: 0.9;
  }
  80% {
    transform: scale(0.95) translate(0, -48px);
    opacity: 1;
  }
  100% {
    transform: scale(1) translate(0, -60px);
    opacity: 1;
  }
}

@keyframes expandDelete {
  0% {
    transform: scale(0) translate(0, 0);
    opacity: 0;
  }
  20% {
    transform: scale(0.3) translate(11px, -5px);
    opacity: 0.5;
  }
  40% {
    transform: scale(0.6) translate(22px, -10px);
    opacity: 0.7;
  }
  60% {
    transform: scale(0.8) translate(33px, -15px);
    opacity: 0.9;
  }
  80% {
    transform: scale(0.95) translate(44px, -20px);
    opacity: 1;
  }
  100% {
    transform: scale(1) translate(55px, -25px);
    opacity: 1;
  }
}

@keyframes collapseReply {
  0% {
    transform: translate(-60px, -25px) scale(1);
    opacity: 1;
  }
  20% {
    transform: translate(-48px, -20px) scale(0.95);
    opacity: 0.9;
  }
  40% {
    transform: translate(-36px, -15px) scale(0.8);
    opacity: 0.7;
  }
  60% {
    transform: translate(-24px, -10px) scale(0.6);
    opacity: 0.5;
  }
  80% {
    transform: translate(-12px, -5px) scale(0.3);
    opacity: 0.3;
  }
  100% {
    transform: translate(0, 0) scale(0);
    opacity: 0;
  }
}

@keyframes collapseLove {
  0% {
    transform: translate(0px, -60px) scale(1);
    opacity: 1;
  }
  20% {
    transform: translate(0px, -48px) scale(0.95);
    opacity: 0.9;
  }
  40% {
    transform: translate(0px, -36px) scale(0.8);
    opacity: 0.7;
  }
  60% {
    transform: translate(0px, -24px) scale(0.6);
    opacity: 0.5;
  }
  80% {
    transform: translate(0px, -12px) scale(0.3);
    opacity: 0.3;
  }
  100% {
    transform: translate(0, 0) scale(0);
    opacity: 0;
  }
}

@keyframes collapseDelete {
  0% {
    transform: translate(55px, -25px) scale(1);
    opacity: 1;
  }
  20% {
    transform: translate(44px, -20px) scale(0.95);
    opacity: 0.9;
  }
  40% {
    transform: translate(33px, -15px) scale(0.8);
    opacity: 0.7;
  }
  60% {
    transform: translate(22px, -10px) scale(0.6);
    opacity: 0.5;
  }
  80% {
    transform: translate(11px, -5px) scale(0.3);
    opacity: 0.3;
  }
  100% {
    transform: translate(0, 0) scale(0);
    opacity: 0;
  }
}

@keyframes fadeInClose {
  0% {
    transform: translateX(-50%) scale(0);
    opacity: 0;
  }
  100% {
    transform: translateX(-50%) scale(1);
    opacity: 1;
  }
}

/* 深色主题适配 */
.dark-theme .fab {
  background: #ffd700;
}

.dark-theme .fab .option {
  background: #8b5cf6;
}

.dark-theme .fab .close i {
  color: #333;
}

/* 深色主题下的思考步骤样式 */
.dark-theme .thinking-steps {
  border-color: #404040;
  background: #1f1f1f;
}

.dark-theme .thinking-steps-header {
  background: #2d2d2d;
  border-color: #404040;
}

.dark-theme .thinking-title {
  color: #e0e0e0;
}

.dark-theme .thinking-step {
  background: #2d2d2d;
  border-color: #404040;
}

.dark-theme .step-content {
  color: #e0e0e0;
}

.dark-theme .step-type {
  background: #1e3a5f;
}

/* 深色主题下的think标签样式 */
.dark-theme .message-text ::v-deep .think-container {
  border-left-color: #60a5fa;
  background: #1a202c;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.4);
}

.dark-theme .message-text ::v-deep .think-header {
  background: #2d3748;
  color: #e2e8f0;
  border-bottom-color: #4a5568;
}

.dark-theme .message-text ::v-deep .think-icon {
  color: #60a5fa;
}

.dark-theme .message-text ::v-deep .think-title {
  color: #e2e8f0;
}

.dark-theme .message-text ::v-deep .think-content {
  background: #2d3748;
  color: #e2e8f0;
}

.dark-theme .message-text ::v-deep .think-content p {
  color: #e2e8f0;
}

.dark-theme .message-text ::v-deep .think-content h1,
.dark-theme .message-text ::v-deep .think-content h2,
.dark-theme .message-text ::v-deep .think-content h3,
.dark-theme .message-text ::v-deep .think-content h4,
.dark-theme .message-text ::v-deep .think-content h5,
.dark-theme .message-text ::v-deep .think-content h6 {
  color: #f7fafc;
}

.dark-theme .message-text ::v-deep .think-content li {
  color: #e2e8f0;
}

.dark-theme .message-text ::v-deep .think-content code {
  background: #4a5568;
  color: #f7fafc;
}

.dark-theme .message-text ::v-deep .think-content pre {
  background: #1a202c;
  border-color: #4a5568;
  color: #e2e8f0;
}

.dark-theme .message-text ::v-deep .think-content blockquote {
  border-left-color: #60a5fa;
  background: #2d3748;
  color: #a0aec0;
}
/*   color: #64b5f6;
} */

.dark-theme .step-confidence {
  color: #b0b0b0;
}

/* .fab .option.reply {
    left: calc((100% / 3) - 3px);
}

.fab .option.love {
    left: calc(50% - 3px);
}

.fab .option.delete {
    left: calc(((100% / 3) * 2) - 3px);
}
 */
 :deep(.anticon-credit-card) {
  color: #fff;
}
:deep(.anticon-audit) {
  color: #fff;
}
:deep(.anticon-profile) {
  color: #fff;
}
</style>