<!--
 * @Author: ysh
 * @Date: 2025-04-07 14:14:05
 * @LastEditors: wrh
 * @LastEditTime: 2026-03-10 22:19:16
-->
<template>
  <div class="app-container">
    <!-- 最外层页面于窗口同宽，使聊天面板居中 -->
    <div class="home-view">
      <!-- 整个聊天面板 -->
      <div class="chat-panel">
        <!-- 左侧的会话列表 -->
        <div class="session-panel">
          <div class="session-header">
            <el-button type="primary" class="new-chat-btn" @click="createNewChat" icon="el-icon-plus">
              开启新对话
            </el-button>
          </div>
          <el-divider />
          <el-scrollbar class="session-scrollbar">
            <div id="recent-containers">
              <div v-if="classifiedRecent.today.length > 0">
                <div class="category-title">今天</div>
                <div v-for="item in classifiedRecent.today" :key="item.topicId" class="record"
                  :class="{ active: currentTopicId === item.topicId }" @click="selectTopic(item)">
                  <span v-if="!item.isEditing" class="topic-text">{{ item.topic }}</span>
                  <el-input v-else v-model="item.topic" @blur="disableEdit(item)" @keyup.enter.native="disableEdit(item)"
                    size="small" />
                  <div class="record-actions" v-if="!item.isEditing">
                    <el-dropdown trigger="click" @command="handleAction">
                      <el-button class="action-icon" style="border: none;" icon="el-icon-more"></el-button>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item :command="{ action: 'rename', item }">重命名</el-dropdown-item>
                          <el-dropdown-item :command="{ action: 'delete', item }" divided>删除</el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </div>
                </div>
              </div>
              <div class="spacer" v-if="classifiedRecent.today.length > 0"></div>

              <div v-if="classifiedRecent.yesterday.length > 0">
                <div class="category-title">昨天</div>
                <div v-for="item in classifiedRecent.yesterday" :key="item.topicId" class="record"
                  :class="{ active: currentTopicId === item.topicId }" @click="selectTopic(item)">
                  <span v-if="!item.isEditing" class="topic-text">{{ item.topic }}</span>
                  <el-input v-else v-model="item.topic" @blur="disableEdit(item)" @keyup.enter="disableEdit(item)"
                    size="small" />
                  <div class="record-actions" v-if="!item.isEditing">
                    <el-dropdown trigger="click" @command="handleAction">
                      <el-button class="action-icon" icon="el-icon-more" style="border: none;" />
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item :command="{ action: 'rename', item }">重命名</el-dropdown-item>
                          <el-dropdown-item :command="{ action: 'delete', item }" divided>删除</el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </div>
                </div>
              </div>
              <div class="spacer" v-if="classifiedRecent.yesterday.length > 0"></div>

              <div v-if="classifiedRecent.dayBeforeYesterday.length > 0">
                <div class="category-title">前天</div>
                <div v-for="item in classifiedRecent.dayBeforeYesterday" :key="item.topicId" class="record"
                  :class="{ active: currentTopicId === item.topicId }" @click="selectTopic(item)">
                  <span v-if="!item.isEditing" class="topic-text">{{ item.topic }}</span>
                  <el-input v-else v-model="item.topic" @blur="disableEdit(item)" @keyup.enter="disableEdit(item)"
                    size="small" />
                  <div class="record-actions" v-if="!item.isEditing">
                    <el-dropdown trigger="click" @command="handleAction">
                      <el-button class="action-icon" icon="el-icon-more" style="border: none;" />
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item :command="{ action: 'rename', item }">重命名</el-dropdown-item>
                          <el-dropdown-item :command="{ action: 'delete', item }" divided>删除</el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </div>
                </div>
              </div>
              <div class="spacer" v-if="classifiedRecent.dayBeforeYesterday.length > 0"></div>

              <div v-if="classifiedRecent.within7Days.length > 0">
                <div class="category-title">7天内</div>
                <div v-for="item in classifiedRecent.within7Days" :key="item.topicId" class="record"
                  :class="{ active: currentTopicId === item.topicId }" @click="selectTopic(item)">
                  <span v-if="!item.isEditing" class="topic-text">{{ item.topic }}</span>
                  <el-input v-else v-model="item.topic" @blur="disableEdit(item)" @keyup.enter="disableEdit(item)"
                    size="small" />
                  <div class="record-actions" v-if="!item.isEditing">
                    <el-dropdown trigger="click" @command="handleAction">
                      <el-button class="action-icon" icon="el-icon-more" style="border: none;" />
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item :command="{ action: 'rename', item }">重命名</el-dropdown-item>
                          <el-dropdown-item :command="{ action: 'delete', item }" divided>删除</el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </div>
                </div>
              </div>
              <div class="spacer" v-if="classifiedRecent.within7Days.length > 0"></div>

              <div v-if="classifiedRecent.within30Days.length > 0">
                <div class="category-title">30天内</div>
                <div v-for="item in classifiedRecent.within30Days" :key="item.topicId" class="record"
                  :class="{ active: currentTopicId === item.topicId }" @click="selectTopic(item)">
                  <span v-if="!item.isEditing" class="topic-text">{{ item.topic }}</span>
                  <el-input v-else v-model="item.topic" @blur="disableEdit(item)" @keyup.enter="disableEdit(item)"
                    size="small" />
                  <div class="record-actions" v-if="!item.isEditing">
                    <el-dropdown trigger="click" @command="handleAction">
                      <el-button class="action-icon" icon="el-icon-more" style="border: none;" />
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item :command="{ action: 'rename', item }">重命名</el-dropdown-item>
                          <el-dropdown-item :command="{ action: 'delete', item }" divided>删除</el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </div>
                </div>
              </div>
              <div class="spacer" v-if="classifiedRecent.within30Days.length > 0"></div>
            </div>

            <!-- 按月记录容器 -->
            <div v-if="sortedMonthlyKeys.length > 0">
              <div v-for="monthKey in sortedMonthlyKeys" :key="monthKey">
                <div class="category-title">{{ formatMonth(monthKey) }}</div>
                <div v-for="item in classifiedMonthly[monthKey]" :key="item.topicId" class="record"
                  :class="{ active: currentTopicId === item.topicId }" @click="selectTopic(item)">
                  <span v-if="!item.isEditing" class="topic-text">{{ item.topic }}</span>
                  <el-input v-else v-model="item.topic" @blur="disableEdit(item)" @keyup.enter="disableEdit(item)"
                    size="small" />
                  <div class="record-actions" v-if="!item.isEditing">
                    <el-dropdown trigger="click" @command="handleAction">
                      <el-button class="action-icon" icon="el-icon-more" style="border: none;" />
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item :command="{ action: 'rename', item }">重命名</el-dropdown-item>
                          <el-dropdown-item :command="{ action: 'delete', item }" divided>删除</el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </div>
                </div>
              </div>
              <div class="spacer"></div>
            </div>

            <!-- 空状态 -->
            <div v-if="!hasRecords" class="empty">
              暂无记录
            </div>
          </el-scrollbar>
        </div>
        <!-- 右侧的消息记录 -->
        <div class="message-panel">
          <!-- 消息列表区域 -->
          <div class="message-container">
            <el-scrollbar ref="messageScrollbar" class="message-scrollbar">
              <!-- 欢迎消息：初次进入 -->
              <div v-if="!currentTopicId && chatMessages.length === 0" class="welcome-message">
                <div class="welcome-content">
                  <div class="welcome-icon">🤖</div>
                  <h2>欢迎使用 OA 助手</h2>
                  <p>我是您的智能助手，可以帮您解答问题、分析数据等。</p>
                  <p>请开始您的对话吧！</p>
                </div>
              </div>
              <!-- 新建对话欢迎消息 -->
              <div v-if="showNewChatWelcome && flatMessages.length === 0 && currentTopicId" class="welcome-message">
                <div class="welcome-content">
                  <div class="welcome-icon">🤖</div>
                  <h2>我是您的AI助手，很高兴见到你！</h2>
                  <p>我可以帮你写代码、读文件、写作各种创意内容，请把你的任务交给我吧~</p>
                </div>
              </div>
              <!-- 消息列表 -->
              <div v-for="(msg, idx) in flatMessages" :key="msg.id || idx" class="message-item" :class="msg.type">
                <div class="message-avatar">
                  <div v-if="msg.type === 'user'" class="user-avatar"></div>
                  <div v-else class="ai-avatar">
                    <img :src="logoImg" alt="AI" class="ai-logo" />
                  </div>
                </div>
                <div class="message-content">
                  <div class="message-bubble" :class="msg.type">
                    <div class="message-text" v-html="formatMessage(msg.text)"></div>
                    <div class="message-time">{{ formatMessageTime(msg.time) }}</div>
                    <!-- AI消息的token用量统计 -->
                    <div v-if="msg.type === 'ai' && msg.tokenUsage && msg.tokenUsage.totalTokens > 0"
                      class="token-usage">
                      <span class="token-label">消耗Token:</span>
                      <span class="token-value">{{ msg.tokenUsage.totalTokens }}</span>
                      <span class="token-breakdown">(输入: {{ msg.tokenUsage.promptTokens }}, 输出: {{ msg.tokenUsage.completionTokens }})</span>
                    </div>
                  </div>
                  <!-- 用户消息的文件列表 -->
                  <div v-if="msg.type === 'user' && msg.chatId && msg.fileList && msg.fileList.length > 0"
                    class="message-files">
                    <div class="files-header">
                      <el-icon>
                        <Document />
                      </el-icon>
                      <span>附件 ({{ msg.fileList.length }})</span>
                    </div>
                    <div class="files-list">
                      <div v-for="file in msg.fileList" :key="file.documentId" class="file-item-display">
                        <el-icon class="file-icon">
                          <Document />
                        </el-icon>
                        <span class="file-name">{{ file.path.split("/")[file.path.split("/").length - 1] }}</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <!-- 加载状态：仅在尚未收到首段流内容时显示，避免出现两个AI气泡 -->
              <div v-if="isLoading && !streamingStarted" class="message-item ai">
                <div class="message-avatar">
                  <div class="ai-avatar">
                    <img :src="logoImg" alt="AI" class="ai-logo" />
                  </div>
                </div>
                <div class="message-content">
                  <div class="message-bubble ai">
                    <div class="loading-dots">
                      <span></span><span></span><span></span>
                    </div>
                  </div>
                </div>
              </div>
            </el-scrollbar>
          </div>

          <!-- 输入框区域 -->
          <div class="input-container">
            <!-- 文件列表显示区域 -->
            <div v-if="selectedFiles.length > 0 || isUploading" class="file-list-container">
              <div class="file-list-header">
                <span v-if="isUploading">正在上传文件...</span>
                <span v-else>已上传 {{ selectedFiles.length }} 个文件</span>
                <el-icon v-if="isUploading" class="loading-icon">
                  <Loading />
                </el-icon>
              </div>
              <div class="file-list">
                <div v-for="(file, index) in selectedFiles" :key="index" class="file-item">
                  <div class="file-info">
                    <el-icon class="file-icon">
                      <Document />
                    </el-icon>
                    <span class="file-name">{{ file.name }}</span>
                    <span class="file-size">({{ formatFileSize(file.size) }})</span>
                  </div>
                  <el-button v-if="!isUploading" size="small" circle icon="el-icon-delete" class="remove-btn"
                    @click="removeFile(index)" />
                </div>
              </div>
            </div>

            <div class="input-wrapper">
              <el-input v-model="inputMessage" type="textarea" :rows="1" :autosize="{ minRows: 1, maxRows: 6 }"
                placeholder="输入您的问题..." @keydown.native.enter="handleKeyDown" @keydown.native.ctrl.enter="handleKeyDown"
                class="message-input" resize="none" />
              <div class="input-actions">
                <el-button circle size="small" class="action-btn" @click="handleFileUpload" icon="el-icon-paperclip">
                </el-button>
                <el-button type="primary" circle size="small" class="send-btn" icon="el-icon-s-promotion"
                  :disabled="!inputMessage.trim() || isLoading" @click="sendMessage">
                </el-button>
              </div>
            </div>
            <div class="input-tips">
              <span>按 Enter 发送，Ctrl + Enter 换行</span>
            </div>

            <!-- 隐藏的文件选择input -->
            <input ref="fileInput" type="file" multiple style="display: none" @change="handleFileSelect"
              accept=".txt,.doc,.docx,.pdf,.xlsx,.xls,.ppt,.pptx,.md" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { parseTime } from "@/utils/ruoyi";
import { Message as ElMessage, MessageBox as ElMessageBox } from 'element-ui'
import { listTopic, delTopic, addTopic, updateTopic } from "@/api/llm/topic";
import { listChat, addChat } from "@/api/llm/chat";
import { listDocument, uploadDocument } from "@/api/llm/document";
import { getAnswerStream, getAnswerWithDocumentStream } from "@/api/llm/session";
import logoImg from '@/assets/images/logo.png'
import { marked } from 'marked';

export default {
  name: 'ChatView',
  data() {
    return {
      topicList: [],
      open: false,
      loading: true,
      showSearch: true,
      ids: [],
      single: true,
      multiple: true,
      total: 0,
      title: "",
      hasRecords: false,
      currentTopicId: null,
      chatMessages: [],
      inputMessage: '',
      isLoading: false,
      messageScrollbar: null,
      showNewChatWelcome: false,
      fileInput: null,
      selectedFiles: [],
      isUploading: false,
      documentChatId: '',
      messageFileMap: new Map(), // 存储消息对应的文件列表，key为chartId
      streamingStarted: false,
      classifiedRecent: {
        today: [],
        yesterday: [],
        dayBeforeYesterday: [],
        within7Days: [],
        within30Days: []
      },
      classifiedMonthly: {},
      logoImg: logoImg,
      form: {},
      queryParams: {
        pageNum: 1,
        pageSize: 99999,
        topic: null,
        agentId: 0,
      },
      rules: {}
    };
  },

  mounted() {
    this.fileInput = this.$refs.fileInput;
    this.getList();
  },

  computed: {
    // 获取排序后的月份键
    sortedMonthlyKeys() {
      return Object.keys(this.classifiedMonthly).sort((a, b) => new Date(b) - new Date(a))
    },

    // 生成扁平化消息列表
    flatMessages() {
      const arr = []
      for (const msg of this.chatMessages) {
        // 处理用户消息
        if (msg.input && msg.input.trim()) {
          const fileList = msg.chatId ? this.messageFileMap.get(msg.chatId) || [] : [];
          const userMessage = {
            type: 'user',
            text: msg.input,
            time: msg.inputTime,
            id: msg.chatId || (msg.topicId + '_input_' + msg.inputTime),
            chatId: msg.chatId,
            fileList: fileList
          };
          arr.push(userMessage);
        }
        // 处理AI回答消息
        if (msg.output && msg.output.trim()) {
          arr.push({
            type: 'ai',
            text: msg.output,
            time: msg.outputTime,
            id: msg.chatId ? msg.chatId + '_ai' : (msg.topicId + '_output_' + msg.outputTime),
            tokenUsage: msg.tokenUsage
          })
        }
      }
      return arr
    }
  },
  methods: {
    enableEdit(item) {
      item.isEditing = true;
    },

    async disableEdit(item) {
      item.isEditing = false;
      try {
        await updateTopic(item);
        ElMessage.success('主题更新成功');
      } catch (error) {
        ElMessage.error('主题更新失败');
      }
    },

    handleAction(command) {
      const { action, item } = command;
      if (action === 'rename') {
        this.enableEdit(item);
      } else if (action === 'delete') {
        this.deleteTopic(item);
      }
    },

    // 删除话题
    async deleteTopic(item) {
      try {
        await ElMessageBox.confirm('确定要删除这个对话吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });

        await delTopic(item.topicId);
        ElMessage.success('删除成功');
        this.getList();
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败');
        }
      }
    },

    async createNewChat() {
      // 检查今天是否已有"新对话"
      const todayNewChat = this.classifiedRecent.today.find(item => item.topic === '新对话');
      if (todayNewChat) {
        this.currentTopicId = todayNewChat.topicId;
        await this.loadChatMessages(todayNewChat.topicId);
        this.showNewChatWelcome = true;
        return;
      }
      try {
        const newTopic = {
          topic: '新对话',
          agentId: 0,
        };
        const response = await addTopic(newTopic);
        await this.getList();
        // 自动选中新建的对话
        if (response && response.data && response.data.topicId) {
          this.currentTopicId = response.data.topicId;
          await this.loadChatMessages(response.data.topicId);
        } else if (response && response.topicId) {
          this.currentTopicId = response.topicId;
          await this.loadChatMessages(response.topicId);
        } else {
          // fallback: 选中最新一条
          if (this.topicList.length > 0) {
            this.currentTopicId = this.topicList[0].topicId;
            await this.loadChatMessages(this.topicList[0].topicId);
          }
        }
        this.showNewChatWelcome = true;
      } catch (error) {
        ElMessage.error('创建新对话失败');
      }
    },

    async selectTopic(item) {
      this.currentTopicId = item.topicId;
      await this.loadChatMessages(item.topicId);
    },

    async loadChatMessages(topicId) {
      try {
        const response = await listChat({ topicId: topicId, pageSize: 1000 });
        this.chatMessages = response.rows || [];

        // 同时加载具有文件的对话
        await this.loadMessageFiles();

        await this.$nextTick();
        this.scrollToBottom();
      } catch (error) {
        ElMessage.error('加载消息失败');
      }
    },

    async loadMessageFiles() {
      try {
        // 清空之前的文件映射
        this.messageFileMap.clear();
        // 获取所有有chatId的消息
        const messagesWithChartId = this.chatMessages.filter(msg => msg.chatId);

        // 为每个chartId获取文件列表
        const promises = messagesWithChartId.map(async (msg) => {
          try {
            const fileResponse = await listDocument({ chatId: msg.chatId });
            if (fileResponse.rows && fileResponse.rows.length > 0) {
              this.messageFileMap.set(msg.chatId, fileResponse.rows);
            }
          } catch (error) {
            console.error(`Failed to load files for chatId ${msg.chatId}:`, error);
          }
        });

        await Promise.all(promises);
      } catch (error) {
        console.error('Failed to load message files:', error);
      }
    },

    async sendMessage() {
      if (!this.inputMessage.trim() || this.isLoading) return;

      if (!this.currentTopicId) {
        await this.createNewChat();
      }
      this.showNewChatWelcome = false;
      this.streamingStarted = false;
      const userMessage = {
        userId: this.$store.state.user.id,
        input: this.inputMessage,
        topicId: this.currentTopicId,
        inputTime: this.parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}'),
        chatId: this.documentChatId || null
      };

      this.chatMessages.push(userMessage);
      const userMessageIndex = this.chatMessages.length - 1;
      const messageToSend = this.inputMessage;
      this.inputMessage = '';

      const uploadedFileId = this.documentChatId;
      this.documentChatId = '';
      this.selectedFiles = [];

      await this.$nextTick();
      this.scrollToBottom();

      try {
        const currentTopic = this.topicList.find(item => item.topicId === this.currentTopicId);
        if (currentTopic && currentTopic.topic === '新对话') {
          await updateTopic({ topicId: this.currentTopicId, topic: messageToSend });
          const updateLocalTopic = (list) => {
            for (const item of list) {
              if (item.topicId === this.currentTopicId) {
                item.topic = messageToSend;
              }
            }
          };
          updateLocalTopic(this.topicList);
          Object.values(this.classifiedRecent).forEach(updateLocalTopic);
          Object.values(this.classifiedMonthly).forEach(updateLocalTopic);
        }
      } catch (e) { }

      const aiMessage = {
        userId: this.$store.state.user.id,
        input: '',
        output: '',
        topicId: this.currentTopicId,
        outputTime: this.parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}'),
        tokenUsage: {
          promptTokens: 0,
          completionTokens: 0,
          totalTokens: 0
        }
      };
      this.chatMessages.push(aiMessage);

      const messageIndex = this.chatMessages.length - 1;

      this.isLoading = true;

      const streamParams = {
        topicId: this.currentTopicId,
        question: userMessage.input
      };

      let streamController;
      if (uploadedFileId) {
        streamParams.chatId = uploadedFileId;
        streamController = getAnswerWithDocumentStream(
          streamParams,
          (content) => {
            const that = this;
            if (!that.streamingStarted) that.streamingStarted = true;

            if (!content || !String(content).trim()) {
              return;
            }

            // 直接追加内容，不使用打字机效果
            aiMessage.output += String(content);
            aiMessage.outputTime = that.parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}');
            that.$nextTick(() => that.scrollToBottom());

            if (window.responseTimeout) {
              clearTimeout(window.responseTimeout);
            }
            window.responseTimeout = setTimeout(() => {
              if (that.isLoading) {
                console.log('=== 响应超时强制结束 ===');
                that.isLoading = false;
                if (window.responseTimeout) {
                  clearTimeout(window.responseTimeout);
                  window.responseTimeout = null;
                }
              }
            }, 300000);

          },
          (error) => {
            const that = this;
            console.error('=== 流式回答错误 ===', error);

            if (window.responseTimeout) {
              clearTimeout(window.responseTimeout);
              window.responseTimeout = null;
            }

            if (aiMessage.output === '') {
              aiMessage.output = '抱歉，我暂时无法回答您的问题，请稍后再试。';
            } else {
              aiMessage.output += '\n\n[回答生成中断]';
            }
            that.isLoading = false;

            that.$nextTick(() => {
              that.scrollToBottom();
            });
          },
          async () => {
            const that = this;
            console.log('=== 回答完成 ===');

            if (window.responseTimeout) {
              clearTimeout(window.responseTimeout);
              window.responseTimeout = null;
            }

            try {
              // 保存用户消息
              const savedUserMessage = await addChat({
                ...that.chatMessages[userMessageIndex],
                topicId: that.currentTopicId
              });

              // 保存AI消息
              const savedMessage = await addChat({
                ...aiMessage,
                topicId: that.currentTopicId
              });

              if (savedUserMessage && savedUserMessage.chatId) {
                that.$set(that.chatMessages, userMessageIndex, {
                  ...that.chatMessages[userMessageIndex],
                  chatId: savedUserMessage.chatId
                });
              }

              if (savedMessage && savedMessage.chatId) {
                that.$set(that.chatMessages, messageIndex, {
                  ...that.chatMessages[messageIndex],
                  chatId: savedMessage.chatId
                });
              }

              if (uploadedFileId) {
                try {
                  const fileResponse = await listDocument({ chatId: uploadedFileId });
                  if (fileResponse.rows && fileResponse.rows.length > 0) {
                    const messageChatId = that.chatMessages[messageIndex].chatId;
                    const keyToUse = messageChatId || uploadedFileId;
                    that.messageFileMap.set(keyToUse, fileResponse.rows);

                    if (!that.chatMessages[messageIndex].chatId) {
                      that.$set(that.chatMessages[messageIndex], 'chatId', uploadedFileId);
                    }
                  }
                } catch (error) {
                  console.error('Failed to load files for new message:', error);
                }
              }
            } catch (error) {
              console.error('保存消息失败:', error);
            }

            that.isLoading = false;
            that.$nextTick(() => {
              that.scrollToBottom();
            });
          }
        );
      } else {
        streamController = getAnswerStream(
          streamParams,
          (jsonData, eventType) => {
            const that = this;
            if (!that.streamingStarted) that.streamingStarted = true;

            // 根据事件类型处理不同的响应
            if (eventType === 'error') {
              // 错误事件
              console.error('收到错误事件:', jsonData);
              if (jsonData.errorMessage) {
                aiMessage.output = jsonData.errorMessage;
              }
              return;
            }

            if (eventType === 'completed') {
              // 完成事件，更新最终的token用量
              if (jsonData.promptTokens !== undefined || jsonData.completionTokens !== undefined || jsonData.totalTokens !== undefined) {
                aiMessage.tokenUsage.promptTokens = jsonData.promptTokens || aiMessage.tokenUsage.promptTokens;
                aiMessage.tokenUsage.completionTokens = jsonData.completionTokens || aiMessage.tokenUsage.completionTokens;
                aiMessage.tokenUsage.totalTokens = jsonData.totalTokens || aiMessage.tokenUsage.totalTokens;
              }
              return;
            }

            // 默认处理 answer 事件
            if (!jsonData || !jsonData.content) {
              return;
            }

            // 更新token用量
            if (jsonData.promptTokens !== undefined || jsonData.completionTokens !== undefined || jsonData.totalTokens !== undefined) {
              aiMessage.tokenUsage.promptTokens = jsonData.promptTokens || aiMessage.tokenUsage.promptTokens;
              aiMessage.tokenUsage.completionTokens = jsonData.completionTokens || aiMessage.tokenUsage.completionTokens;
              aiMessage.tokenUsage.totalTokens = jsonData.totalTokens || aiMessage.tokenUsage.totalTokens;
            }

            const content = jsonData.content;

            // 过滤不完整的句子（以逗号、顿号等结尾）
            const trimmed = String(content).trim();
            if (trimmed.length > 0 && trimmed.length < 30) {
              const lastChar = trimmed.charAt(trimmed.length - 1);
              if (lastChar === '，' || lastChar === '、' || lastChar === '：' || lastChar === ':') {
                return;
              }
            }

            // 直接追加内容，不使用打字机效果
            aiMessage.output += trimmed;
            aiMessage.outputTime = that.parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}');
            that.$nextTick(() => that.scrollToBottom());

            if (window.responseTimeout) {
              clearTimeout(window.responseTimeout);
            }
            window.responseTimeout = setTimeout(() => {
              if (that.isLoading) {
                console.log('=== 响应超时强制结束 ===');
                that.isLoading = false;
                if (window.responseTimeout) {
                  clearTimeout(window.responseTimeout);
                  window.responseTimeout = null;
                }
              }
            }, 300000);

          },
          (error) => {
            const that = this;
            console.error('=== 流式回答错误 ===', error);

            if (window.responseTimeout) {
              clearTimeout(window.responseTimeout);
              window.responseTimeout = null;
            }

            if (aiMessage.output === '') {
              aiMessage.output = '抱歉，我暂时无法回答您的问题，请稍后再试。';
            } else {
              aiMessage.output += '\n\n[回答生成中断]';
            }
            that.isLoading = false;

            that.$nextTick(() => {
              that.scrollToBottom();
            });
          },
          async () => {
            const that = this;
            console.log('=== 回答完成 ===');

            if (window.responseTimeout) {
              clearTimeout(window.responseTimeout);
              window.responseTimeout = null;
            }

            try {
              // 保存用户消息
              const savedUserMessage = await addChat({
                ...that.chatMessages[userMessageIndex],
                topicId: that.currentTopicId
              });

              // 保存AI消息
              const savedMessage = await addChat({
                ...aiMessage,
                topicId: that.currentTopicId
              });

              if (savedUserMessage && savedUserMessage.chatId) {
                that.$set(that.chatMessages, userMessageIndex, {
                  ...that.chatMessages[userMessageIndex],
                  chatId: savedUserMessage.chatId
                });
              }

              if (savedMessage && savedMessage.chatId) {
                that.$set(that.chatMessages, messageIndex, {
                  ...that.chatMessages[messageIndex],
                  chatId: savedMessage.chatId
                });
              }
            } catch (error) {
              console.error('保存消息失败:', error);
            }

            that.isLoading = false;
            that.$nextTick(() => {
              that.scrollToBottom();
            });
          }
        );
      }

      window.currentChatController = streamController;
    },
    //格式化消息内容
    formatMessage(content) {
      // 直接使用marked解析markdown内容
      return marked(content);
    },

    handleKeyDown(event) {
      if (event.key === 'Enter') {
        if (event.ctrlKey || event.metaKey) {
          // Ctrl+Enter 或 Cmd+Enter 换行
          this.inputMessage += '\n';
        } else {
          // Enter 发送消息
          event.preventDefault();
          this.sendMessage();
        }
      }
    },

    handleFileUpload() {
      if (this.fileInput) {
        this.fileInput.click();
      }
    },

    async handleFileSelect(event) {
      const files = Array.from(event.target.files);
      if (files.length > 0) {
        // 清空input值，允许选择相同文件
        event.target.value = '';

        // 立即上传文件
        try {
          this.isUploading = true;
          let res = await uploadDocument(files);
          this.documentChatId = res.data.chatId;
          // 上传成功后，将文件添加到已上传列表
          this.selectedFiles = [...this.selectedFiles, ...files];
          ElMessage.success(`成功上传 ${files.length} 个文件`);

        } catch (error) {
          ElMessage.error('文件上传失败');
          console.error('File upload error:', error);
        } finally {
          this.isUploading = false;
        }
      }
    },

    removeFile(index) {
      this.selectedFiles.splice(index, 1);
    },

    formatFileSize(bytes) {
      if (bytes === 0) return '0 B';
      const k = 1024;
      const sizes = ['B', 'KB', 'MB', 'GB'];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    },

    scrollToBottom() {
      if (this.$refs.messageScrollbar) {
        const scrollbar = this.$refs.messageScrollbar;
        // Element UI的el-scrollbar组件内部的滚动容器是wrap DOM元素
        if (scrollbar && scrollbar.wrap) {
          scrollbar.wrap.scrollTop = scrollbar.wrap.scrollHeight;
        }
      }
    },

    formatMessageTime(time) {
      if (!time) return '';
      const date = this.parseTime(new Date(time), '{y}-{m}-{d} {h}:{i}:{s}');
      return date;
    },

    // 数据已在data中定义，这里不再重复

    /** 查询cmc聊天主题列表 */
    async getList() {
      try {
        this.loading = true;
        let response = await listTopic(this.queryParams);
        if (response.total > 0) {
          this.topicList = response.rows;
          this.total = response.total;
          this.hasRecords = true;
        } else {
          // 没有记录时，清空列表
          this.topicList = [];
          this.total = 0;
          this.hasRecords = false;
          // 清空当前选中的话题
          this.currentTopicId = null;
          this.chatMessages = [];
        }
        // 分类近期记录

        const today = new Date()
        today.setHours(0, 0, 0, 0)

        const yesterday = new Date(today)
        yesterday.setDate(yesterday.getDate() - 1)

        const dayBeforeYesterday = new Date(today)
        dayBeforeYesterday.setDate(dayBeforeYesterday.getDate() - 2)

        const sevenDaysAgo = new Date(today)
        sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7)

        const thirtyDaysAgo = new Date(today)
        thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30)

        // 清空之前的分类
        this.classifiedRecent = {
          today: [],
          yesterday: [],
          dayBeforeYesterday: [],
          within7Days: [],
          within30Days: []
        };
        this.classifiedMonthly = {};

        this.topicList.forEach(record => {
          const recordDate = new Date(record.createTime)
          recordDate.setHours(0, 0, 0, 0)

          if (recordDate.getTime() === today.getTime()) {
            this.classifiedRecent.today.push(record)
          } else if (recordDate.getTime() === yesterday.getTime()) {
            this.classifiedRecent.yesterday.push(record)
          } else if (recordDate.getTime() === dayBeforeYesterday.getTime()) {
            this.classifiedRecent.dayBeforeYesterday.push(record)
          } else if (recordDate > sevenDaysAgo) {
            this.classifiedRecent.within7Days.push(record)
          } else if (recordDate > thirtyDaysAgo) {
            this.classifiedRecent.within30Days.push(record)
          } else if (recordDate <= thirtyDaysAgo) {
            const monthKey = this.getMonthKey(recordDate)

            if (!this.classifiedMonthly[monthKey]) {
              this.classifiedMonthly[monthKey] = []
            }

            this.classifiedMonthly[monthKey].push(record)
          }
        })
      } catch (error) {
        console.error('获取话题列表失败:', error)
        ElMessage.error('获取话题列表失败')
      } finally {
        this.loading = false
      }
    },

    // 获取月份键 (yyyy-MM)
    getMonthKey(date) {
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      return `${year}-${month}`
    },

    // 格式化月份显示
    formatMonth(monthKey) {
      const [year, month] = monthKey.split('-')
      return `${year}-${month}`
    },



  }
}
</script>
<style lang="scss" scoped>
.home-view {
  display: flex;
  width: 100%;
  height: calc(100vh - 127px);
  background-color: #f5f5f5;

  .chat-panel {
    display: flex;
    width: 100%;
    height: 100%;
    background-color: white;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    margin: 8px;
    overflow: hidden;

    /* 左侧聊天会话面板*/
    .session-panel {
      background-color: #f8f9fa;
      width: 280px;
      border-right: 1px solid #e9ecef;
      display: flex;
      flex-direction: column;

      .session-header {
        padding: 16px;
        border-bottom: 1px solid #e9ecef;

        .new-chat-btn {
          width: 100%;
          height: 40px;
          border-radius: 8px;
          font-weight: 500;
        }
      }

      .session-scrollbar {
        flex: 1;
        padding: 8px 0;
      }
    }

    /* 右侧消息记录面板*/
    .message-panel {
      flex: 1;
      display: flex;
      flex-direction: column;
      background-color: white;

      .message-container {
        flex: 1;
        position: relative;
        overflow: hidden;

        .message-scrollbar {
          height: 100%;
          padding: 20px;
          overflow-y: auto;

          &::-webkit-scrollbar {
            width: 6px;
          }

          &::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 3px;
          }

          &::-webkit-scrollbar-thumb {
            background: #c1c1c1;
            border-radius: 3px;

            &:hover {
              background: #a8a8a8;
            }
          }
        }

        .welcome-message {
          display: flex;
          justify-content: center;
          align-items: center;
          height: 100%;

          .welcome-content {
            text-align: center;
            max-width: 400px;

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

            h2 {
              color: #333;
              margin-bottom: 12px;
              font-weight: 600;
            }

            p {
              color: #666;
              line-height: 1.6;
              margin-bottom: 8px;
            }
          }
        }

        .message-item {
          display: flex;
          margin-bottom: 24px;
          align-items: flex-start;

          &.user {
            flex-direction: row-reverse;

            .message-content {
              margin-left: 0;
              margin-right: 12px;
            }

            .message-bubble {
              background-color: #eff6ff;
              color: rgb(0, 0, 0);
              border-radius: 18px;
            }
          }

          &.ai {
            .message-bubble {
              background-color: #f8f9fa;
              color: #333;
              border-radius: 18px 18px 18px 4px;
            }
          }

          .message-avatar {
            flex-shrink: 0;
            width: 32px;
            height: 32px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 16px;

            .user-avatar {
              background-color: #007bff;
              color: white;
            }

            .ai-avatar {
              background-color: #fff;
              display: flex;
              align-items: center;
              justify-content: center;
              width: 32px;
              height: 32px;
              border-radius: 50%;
              overflow: hidden;
              border: 1px solid #e9ecef;

              .ai-logo {
                width: 100%;
                height: 100%;
                object-fit: cover;
                border-radius: 50%;
              }
            }
          }

          .message-content {
            flex: 1;
            margin-left: 12px;
            max-width: 70%;
            min-width: 0;

            .message-bubble {
              padding: 12px 16px;
              line-height: 1.5;
              word-wrap: break-word;
              word-break: break-word;
              max-width: 100%;

              .message-text {
                  margin-bottom: 4px;
                  white-space: pre-wrap;
                  overflow-wrap: break-word;
                  line-height: 1.6;

                  /* 表格样式 */
                  table {
                    width: 100%;
                    border-collapse: collapse;
                    margin: 8px 0;
                    font-size: 14px;
                  }

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

                  th {
                    background-color: #f5f5f5;
                    font-weight: 600;
                  }

                  tr:nth-child(even) {
                    background-color: #f9f9f9;
                  }

                  /* 列表样式 */
                  ul,
                  ol {
                    padding-left: 24px;
                    margin: 8px 0;
                  }

                  li {
                    margin-bottom: 4px;
                  }

                  /* 引用样式 */
                  blockquote {
                    border-left: 4px solid #1890ff;
                    padding: 8px 12px;
                    margin: 8px 0;
                    color: #666;
                    background-color: #f8f9fa;
                    border-radius: 0 4px 4px 0;
                  }

                  /* 标题样式 */
                  h1, h2, h3, h4, h5, h6 {
                    margin: 12px 0 8px;
                    font-weight: 600;
                    color: #333;
                  }

                  h1 { font-size: 20px; }
                  h2 { font-size: 18px; }
                  h3 { font-size: 16px; }
                  h4, h5, h6 { font-size: 14px; }

                  /* 链接样式 */
                  a {
                    color: #1890ff;
                    text-decoration: none;
                  }

                  a:hover {
                    text-decoration: underline;
                  }

                  /* 粗体和斜体 */
                  strong {
                    font-weight: 600;
                  }

                  em {
                    font-style: italic;
                  }

                  /* 行内代码 */
                  code {
                    background-color: #f4f4f4;
                    padding: 2px 6px;
                    border-radius: 4px;
                    font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
                    font-size: 14px;
                    color: #e06c75;
                  }
                }

              .message-time {
                font-size: 12px;
                opacity: 0.7;
                text-align: right;
              }

              .token-usage {
                margin-top: 8px;
                padding-top: 8px;
                border-top: 1px dashed #e0e0e0;
                font-size: 12px;
                text-align: right;
                color: #666;

                .token-label {
                  margin-right: 4px;
                }

                .token-value {
                  color: #1890ff;
                  font-weight: 500;
                  margin-right: 4px;
                }

                .token-breakdown {
                  color: #999;
                  font-size: 11px;
                }
              }
            }

            .message-files {
              margin-top: 8px;
              border: 1px solid #e9ecef;
              border-radius: 8px;
              background-color: #f8f9fa;
              padding: 8px;

              .files-header {
                display: flex;
                align-items: center;
                gap: 6px;
                font-size: 12px;
                color: #666;
                margin-bottom: 6px;
                font-weight: 500;

                .el-icon {
                  font-size: 14px;
                }
              }

              .files-list {
                .file-item-display {
                  display: flex;
                  align-items: center;
                  gap: 6px;
                  padding: 4px 8px;
                  background-color: white;
                  border-radius: 4px;
                  margin-bottom: 4px;
                  border: 1px solid #e9ecef;

                  &:last-child {
                    margin-bottom: 0;
                  }

                  .file-icon {
                    color: #666;
                    font-size: 14px;
                  }

                  .file-name {
                    flex: 1;
                    font-size: 12px;
                    color: #333;
                    white-space: nowrap;
                    overflow: hidden;
                    text-overflow: ellipsis;
                  }

                  .file-size {
                    font-size: 11px;
                    color: #999;
                    white-space: nowrap;
                  }
                }
              }
            }
          }
        }

        .loading-dots {
          display: flex;
          gap: 4px;
          padding: 8px 0;

          span {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background-color: #ccc;
            animation: loading 1.4s infinite ease-in-out;

            &:nth-child(1) {
              animation-delay: -0.32s;
            }

            &:nth-child(2) {
              animation-delay: -0.16s;
            }
          }
        }
      }

      .input-container {
        border-top: 1px solid #e9ecef;
        padding: 16px;
        background-color: white;

        .file-list-container {
          margin-bottom: 12px;
          border: 1px solid #e9ecef;
          border-radius: 8px;
          background-color: #f8f9fa;

          .file-list-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 8px 12px;
            border-bottom: 1px solid #e9ecef;
            font-size: 14px;
            font-weight: 500;
            color: #333;

            .loading-icon {
              animation: rotate 1s linear infinite;
              color: #007bff;
              font-size: 16px;
            }
          }

          .file-list {
            max-height: 200px;
            overflow-y: auto;
            padding: 8px;

            .file-item {
              display: flex;
              justify-content: space-between;
              align-items: center;
              padding: 8px 12px;
              margin-bottom: 4px;
              background-color: white;
              border-radius: 6px;
              border: 1px solid #e9ecef;
              transition: all 0.2s ease;

              &:hover {
                border-color: #007bff;
                box-shadow: 0 2px 4px rgba(0, 123, 255, 0.1);
              }

              &:last-child {
                margin-bottom: 0;
              }

              .file-info {
                display: flex;
                align-items: center;
                flex: 1;
                min-width: 0;

                .file-icon {
                  margin-right: 8px;
                  color: #666;
                  font-size: 16px;
                }

                .file-name {
                  font-size: 14px;
                  color: #333;
                  white-space: nowrap;
                  overflow: hidden;
                  text-overflow: ellipsis;
                  margin-right: 8px;
                }

                .file-size {
                  font-size: 12px;
                  color: #999;
                  white-space: nowrap;
                }
              }

              .remove-btn {
                color: #dc3545;
                border: none;
                background: transparent;
                padding: 4px;
                min-height: auto;

                &:hover {
                  background-color: rgba(220, 53, 69, 0.1);
                  color: #dc3545;
                }
              }
            }
          }
        }

        .input-wrapper {
          position: relative;
          border: 1px solid #e9ecef;
          border-radius: 12px;
          padding: 8px;
          background-color: #f8f9fa;

          .message-input {
            border: none;
            background: transparent;
            resize: none;

            :deep(.el-textarea__inner) {
              border: none;
              background: transparent;
              box-shadow: none;
              padding: 8px 60px 8px 8px;
              min-height: 40px;
              max-height: 120px;
            }
          }

          .input-actions {
            position: absolute;
            right: 8px;
            top: 50%;
            transform: translateY(-50%);
            display: flex;
            gap: 8px;

            .action-btn {
              background-color: transparent;
              border: none;
              color: #666;

              &:hover {
                background-color: #e9ecef;
                color: #333;
              }
            }

            .send-btn {
              background-color: #007bff;
              border: none;

              &:hover:not(:disabled) {
                background-color: #0056b3;
              }

              &:disabled {
                background-color: #ccc;
                cursor: not-allowed;
              }
            }
          }
        }

        .input-tips {
          margin-top: 8px;
          text-align: center;
          font-size: 12px;
          color: #999;
        }
      }
    }
  }
}

.category-title {
  padding: 8px 16px;
  font-size: 12px;
  font-weight: 600;
  color: #666;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.record {
  margin: 2px 8px;
  padding: 8px 12px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: space-between;

  &:hover {
    background-color: #e9ecef;

    .record-actions {
      opacity: 1;
    }
  }

  &.active {
    background-color: #007bff;
    color: white;

    .topic-text {
      color: white;
    }
  }

  .topic-text {
    flex: 1;
    font-size: 14px;
    color: #333;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    margin-right: 8px;
  }

  .record-actions {
    opacity: 0;
    transition: opacity 0.2s ease;

    .action-icon {
      width: 20px;
      height: 20px;
      padding: 0;
      border: none;
      background: transparent;
      color: #666;
      font-size: 14px;

      &:hover {
        background-color: rgba(255, 255, 255, 0.8);
        color: #333;
      }
    }
  }
}

.spacer {
  height: 16px;
}

.empty {
  padding: 20px;
  text-align: center;
  color: #999;
  font-size: 14px;
}

@keyframes loading {

  0%,
  80%,
  100% {
    transform: scale(0);
  }

  40% {
    transform: scale(1);
  }
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}

</style>