<template>
  <div class="layout">
    <!-- 添加密码修改弹窗组件 -->
    <ChangePasswordDialog
      v-model:visible="showPasswordDialog"
    />
    
    <div class="header">
      <div class="user-profile-bar">
         <div class="logo">
          <img
            src="../assets/logos.JPG"
            
            alt="logo"
            class="logo-img"
          />
       <!--  <span>Raycos Tech</span> -->
      </div>
      <div class="user-info-bar">
        <div class="user-info" @click="toggleDropdown">
          <div class="user-name">商户名称：{{ userInfo.merchant?.merchant_name || '未登录用户' }}</div>
          <div class="user-name">当前用户：{{ 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 按钮 -->
      <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"
          :key="conversation.id"
          :class="[
            'conversation-item',
            { active: currentConversationId === conversation.id },
          ]"
          @click="switchConversation(conversation.id)"
        >
          {{ conversation.title }}
        </div>
      </div>

      <!-- 添加模型配置和语音配置的容器 -->
      <div class="config-container">
        <KnowledgeConfig />
        <ModelConfig />
        <VoiceConfig />
      </div>
    </div>

    <div class="chat">
      <!-- 欢迎消息 -->
      <div v-if="messages.length === 0" class="welcome-section">
        <!-- 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>推荐问题</h4>
              </div>
              <p class="card-subtitle">为您精选的热门问题</p>
              <div class="suggestion-items">
                <!-- 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>
            <!-- 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-else class="message-list" ref="messageList">
        <div
          v-for="message in messages"
          :key="message.id"
          :class="[
            'message-item',
            message.role === 'user' ? 'user' : 'assistant',
          ]"
        >
          <div class="message-bubble">
            <div class="message-content">
              <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'"
                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>
      </div>

      <!-- 输入框 -->
      <div class="input-container">
        <!-- 搜索开关组 -->
        <div class="search-toggles" :class="{ 'compact': isCompact }">
          <div class="search-toggle-item">
            <div class="toggle-content">
              <GlobalOutlined />
              <span class="toggle-text" v-show="!isCompact">互联网</span>
              <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">
            <div class="toggle-content">
              <DatabaseOutlined />
              <span class="toggle-text" v-show="!isCompact">知识库</span>
              <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">
            <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" -->
          <button
            class="send-btn"
            @click="sendMessage"
            :disabled="!inputContent && attachedFiles.length === 0"
          >
            <img src="../assets/svg/up.svg" alt="send" />
          </button>
        </div>
      </div>
    </div>

    <div 
      class="right_menu" 
      :class="{ 
        collapsed: !isRightMenuVisible
      }" 
      :style="{ width: rightMenuWidth + 'px' }"
    >
    <!-- 修改收缩按钮的位置和样式 -->
    <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="collapse-button" 
        :class="{ 'menu-expanded': !isRightMenuCollapsed }"
        :style="!isRightMenuCollapsed ? { left: `-20px` } : {}"
        @click="toggleRightMenu"
      >
        <img
          :src="isRightMenuCollapsed ? leftIcon : rightIcon"
          alt="toggle"
          class="collapse-icon"
        />
      </div> -->
      <div class="right-menu-content">
        <!-- 添加 Tab 切换 -->
        <div class="right-menu-tabs">
          <div 
            class="tab-item" 
            :class="{ active: activeTab === 'search' }"
            @click="activeTab = 'search'"
          >
            <FileSearchOutlined />
            <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 === 'preview' }"
            @click="activeTab = 'preview'"
          >
            <FileOutlined />
            <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>
          <DocumentPreview 
            :documents="attachedFiles"
            @select="handleDocumentSelect"
          />
        </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>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, nextTick, onUnmounted, onMounted, computed } from "vue";
import {
  PlusOutlined,
  FireOutlined,
  ReadOutlined,
  HeartOutlined,
  SmileOutlined,
  CommentOutlined,
  CloudUploadOutlined,
  PaperClipOutlined,
  ShareAltOutlined,
  EllipsisOutlined,
  CloseOutlined,
  FileOutlined,
  ArrowUpOutlined,
  UploadOutlined,
  FileSearchOutlined,
  GlobalOutlined,
  DatabaseOutlined,
  FolderOutlined,
  SelectOutlined,
} 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 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 { useRouter } from 'vue-router'
import { message } from 'ant-design-vue';

// 初始化 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 conversations = ref([
  {
    id: 1,
    title: "当前会话",
    messages: [],
  },
]);

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

// 添加音频播放相关的响应式变量
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(true);

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

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

//知识库搜索
const enableKnowledgeSearch = ref(false);
const knowledgeResults = ref([]);
const knowledgeTotal = ref(0);
const isKnowledgeLoading = ref(false);

// 检测设备类型
const checkMobile = () => {
  isMobile.value = window.innerWidth <= 768;
};


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

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 ? '0' : '260px';
  }
};

// 修改右侧菜单切换逻辑
const toggleRightMenu = () => {
  isRightMenuCollapsed.value = !isRightMenuCollapsed.value;
  
  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`,
      {
        headers: {
          'Authorization': `JWT ${localStorage.getItem('token')}`
        }
      }
    );
    console.log("API Response:", response.data);

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

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

  const updateItems = () => {
    if (!documentSummary.value?.length) {
      console.log("No document summary data available");
      return;
    }

    // 处理第一项数据（Hot Topics）
    try {
      const hotTopicsData = documentSummary.value[0];
      if (hotTopicsData?.questions) {
        const parsedQaPairs =
          /* JSON.parse( */ hotTopicsData.questions; /* .replace(/'/g, '"')); */
        const formattedQaPairs = parsedQaPairs.map((question) => ({
          question,
        }));
        // 随机选择3个问题
        const shuffled = [...formattedQaPairs].sort(() => 0.5 - Math.random());
        currentQaPairs.value = shuffled.slice(0, 3);
      }
    } catch (error) {
      console.error("解析 Hot Topics 失败:", error);
    }

    // 处理第二项数据（Design Guide）
    try {
      const designGuideData = documentSummary.value[1];
      if (designGuideData?.questions) {
        const parsedGuides =
          /* JSON.parse( */ designGuideData.questions; /* .replace(/'/g, '"')); */
        const formattedGuides = parsedGuides.map((question) => ({ question }));
        // 随机选择3个指南
        const shuffled = [...formattedGuides].sort(() => 0.5 - Math.random());
        currentDesignGuides.value = shuffled.slice(0, 3);
      }
    } catch (error) {
      console.error("解析 Design Guide 失败:", error);
    }
  };

  // 初始更新
  updateItems();

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

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

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


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

const removeFile = (file) => {
  attachedFiles.value = attachedFiles.value.filter((f) => f !== file);
};

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;

  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';
      /* expandRightMenu(); */
    }
  }

  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 sendMessage = async () => {
  // 检查登录状态
  const token = localStorage.getItem('token');
  if (!token) {
    router.push('/login');
    return;
  }

  if (
    (!inputContent.value.trim() && attachedFiles.value.length === 0) ||
    isTyping.value
  )
    return;

  // 保存当前输入内容
  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: messageContent,
    displayContent: messageContent,
    files: attachedFiles.value.map((file) => ({
      name: file.name,
      size: file.sizeFormatted,
      type: file.type,
      url: file.url,
    })),
  };
  messages.value.push(userMessage);
  scrollToBottom();

  // 添加临时AI消息
  const tempAiMessage = {
    id: Date.now() + 1,
    role: "assistant",
    content: "Thinking...",
    displayContent: "Thinking...",
    isLoading: true,
  };
  messages.value.push(tempAiMessage);
  scrollToBottom();

  try {
    // 根据开关状态选择不同的 API 端点
    const apiEndpoint = enableWebSearch.value
      ? `${import.meta.env.VITE_BASE_AI_API}/api/chat/web-search-llm/`
      : `${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: "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')}`
      }
    }
  );

    // 移除临时消息
    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;

    // 更新 session_id
    if (sessionId) {
      session_id.value = sessionId;
    }

    // 创建新的AI消息
    const aiMessage = reactive({
      id: Date.now() + 2,
      role: "assistant",
      content: messageContent,
      displayContent: "",
      audioData: audioInfo || null,
    });
    messages.value.push(aiMessage);

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

    // 显示打字效果
    await typeMessage(aiMessage);
    
  } 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: "Sorry, there was an error processing your request.",
      displayContent: "Sorry, there was an error processing your request.",
    });
  } finally {
    isTyping.value = false;
    await nextTick();
    scrollToBottom();
  }
};

// 修改 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",
      }
    );

    if (response.data && response.data.code === 200) {
      searchResults.value = response.data.data.results || [];
      searchTotal.value = response.data.data.total_results || 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 delay = 30; // 打字延迟时间
    let i = 0;
    message.displayContent = ""; // 确保开始时是空的

    const typeChar = () => {
      if (i < message.content.length) {
        message.displayContent = message.content.substring(0, i + 1);
        i++;
        nextTick(() => {
          scrollToBottom();
          setTimeout(typeChar, delay);
        });
      } else {
        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);
  messages.value = conversation ? conversation.messages : [];
  session_id.value = ""; // 重置 session_id
};

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';
      /* expandRightMenu(); */
    }
  }

  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 "";
  return md.render(content);
};

// 添加新的响应式变量
const rightMenuWidth = ref(450); // 默认宽度
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`;
    }
  };
  
  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(() => {
    // 移除搜索开关对菜单显示的影响
    return !isRightMenuCollapsed.value;
    /* return (!isRightMenuCollapsed.value && (
      (enableWebSearch.value && activeTab.value === 'search') ||
      (enableKnowledgeSearch.value && activeTab.value === 'knowledge') ||
      (activeTab.value === 'preview' && attachedFiles.value.length > 0)
    )); */
  });

  // 修改知识库搜索开关处理方法
  const handleKnowledgeToggle = (event) => {
    if (event.target.checked) {
      // 开启知识库搜索时关闭互联网搜索
      enableWebSearch.value = false;
      // 切换到知识库标签页
      activeTab.value = 'knowledge';
      
      // 如果有输入内容，执行知识库搜索
      if (inputContent.value.trim()) {
        handleKnowledgeSearch({
          query: inputContent.value,
          page: 1,
          pageSize: 20
        });
      }
    }
  };

  // 修改知识库搜索方法
  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.results || [];
        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) {
      // 开启互联网搜索时关闭知识库搜索
      enableKnowledgeSearch.value = false;
      // 切换到搜索标签页
      activeTab.value = 'search';
      
      // 如果有输入内容，执行互联网搜索
      if (inputContent.value.trim()) {
        currentSearchQuery.value = inputContent.value;
       /*  sendMessageS(inputContent.value).catch((error) => {
          console.error("Web search failed:", error);
        }); */
      }
    }
  };

  // 添加新的响应式变量
  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`);
      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;
  };
 // 用户信息
  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;
    }
  };

 </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: 100%;
  height: 100%;
  background-color: #f7f7f8;
 
}
.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 12px;
}

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

.user-info {
  display: flex;
  flex-direction: column;
  margin-right: 15px;
}

.user-name {
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.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: #333;
  transition: background-color 0.2s;
}

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

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

.menu {
  margin-top: 64px;
  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;
  padding: 24px;
  display: flex;
  flex-direction: column;
  gap: 24px;
  overflow-y: auto;
  overflow-x: hidden;
  margin-left: 0;
  margin-right: 0;
  transition: all 0.3s ease;
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  justify-content: space-between;
}

.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: 24px;
} */

.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 {
  flex: 1;
  padding: 0 8px;
  overflow-y: auto;
}

.conversation-item {
  padding: 12px;
  margin: 4px 0;
  border-radius: 8px;
  color: rgba(0, 0, 0, 0.88);
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.2s;
}

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

.conversation-item.active {
  background: #fff;
  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 {
  width: 50%;
  margin: auto auto 0;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.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 #e5e6eb;
  border-radius: 8px;
  background: white;
}

.message-input {
  flex: 1;
  border: none;
  outline: none;
  padding: 8px;
  font-size: 14px;
  background: transparent;
}

.message-input::placeholder {
  color: rgba(0, 0, 0, 0.45);
}

.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;
}

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

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

.panel-content {
  background: white;
}

.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: rgba(0, 0, 0, 0.88);
}

.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;
  transition: all 0.3s;
}

.upload-area.has-files {
  padding: 12px;
  background: #fff;
}

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

.upload-text {
  font-size: 14px;
  color: rgba(0, 0, 0, 0.88);
  margin-bottom: 4px;
}

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

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

.file-item {
  position: relative;
  width: 260px;
  padding: 8px 12px;
  margin: 4px 0;
  background: #f5f5f5;
  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: rgba(0, 0, 0, 0.88);
  font-size: 14px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.file-info .file-name {
  max-width: 150px;
}

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

.file-size {
  display: block;
  color: rgba(0, 0, 0, 0.45);
  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 属性 */
}
: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: #f5f5f5;
}

.remove-btn {
  margin-left: auto;
  padding: 4px;
  border: none;
  background: transparent;
  cursor: pointer;
  color: rgba(0, 0, 0, 0.45);
}

.remove-btn:hover {
  color: rgba(0, 0, 0, 0.88);
}

.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: #f5f5f5;
  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: 20px;
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin: 30px 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: #fff;
  color: rgba(0, 0, 0, 0.88);
}

/* 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: #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: 2;
  transition: all 0.3s ease;
}

.menu-collapsed {
  left: 0px;
  border-right: 1px solid rgba(0, 0, 0, 0.06);
  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: #fff;
  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;
}
.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: auto;
  border-top: 1px solid rgba(0, 0, 0, 0.06);
}

.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: rgba(0, 0, 0, 0.88);
  cursor: pointer;
}

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

.toggle-label.disabled {
  color: rgba(0, 0, 0, 0.45);
  cursor: not-allowed;
}

.disabled-hint {
  font-size: 12px;
  color: rgba(0, 0, 0, 0.45);
  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: #fff;
  border: 1px solid rgba(0, 0, 0, 0.06);
  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: #f5f5f5;
}

.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: 100%;
    padding: 10px;
  }

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

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

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

  .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: 24px 16px;
    margin: 0;
    width: 100%;
  }

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

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

  .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: 8px;
  }

  .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 #f0f0f0;
}

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

/* 添加开关样式 */
.web-search-toggle {
  display: flex;
  align-items: center;
}

.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: #fff;
}

.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 #f0f0f0;
  font-size: 16px;
  font-weight: bold;
}

.search-toggles {
  display: flex;
  gap: 12px;
  padding: 8px 12px;
  background: rgba(0, 0, 0, 0.02);
  border-radius: 8px;
  margin-bottom: 8px;
  transition: all 0.3s ease;

  &.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;
  background: #fff;
  border-radius: 6px;
  padding: 6px 12px;
  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: #000000a6;
  }
}

.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: 6px;
    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: #fff;
  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: rgba(0, 0, 0, 0.65);
  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: #fff;
  display: flex;
  flex-direction: column;
}

/* 搜索头部样式 */
.search-header {
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #fff;
  flex-shrink: 0;
}

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

/* 知识库结果面板样式 */
.knowledge-results {
  flex: 1;
  padding: 16px;
  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%;
}

.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: rgba(0, 0, 0, 0.88);
  cursor: pointer;
  transition: all 0.3s;
  outline: none;
  margin-left: auto;
  min-width: 120px;

  &: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 {
    min-width: 80px;
    font-size: 12px;
    padding: 2px 4px;
  }
}
</style>
<style lang="less" scoped>
::v-deep .message-content {
  /* 确保 scoped 样式能够渗透到动态生成的内容 */
  h1,
  h2,
  h3,
  h4,
  h5,
  h6 {
    margin-top: 16px;
    margin-bottom: 8px;
    font-weight: 600;
  }

  p {
    margin-bottom: 8px;
  }

  code {
    background: #f5f5f5;
    padding: 2px 4px;
    border-radius: 4px;
    font-family: monospace;
  }

  pre {
    background: #f5f5f5;
    padding: 16px;
    border-radius: 8px;
    overflow-x: auto;
  }

  ul,
  ol {
    padding-left: 24px;
    margin-bottom: 8px;
  }

  blockquote {
    border-left: 4px solid #ddd;
    padding-left: 16px;
    margin: 8px 0;
    color: rgba(0, 0, 0, 0.65);
  }

  a {
    color: #1677ff;
    text-decoration: none;
  }

  a:hover {
    text-decoration: underline;
  }

  table {
    border-collapse: collapse;
    width: 100%;
    margin-bottom: 16px;
  }

  th,
  td {
    border: 1px solid #ddd;
    padding: 8px;
    text-align: left;
  }

  th {
    background: #f5f5f5;
  }
}

.message-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 8px;
  padding-top: 8px;
  border-top: 1px solid rgba(0, 0, 0, 0.06);
}

.message-actions :deep(.export-button) {
  opacity: 0.6;
  transition: opacity 0.2s;
}

.message-actions :deep(.export-button:hover) {
  opacity: 1;
}
</style>