<!--
 * @Author: wrh
 * @Date: 2025-01-01 00:00:00
 * @LastEditors: wrh
 * @LastEditTime: 2025-09-11 15:58:35
-->
<template>
  <div class="agent-detail-container" v-loading="loading">
    <div v-if="agentInfo" class="detail-content">
      <!-- 智能体头部信息 -->
      <div class="agent-header">
        <div class="agent-basic-info">
          <h2 class="agent-title">{{ agentInfo.agentName }}</h2>
          <p class="agent-description">{{ agentInfo.description || '暂无描述' }}</p>
          <div class="agent-meta-info">
            <span class="meta-item">
              <el-icon>
                <Calendar />
              </el-icon>
              创建时间：{{ agentInfo.createTime }}
            </span>
          </div>
        </div>
      </div>

      <!-- 对话区域 -->
      <div class="chat-section">
        <!-- 话题列表 -->
        <div v-if="topicList.length > 0" class="topic-list">
          <div class="topic-header">
            <h4>历史对话</h4>
          </div>
          <div class="topic-content">
            <div v-for="topic in topicList" :key="topic.topicId" class="topic-item"
              :class="{ 'active': currentTopicId === topic.topicId }">
              <div class="topic-info" @click="selectTopic(topic)">
                <div class="topic-name">{{ topic.topic }}</div>
                <div class="topic-time">{{ topic.createTime }}</div>
              </div>
              <div class="topic-actions">
                <el-button type="danger" size="small" :icon="Delete" circle @click.stop="handleDeleteTopic(topic)"
                  class="delete-btn" title="删除对话" />
              </div>
            </div>
          </div>
        </div>

        <!-- 对话内容区域 -->
        <div class="chat-content">
          <div class="section-header">
            <h3>{{ chatTitle }}</h3>
            <div class="header-actions">
              <el-button v-if="currentTopicId" size="small" type="primary" @click="startNewChat">
                <el-icon>
                  <Plus />
                </el-icon>
                新建对话
              </el-button>
              <el-button v-if="!currentTopicId && chatMessages.length > 0" size="small" @click="clearChat">
                清空对话
              </el-button>
            </div>
          </div>

          <!-- 聊天消息列表 -->
          <div class="chat-messages" ref="messagesContainer">
            <!-- 开场白 -->
            <div v-if="openingMessage && !currentTopicId" class="message-item assistant-message">
              <div class="message-avatar">
                <svg-icon icon-class="robot" />
              </div>
              <div class="message-content">
                <div class="message-text">{{ openingMessage }}</div>
              </div>
            </div>

            <!-- 文件上传提示消息 -->
            <div v-if="openingMessage && !currentTopicId" class="message-item assistant-message">
              <div class="message-avatar">
                <svg-icon icon-class="robot" />
              </div>
              <div class="message-content">
                <div class="message-upload-area">
                  <p class="upload-tip">请上传您需要分析的招标文件（单个文件）：</p>
                  <el-upload class="inline-upload" :action="uploadAction" :multiple="false" :auto-upload="false"
                    :file-list="chatFileList" :on-change="handleChatFileChange" :before-upload="beforeUpload"
                    :show-file-list="true" :limit="1">
                    <el-button type="primary" size="small">
                      <el-icon>
                        <Upload />
                      </el-icon>
                      选择招标文件
                    </el-button>
                  </el-upload>
                  <div v-if="chatFileList.length > 0" class="chat-upload-actions">
                    <el-button size="small" type="success" @click="submitChatUpload">
                      <el-icon>
                        <Check />
                      </el-icon>
                      确认上传
                    </el-button>
                  </div>
                  <div v-if="percentageDisplay">
                    <el-progress :percentage="percentage" :stroke-width="25" :text-inside="true">
                      <el-button text>{{ progress }}</el-button>
                    </el-progress>
                  </div>
                </div>
              </div>
            </div>

            <!-- 对话消息 -->
            <div v-for="(message, index) in chatMessages" :key="index" class="message-item" :class="[
              message.role === 'user' ? 'user-message' : 'assistant-message',
              message.isFileInfo ? 'file-info-message' : ''
            ]">
              <div class="message-avatar">
                <el-icon v-if="message.role === 'user'">
                  <User />
                </el-icon>
                <el-icon v-else>
                  <svg-icon icon-class="robot" />
                </el-icon>
              </div>
              <div class="message-content">
                <div v-if="message.isHtml" class="message-text" v-html="message.content"></div>
                <div v-else class="message-text">{{ message.content }}</div>
                <div class="message-actions">
                  <span class="message-time">{{ message.timestamp }}</span>
                  <el-button v-if="message.canRetry" type="text" size="small" @click="retryMessage(message)"
                    class="retry-btn">
                    <el-icon>
                      <Refresh />
                    </el-icon>
                    重新发送
                  </el-button>
                </div>
              </div>
            </div>

            <!-- 文件上传提示消息 -->
            <div v-if="techUploadDisplay" class="message-item assistant-message">
              <div class="message-avatar">
                <svg-icon icon-class="robot" />
              </div>
              <div class="message-content">
                <div class="message-upload-area">
                  <p class="upload-tip">请上传大纲修改后的技术文件：</p>
                  <el-upload class="inline-upload" :action="uploadAction" :multiple="false" :auto-upload="false"
                    :file-list="chatFileList" :on-change="handleChatFileChange" :before-upload="beforeUpload"
                    :show-file-list="true" :limit="1">
                    <el-button type="primary" size="small">
                      <el-icon>
                        <Upload />
                      </el-icon>
                      选择技术文件
                    </el-button>
                  </el-upload>
                  <div v-if="chatFileList.length > 0" class="chat-upload-actions">
                    <el-button size="small" type="success" @click="submitFileUpload">
                      <el-icon>
                        <Check />
                      </el-icon>
                      确认上传
                    </el-button>
                  </div>
                  <div v-if="percentageDisplay">
                    <el-progress :percentage="percentage" :stroke-width="25" :text-inside="true">
                      <el-button text>{{ progress }}</el-button>
                    </el-progress>
                  </div>
                </div>
              </div>
            </div>

            <!-- 正在输入指示器 -->
            <div v-if="isTyping" class="message-item assistant-message">
              <div class="message-avatar">
                <svg-icon icon-class="robot" />
              </div>
              <div class="message-content">
                <div class="typing-indicator">
                  <span></span>
                  <span></span>
                  <span></span>
                </div>
              </div>
            </div>
          </div>

          <!-- 输入区域 -->
          <div class="chat-input-area">
            <el-input v-model="inputMessage" type="textarea" :autosize="{ minRows: 2, maxRows: 4 }"
              placeholder="请输入您的问题..." @keydown.enter="handleEnterKeydown" />
            <div class="input-actions">
              <span class="input-tip">Enter 发送，Shift + Enter 换行</span>
              <el-button type="primary" @click="sendMessage()" :disabled="!inputMessage.trim() || isTyping">
                发送
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-else class="empty-state">
      <el-icon size="48"><Select /></el-icon>
      <p>请选择一个智能体查看详细信息</p>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, watch, nextTick, computed, getCurrentInstance } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Delete, Refresh } from '@element-plus/icons-vue';
import { getAgent, opening, uploadFile, uploadModifyFile, getProcessValue } from '@/api/llm/agent';
import { answer } from '@/api/llm/mcp';
import { listTopic, getTopic, delTopic, addTopic, updateTopic } from "@/api/llm/topic";
import { listChat, addChat, updateChat } from "@/api/llm/chat";
import { listDocument } from "@/api/llm/document";
import useUserStore from '@/store/modules/user'

const { proxy } = getCurrentInstance()

// Props
const props = defineProps({
  agentId: {
    type: [String, Number],
    default: null
  }
})

const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const agentInfo = ref(null)
const openingMessage = ref('')
const chatMessages = ref([])
const inputMessage = ref('')
const isTyping = ref(false)
const messagesContainer = ref(null)
const topicList = ref([])
const currentTopicId = ref(null)
const chatTitle = ref('智能体新对话')
const percentage = ref(0);
const progress = ref("");
const percentageDisplay = ref(false);
const techUploadDisplay = ref(false)

// 聊天内文件上传相关
const chatFileList = ref([]) // 聊天内的文件列表
const uploadAction = computed(() => '/llm/agent/upload')

// 监听agentId变化
watch(
  () => props.agentId,
  (newAgentId) => {
    if (newAgentId) {
      loadAgentDetail(newAgentId)
    } else {
      agentInfo.value = null
      openingMessage.value = ''
      chatMessages.value = []
      chatFileList.value = []
      currentTopicId.value = null
      chatTitle.value = '智能体新对话'
    }
  },
  { immediate: true }
)

// 加载智能体详细信息
const loadAgentDetail = async (agentId) => {
  loading.value = true
  try {
    // 获取智能体详细信息
    const response = await getAgent(agentId)
    agentInfo.value = response.data

    // 获取开场白
    if (agentInfo.value?.agentName) {
      const res = await opening(agentInfo.value.agentName)
      openingMessage.value = res.data.resultContent;
    }
    // 查询当前智能体的话题列表
    await loadTopic()
    // 自动滚动到底部
    nextTick(() => {
      scrollToBottom()
    })
  } catch (error) {
    console.error('加载智能体详细信息失败:', error)
    ElMessage.error('加载智能体信息失败')
  } finally {
    loading.value = false
  }
}
// 加载选择智能体的话题列表
const loadTopic = async () => {
  const res = await listTopic({ agentId: props.agentId })
  if (res.rows.length > 0) {
    topicList.value = res.rows
  }
  else {
    topicList.value = res.rows
    techUploadDisplay.value = false
  }
}

// 加载指定话题的聊天记录（公共函数）
const loadChatMessages = async (topicId) => {
  try {
    const res = await listChat({ topicId: topicId });
    if (res.rows.length > 0) {
      // 处理聊天消息格式
      const messages = []
      for (const chat of res.rows) {
        // 加载该聊天记录相关的文件，优先显示
        if (chat.chatId) {
          try {
            const fileResponse = await listDocument({ chatId: chat.chatId });
            if (fileResponse.rows && fileResponse.rows.length > 0) {
              const fileNames = fileResponse.rows.map(doc => doc.path.split("/")[doc.path.split("/").length - 1]).join(', ');
              // 先添加文件信息消息
              messages.push({
                role: 'assistant',
                content: `📎 相关文件: ${fileNames}`,
                isHtml: false,
                isFileInfo: true // 标记为文件信息消息
              })
            }
          } catch (error) {
            console.warn('加载文件信息失败:', error)
          }
        }
        // 添加用户输入消息（如果存在）
        if (chat.input) {
          messages.push({
            role: 'user',
            content: chat.input,
            timestamp: chat.inputTime || new Date(chat.createTime).toLocaleTimeString(),
            isHtml: false,
            originalContent: chat.input, // 为历史消息添加原始内容
            canRetry: false // 历史消息默认不显示重试按钮
          })
        }
        // 添加助手回复消息
        if (chat.output) {
          messages.push({
            role: 'assistant',
            content: chat.output,
            timestamp: chat.outputTime || new Date(chat.createTime).toLocaleTimeString(),
            isHtml: true // 历史消息可能包含HTML内容
          })
        }
      }
      // 更新聊天消息
      chatMessages.value = messages
      return messages.length > 0
    } else {
      chatMessages.value = []
      return false
    }
  } catch (error) {
    console.error('加载话题对话记录失败:', error)
    chatMessages.value = []
    throw error
  }
}

// 选择话题
const selectTopic = async (topic) => {
  console.log('选择话题:', topic)
  currentTopicId.value = topic.topicId
  chatTitle.value = topic.topic

  try {
    const hasMessages = await loadChatMessages(topic.topicId)

    // 滚动到底部
    nextTick(() => {
      scrollToBottom()
    })

    if (hasMessages) {
      ElMessage.success(`已加载话题"${topic.topic}"的对话记录`)
    } else {
      ElMessage.info('该话题暂无对话记录')
    }
  } catch (error) {
    ElMessage.error('加载对话记录失败')
  }
}

// 删除话题
const handleDeleteTopic = async (topic) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除话题"${topic.topic}"吗？删除后无法恢复。`,
      '删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }
    )

    // 调用删除API
    await delTopic(topic.topicId)

    // 如果删除的是当前选中的话题，则重置对话状态
    if (currentTopicId.value === topic.topicId) {
      currentTopicId.value = null
      chatMessages.value = []
      chatTitle.value = '智能体新对话'
    }

    // 重新加载话题列表
    await loadTopic()

    ElMessage.success('话题删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除话题失败:', error)
      ElMessage.error('删除话题失败')
    }
  }
}

// 处理 Enter 键事件
const handleEnterKeydown = (event) => {
  // 如果按住 Shift 键，允许换行
  if (event.shiftKey) {
    return
  }
  // 阻止默认的换行行为
  event.preventDefault()
  // 发送消息
  sendMessage()
}

// 发送消息（支持重试）
const sendMessage = async (retryContent = null) => {
  // 确保 retryContent 是字符串类型，如果是事件对象则忽略
  const validRetryContent = (typeof retryContent === 'string') ? retryContent : null
  const message = validRetryContent || inputMessage.value.trim()
  if (!message || isTyping.value) return

  // 添加用户消息
  const userMessage = {
    role: 'user',
    content: message,
    timestamp: new Date().toLocaleTimeString(),
    isHtml: false, // 用户消息不使用HTML渲染
    originalContent: message, // 保存原始内容用于重试
    canRetry: false // 初始时不显示重试按钮
  }
  chatMessages.value.push(userMessage)

  // 只有在非重试模式下才清空输入框
  if (!retryContent) {
    inputMessage.value = ''
  }

  isTyping.value = true

  nextTick(() => {
    scrollToBottom()
  })

  try {
    // 调用智能体回答API
    const response = await answer({
      topicId: currentTopicId.value,
      question: message
    })
    let content = JSON.parse(response.resultContent).content;
    console.log(content);

    // 检查是否是默认的失败回复
    const defaultFailureMessage = '抱歉，我暂时无法回答这个问题。';
    const finalContent = formatContentLinks(content) || defaultFailureMessage;

    // 添加助手回复
    const assistantMessage = {
      role: 'assistant',
      content: finalContent,
      timestamp: new Date().toLocaleTimeString(),
      isHtml: true // 普通聊天消息使用HTML渲染
    }
    chatMessages.value.push(assistantMessage)

    // 如果是默认失败回复，为用户消息添加重试按钮
    if (finalContent === defaultFailureMessage) {
      userMessage.canRetry = true
    }
  } catch (error) {
    console.error('发送消息失败:', error)
    ElMessage.error('发送消息失败')

    // 添加错误消息
    const errorMessage = {
      role: 'assistant',
      content: '抱歉，发生了一些错误，请稍后再试。',
      timestamp: new Date().toLocaleTimeString(),
      isHtml: false
    }
    chatMessages.value.push(errorMessage)

    // 为用户消息添加重试按钮
    userMessage.canRetry = true
  } finally {
    isTyping.value = false
    nextTick(() => {
      scrollToBottom()
    })
  }
}

// 重新发送消息
const retryMessage = async (message) => {
  // 找到当前消息在数组中的索引
  const messageIndex = chatMessages.value.findIndex(msg => msg === message)
  if (messageIndex === -1) return

  // 获取原始消息内容
  const originalContent = message.originalContent || message.content
  if (!originalContent || typeof originalContent !== 'string') {
    ElMessage.error('无法获取原始消息内容')
    return
  }

  // 移除从当前用户消息开始的所有消息（包括后续的助手回复）
  const messagesToKeep = chatMessages.value.slice(0, messageIndex)
  chatMessages.value = messagesToKeep

  // 重新发送原始消息
  await sendMessage(originalContent)
}

// 滚动到底部
const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

// 聊天内文件上传相关方法
const handleChatFileChange = (file, fileList) => {
  // 只保留最新选择的文件（限制为单文件）
  chatFileList.value = fileList.slice(-1)
}

const beforeUpload = (file) => {
  const isValidType = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'text/plain'].includes(file.type)
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isValidType) {
    ElMessage.error('只支持 PDF、DOC、DOCX、TXT 格式的文件！')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('单个文件大小不能超过 10MB！')
    return false
  }
  return false // 阻止自动上传
}
// 聊天内文件上传提交
const submitChatUpload = async () => {
  if (chatFileList.value.length === 0) {
    ElMessage.warning('请先选择文件')
    return
  }
  try {
    percentageDisplay.value = true;
    var timer;
    clearInterval(timer);
    getProcess()
    function getProcess() {
      timer = setInterval(function () { //隔2000毫秒获取进度
        getProcessValue().then(res => {
          if (res.code == 200 & res.msg.includes(":")) {
            progress.value = res.msg;
            percentage.value = Number(res.msg.split(":")[1].replace("%", ""))
          }
        });
      }, 2000)
    }
    const file = chatFileList.value[0].raw // 只取第一个文件
    const fileName = file.name;
    try {
      const response = await uploadFile(file, agentInfo.value.agentName)
      const chatId = response.data.chatId; //获取保存后的chatId
      // 解析返回的数据
      if (response.data && response.data.assistantMessage) {
        percentageDisplay.value = false;
        // 格式化链接：在href前加上基础API地址
        let assistantContent = formatContentLinks(response.data.assistantMessage)
        clearInterval(timer);
        // 添加上传成功的消息到聊天记录
        const uploadMessage = {
          role: 'assistant',
          content: assistantContent,
          timestamp: new Date().toLocaleTimeString(),
          isHtml: true // 标记这是HTML内容
        }
        chatMessages.value.push(uploadMessage);
        techUploadDisplay.value = true;
        // ElMessage.success('文件上传成功');
        let topicRes = await addTopic({ agentId: props.agentId, topic: fileName });
        const topicId = topicRes.msg;
        await updateChat({ userId: userStore.id, chatId, topicId, output: assistantContent, outputTime: proxy.parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}') });

        // 刷新话题列表
        await loadTopic();

        // 激活当前话题并加载聊天记录
        currentTopicId.value = topicId;
        chatTitle.value = fileName;

        // 重新加载该话题的聊天记录以显示文件相关内容
        try {
          await loadChatMessages(topicId)
        } catch (error) {
          console.error('加载话题聊天记录失败:', error)
        }

        // 清空文件上传列表
        chatFileList.value = [];

        nextTick(() => {
          scrollToBottom()
        })
      }
    }
    catch (error) {
      clearInterval(timer);
      console.error('文件上传失败:', error)
    }

  } catch (error) {
    console.error('文件上传失败:', error)
    ElMessage.error('文件上传失败')

    // 添加上传失败的消息到聊天记录
    const errorMessage = {
      role: 'assistant',
      content: '文件上传失败，请检查文件格式或网络连接后重试。',
      timestamp: new Date().toLocaleTimeString(),
      isHtml: false
    }
    chatMessages.value.push(errorMessage)

    nextTick(() => {
      scrollToBottom()
    })
  }
}

// 聊天内文件上传提交
const submitFileUpload = async () => {
  if (chatFileList.value.length === 0) {
    ElMessage.warning('请先选择文件')
    return
  }
  try {
    percentageDisplay.value = true;
    var timer;
    clearInterval(timer);
    getProcess()
    function getProcess() {
      timer = setInterval(function () { //隔2000毫秒获取进度
        getProcessValue().then(res => {
          if (res.code == 200 & res.msg.includes(":")) {
            progress.value = res.msg;
            percentage.value = Number(res.msg.split(":")[1].replace("%", ""))
          }
        });
      }, 2000)
    }
    const file = chatFileList.value[0].raw // 只取第一个文件
    const fileName = file.name;
    try {
      const response = await uploadModifyFile(file, agentInfo.value.agentName)
      const chatId = response.data.chatId; //获取保存后的chatId
      // 解析返回的数据
      if (response.data && response.data.assistantMessage) {
        percentageDisplay.value = false;
        // 格式化链接：在href前加上基础API地址
        let assistantContent = formatContentLinks(response.data.assistantMessage)
        clearInterval(timer);
        // 添加上传成功的消息到聊天记录
        const uploadMessage = {
          role: 'assistant',
          content: assistantContent,
          timestamp: new Date().toLocaleTimeString(),
          isHtml: true // 标记这是HTML内容
        }
        chatMessages.value.push(uploadMessage);
        techUploadDisplay.value = false;
        await updateChat({ userId: userStore.id, chatId, topicId: currentTopicId.value, output: assistantContent, outputTime: proxy.parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}') });

        // 清空文件上传列表
        chatFileList.value = [];

        nextTick(() => {
          scrollToBottom()
        })
      }
    }
    catch (error) {
      clearInterval(timer);
      console.error('文件上传失败:', error)
    }

  } catch (error) {
    console.error('文件上传失败:', error)
    ElMessage.error('文件上传失败')

    // 添加上传失败的消息到聊天记录
    const errorMessage = {
      role: 'assistant',
      content: '文件上传失败，请检查文件格式或网络连接后重试。',
      timestamp: new Date().toLocaleTimeString(),
      isHtml: false
    }
    chatMessages.value.push(errorMessage)

    nextTick(() => {
      scrollToBottom()
    })
  }
}
// 开始新对话
const startNewChat = () => {
  currentTopicId.value = null
  chatMessages.value = []
  chatFileList.value = []
  chatTitle.value = '智能体新对话'

  // 滚动到顶部显示开场白
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = 0
    }
  })

  ElMessage.success('已切换到新对话模式')
}

// 清空对话
const clearChat = () => {
  chatMessages.value = []
  chatFileList.value = []
  chatTitle.value = '智能体新对话'

  // 滚动到顶部显示开场白
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = 0
    }
  })

  ElMessage.success('对话已清空')
}

// 格式化内容中的链接
const formatContentLinks = (content) => {
  if (!content) return content

  // 使用正则表达式匹配 <a href='/profile/...'>...</a> 格式的链接
  const linkRegex = /<a\s+href=['"]([^'"]*?)['"][^>]*?>(.*?)<\/a>/gi

  let formattedContent = content.replace(linkRegex, (match, href, text) => {
    // 如果href不是以http开头的，说明是相对路径，需要添加基础API地址
    if (!href.startsWith('http')) {
      const baseApi = import.meta.env.VITE_APP_BASE_API || ''
      const fullUrl = baseApi + href
      return `<a href="${fullUrl}" target="_blank" style="color: #1890ff; text-decoration: underline;">${text}</a>`
    }
    return match
  })

  // 将普通换行符转换为HTML换行符
  formattedContent = formattedContent.replace(/\n/g, '<br>')

  return formattedContent
}
</script>

<style lang="scss" scoped>
.agent-detail-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.detail-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.agent-header {
  padding: 15px;
  border-bottom: 1px solid #e4e4e4;
  background: white;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;

  .agent-basic-info {
    flex: 1;

    .agent-title {
      margin: 0 0 8px 0;
      font-size: 24px;
      font-weight: 600;
      color: #333;
    }

    .agent-description {
      margin: 0 0 12px 0;
      font-size: 14px;
      color: #666;
      line-height: 1.5;
    }

    .agent-meta-info {
      display: flex;
      gap: 16px;

      .meta-item {
        display: flex;
        align-items: center;
        gap: 4px;
        font-size: 12px;
        color: #999;

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

  .agent-actions {
    display: flex;
    gap: 12px;
  }
}

.chat-section {
  background: white;
  margin: 16px 24px;
  border-radius: 8px;
  border: 1px solid #e4e4e4;
  overflow: hidden;
  display: flex;
  height: calc(100vh - 200px);

  // 话题列表样式
  .topic-list {
    width: 250px;
    border-right: 1px solid #e4e4e4;
    display: flex;
    flex-direction: column;
    background: #f8f9fa;

    .topic-header {
      padding: 16px 20px;
      border-bottom: 1px solid #e4e4e4;
      background: #f5f7fa;
      color: #495057;

      h4 {
        margin: 0;
        font-size: 14px;
        font-weight: 600;
        color: #495057;
        display: flex;
        align-items: center;

        &::before {
          content: "📚";
          margin-right: 8px;
          font-size: 16px;
        }
      }
    }

    .topic-content {
      flex: 1;
      overflow-y: auto;
      padding: 8px 0;

      .topic-item {
        padding: 12px 16px;
        border-bottom: 1px solid #e9ecef;
        transition: all 0.3s ease;
        background: white;
        margin: 4px 8px;
        border-radius: 6px;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        display: flex;
        justify-content: space-between;
        align-items: center;

        &:hover {
          background: #e3f2fd;
          transform: translateX(2px);
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);

          .topic-actions {
            opacity: 1;
          }
        }

        &.active {
          background: #f5f7fa;
          color: #495057;
          transform: translateX(3px);
          box-shadow: 0 3px 12px rgba(73, 80, 87, 0.2);
          border-left: 3px solid #409EFF;

          .topic-info {
            .topic-name {
              color: #495057;
              font-weight: 600;

              &::before {
                content: "💬";
                filter: none;
              }
            }

            .topic-time {
              color: #6c757d;
            }
          }
        }

        &:last-child {
          border-bottom: none;
        }

        .topic-info {
          flex: 1;
          cursor: pointer;
          min-width: 0; // 允许flex项目缩小到内容以下
          max-width: calc(100% - 40px); // 为删除按钮预留40px空间

          .topic-name {
            font-size: 13px;
            font-weight: 500;
            color: #495057;
            margin-bottom: 4px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            max-width: 100%;

            &::before {
              content: "💬";
              margin-right: 6px;
              font-size: 12px;
            }
          }

          .topic-time {
            font-size: 11px;
            color: #6c757d;
            font-style: italic;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            max-width: 100%;
          }
        }

        .topic-actions {
          flex-shrink: 0; // 防止删除按钮被压缩
          width: 32px; // 固定宽度
          display: flex;
          justify-content: center;
          opacity: 0;
          transition: opacity 0.3s ease;

          .delete-btn {
            width: 24px;
            height: 24px;
            padding: 0;
            border: none;
            background: #ff4757;

            &:hover {
              background: #ff3742;
              transform: scale(1.1);
            }

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

  // 对话内容区域样式
  .chat-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    background: #fdfdfd;

    .section-header {
      padding: 16px 20px;
      border-bottom: 1px solid #e4e4e4;
      background: #f5f7fa;
      display: flex;
      justify-content: space-between;
      align-items: center;

      h3 {
        margin: 0;
        font-size: 16px;
        font-weight: 600;
        color: #495057;
        display: flex;
        align-items: center;

        &::before {
          content: "✨";
          margin-right: 8px;
          font-size: 18px;
        }
      }

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

    .chat-messages {
      flex: 1;
      padding: 16px 20px;
      overflow-y: auto;
      max-height: 900px;

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

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

          .message-avatar {
            background: #1890ff;
            color: white;
            margin-left: 12px;
            margin-right: 0;
          }

          .message-content {
            text-align: right;

            .message-text {
              background: #1890ff;
              color: white;
            }

            .message-actions {
              justify-content: flex-end;

              .retry-btn {
                order: -1; // 将重试按钮放在时间前面
                margin-left: 0;
                margin-right: 8px;
                color: #1890ff;
                background-color: rgba(255, 255, 255, 0.9);

                &:hover {
                  background-color: white;
                }
              }
            }
          }
        }

        &.assistant-message {
          .message-avatar {
            background: #f0f0f0;
            color: #666;
            margin-right: 12px;
          }

          .message-content {
            .message-text {
              background: #f0f0f0;
              color: #333;
            }
          }

          // 文件信息消息特殊样式
          &.file-info-message {
            .message-avatar {
              background: #e3f2fd;
              color: #1976d2;
            }

            .message-content {
              .message-text {
                background: linear-gradient(135deg, #e3f2fd 0%, #f3e5f5 100%);
                color: #1565c0;
                border-left: 4px solid #2196f3;
                font-weight: 500;

                &::before {
                  content: "📋";
                  margin-right: 8px;
                  font-size: 16px;
                }
              }
            }
          }
        }

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

        .message-content {
          max-width: 70%;

          .message-text {
            padding: 8px 12px;
            border-radius: 8px;
            font-size: 14px;
            line-height: 1.5;
            word-wrap: break-word;

            // HTML消息中的链接样式
            :deep(a) {
              color: #1890ff;
              text-decoration: underline;

              &:hover {
                color: #40a9ff;
                text-decoration: none;
              }
            }

            // 换行处理
            :deep(br) {
              display: block;
              margin: 4px 0;
            }
          }

          .message-actions {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-top: 4px;

            .message-time {
              font-size: 11px;
              color: #999;
            }

            .retry-btn {
              font-size: 11px;
              color: #1890ff;
              padding: 2px 6px;
              margin-left: 8px;

              &:hover {
                background-color: #f0f8ff;
              }

              .el-icon {
                font-size: 12px;
                margin-right: 2px;
              }
            }
          }
        }

        // 聊天内文件上传区域样式
        .message-upload-area {
          background: #f8f9fa;
          border: 1px dashed #d0d7de;
          border-radius: 8px;
          padding: 16px;

          .upload-tip {
            margin: 0 0 12px 0;
            font-size: 14px;
            color: #333;
          }

          .inline-upload {
            margin-bottom: 12px;

            :deep(.el-upload-list) {
              margin-top: 8px;

              .el-upload-list__item {
                font-size: 12px;
                margin: 2px 0;
              }
            }
          }

          .chat-upload-actions {
            display: flex;
            gap: 8px;
            margin-top: 8px;
          }
        }
      }
    }

    .chat-input-area {
      padding: 16px 20px;
      border-top: 1px solid #e4e4e4;

      .input-actions {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 8px;

        .input-tip {
          font-size: 12px;
          color: #999;
        }
      }
    }
  }
}

// 打字指示器动画
.typing-indicator {
  display: flex;
  gap: 4px;
  padding: 8px 12px;
  background: #f0f0f0;
  border-radius: 8px;

  span {
    width: 6px;
    height: 6px;
    background: #999;
    border-radius: 50%;
    animation: typing 1.4s infinite ease-in-out;

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

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

@keyframes typing {

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

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

.empty-state {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #999;

  p {
    margin-top: 16px;
    font-size: 14px;
  }
}
</style>