<!--
 * @Author: ysh
 * @Date: 2025-04-07 14:14:05
 * @LastEditors: wrh
 * @LastEditTime: 2025-07-29 17:12:19
-->
<template>
  <div class="app-container">
    <!-- 最外层页面于窗口同宽，使聊天面板居中 -->
    <div class="home-view">
      <!-- 整个聊天面板 -->
      <div class="chat-panel">
        <!-- 左侧的会话列表 -->
        <div class="session-panel">
          <div class="session-header">
            <el-button :icon="Plus" type="primary" class="new-chat-btn" @click="createNewChat">
              开启新对话
            </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="disableEdit(item)"
                    size="small" />
                  <div class="record-actions" v-if="!item.isEditing">
                    <el-dropdown trigger="click" @command="handleAction">
                      <el-button class="action-icon" :icon="MoreFilled" 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.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="MoreFilled" 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="MoreFilled" 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="MoreFilled" 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="MoreFilled" 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="MoreFilled" 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>欢迎使用 AI 助手</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>
                  </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>
              <!-- 加载状态 -->
              <div v-if="isLoading" 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="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.enter.prevent="handleEnter" @keydown.ctrl.enter="handleCtrlEnter"
                class="message-input" resize="none" />
              <div class="input-actions">
                <el-button :icon="Paperclip" circle size="small" class="action-btn" @click="handleFileUpload" />
                <el-button :icon="Promotion" type="primary" circle size="small" class="send-btn"
                  :disabled="!inputMessage.trim() || isLoading" @click="sendMessage" />
              </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 setup name=''>
import { reactive, toRefs, onBeforeMount, onMounted, nextTick, ref, computed, getCurrentInstance } from 'vue'
import { Plus, Delete, User, ChatDotRound, Paperclip, Promotion, MoreFilled, Document, Loading } from '@element-plus/icons-vue'
import { listTopic, getTopic, delTopic, addTopic, updateTopic } from "@/api/llm/topic";
import { listChat, addChat, updateChat } from "@/api/llm/chat";
import { listDocument, uploadDocument } from "@/api/llm/document";
import { getAnswer, getAnswerWithDocument } from "@/api/llm/session";
import { ElMessage, ElMessageBox } from 'element-plus'
import useUserStore from '@/store/modules/user'
import logoImg from '@/assets/images/logo.png'

const { proxy } = getCurrentInstance();
const userStore = useUserStore()

const topicList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const hasRecords = ref(false);
const currentTopicId = ref(null);
const chatMessages = ref([]);
const inputMessage = ref('');
const isLoading = ref(false);
const messageScrollbar = ref(null);
const showNewChatWelcome = ref(false);
const fileInput = ref(null);
const selectedFiles = ref([]);
const isUploading = ref(false);
const documentChatId = ref('');
const messageFileMap = ref(new Map()); // 存储消息对应的文件列表，key为chartId

const classifiedRecent = ref({
  today: [],
  yesterday: [],
  dayBeforeYesterday: [],
  within7Days: [],
  within30Days: []
});
const classifiedMonthly = ref({});

const enableEdit = (item) => {
  item.isEditing = true;
};

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

const handleAction = (command) => {
  const { action, item } = command;
  if (action === 'rename') {
    enableEdit(item);
  } else if (action === 'delete') {
    deleteTopic(item);
  }
};
// 删除话题
const deleteTopic = async (item) => {
  try {
    await ElMessageBox.confirm('确定要删除这个对话吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

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

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

const selectTopic = async (item) => {
  currentTopicId.value = item.topicId;
  await loadChatMessages(item.topicId);
};

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

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

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

const loadMessageFiles = async () => {
  try {
    // 清空之前的文件映射
    messageFileMap.value.clear();
    // 获取所有有chatId的消息
    const messagesWithChartId = chatMessages.value.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) {
          messageFileMap.value.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);
  }
};

const sendMessage = async () => {
  if (!inputMessage.value.trim() || isLoading.value) return;

  if (!currentTopicId.value) {
    await createNewChat();
  }
  showNewChatWelcome.value = false;
  const userMessage = {
    userId: userStore.id,
    input: inputMessage.value,
    topicId: currentTopicId.value,
    inputTime: proxy.parseTime(new Date(), '{y}-{m}-{d}'),
    chatId: documentChatId.value || null
  };

  // 添加用户消息到聊天记录
  chatMessages.value.push(userMessage);
  const messageToSend = inputMessage.value;
  inputMessage.value = '';

  // 暂存文件上传ID，用于后续查询
  const uploadedFileId = documentChatId.value;

  // 清空文档chartId，确保每次上传只对下一条消息有效
  documentChatId.value = '';

  // 清空已上传的文件列表
  selectedFiles.value = [];

  await nextTick();
  scrollToBottom();

  // 自动更改当前topic名称为用户问题
  try {
    // 只有当当前topic名称为"新对话"时才更新为用户问题
    const currentTopic = topicList.value.find(item => item.topicId === currentTopicId.value);
    if (currentTopic && currentTopic.topic === '新对话') {
      await updateTopic({ topicId: currentTopicId.value, topic: messageToSend });
      // 同步本地topicList
      const updateLocalTopic = (list) => {
        for (const item of list) {
          if (item.topicId === currentTopicId.value) {
            item.topic = messageToSend;
          }
        }
      };
      updateLocalTopic(topicList.value);
      Object.values(classifiedRecent.value).forEach(updateLocalTopic);
      Object.values(classifiedMonthly.value).forEach(updateLocalTopic);
    }
  } catch (e) { }

  // 发送消息到后端，得到回答，并更新到数据库
  try {
    isLoading.value = true;

    let answer;
    // 判断是否存在附件，存在则使用getAnswerWithDocument API
    if (uploadedFileId) {
      answer = await getAnswerWithDocument({ topicId: currentTopicId.value, chatId: uploadedFileId, question: userMessage.input });
    } else {
      answer = await getAnswer({ topicId: currentTopicId.value, question: userMessage.input });
    }

    // 使用Vue的响应式更新方法
    const messageIndex = chatMessages.value.length - 1;
    if (messageIndex >= 0) {
      // 使用Vue.set或直接赋值来确保响应式更新
      chatMessages.value[messageIndex] = {
        ...chatMessages.value[messageIndex],
        output: answer[0].content,
        outputTime: proxy.parseTime(new Date(), '{y}-{m}-{d}')
      };
    }

    // 保存到数据库
    const savedMessage = await addChat(chatMessages.value[messageIndex]);

    // 如果保存成功，更新消息的实际ID
    if (savedMessage && savedMessage.chatId) {
      chatMessages.value[messageIndex].chatId = savedMessage.chatId;
    }

    // 如果当前消息包含文件，使用上传时的ID查询文件列表
    if (uploadedFileId) {
      try {
        const fileResponse = await listDocument({ chatId: uploadedFileId });
        if (fileResponse.rows && fileResponse.rows.length > 0) {
          // 使用消息的chatId作为key存储文件列表
          const messageChatId = chatMessages.value[messageIndex].chatId;
          const keyToUse = messageChatId || uploadedFileId;
          messageFileMap.value.set(keyToUse, fileResponse.rows);

          // 确保消息有chatId用于显示
          if (!chatMessages.value[messageIndex].chatId) {
            chatMessages.value[messageIndex].chatId = uploadedFileId;
          }
        }
      } catch (error) {
        console.error('Failed to load files for new message:', error);
      }
    }

    isLoading.value = false;
    await nextTick();
    scrollToBottom();
  } catch (error) {
    ElMessage.error('发送消息失败');
    isLoading.value = false;
  }
};

const handleEnter = () => {
  sendMessage();
};

const handleCtrlEnter = () => {
  inputMessage.value += '\n';
};

const handleFileUpload = () => {
  if (fileInput.value) {
    fileInput.value.click();
  }
};

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

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

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

const removeFile = (index) => {
  selectedFiles.value.splice(index, 1);
};



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

const scrollToBottom = () => {
  if (messageScrollbar.value) {
    const scrollbar = messageScrollbar.value.wrapRef;
    scrollbar.scrollTop = scrollbar.scrollHeight;
  }
};

const formatMessage = (content) => {
  // 简单的消息格式化，可以扩展支持markdown等
  return content.replace(/\n/g, '<br>');
};

const formatMessageTime = (time) => {
  if (!time) return '';
  const date = proxy.parseTime(new Date(time), '{y}-{m}-{d}');
  return date;
};

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 99999,
    topic: null,
    agentId: 0,
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询cmc聊天主题列表 */
const getList = async () => {
  try {
    loading.value = true;
    let response = await listTopic(queryParams.value);
    if (response.total > 0) {
      topicList.value = response.rows;
      total.value = response.total;
      loading.value = false;
      hasRecords.value = true;
      // 分类近期记录

      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)

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

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

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

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

          classifiedMonthly.value[monthKey].push(record)
        }
      })
    }
  } catch (err) {
    console.error('获取数据失败:', err)
  } finally {
    loading.value = false
  }
}

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

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

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

// 生成扁平化消息列表
const flatMessages = computed(() => {
  const arr = []
  for (const msg of chatMessages.value) {
    // 处理用户消息
    if (msg.input && msg.input.trim()) {
      const fileList = msg.chatId ? messageFileMap.value.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),
      })
    }
  }
  return arr
})

onMounted(() => {
  getList();
})
</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;
              }

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

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