<template>
  <div class="ai-chat-container">
    <!-- 侧边栏：会话列表 -->
    <div class="chat-sidebar">
      <div class="sidebar-header">
        <el-button type="primary" icon="Plus" @click="handleNewChat" class="new-chat-btn">
          新对话
        </el-button>
      </div>

      <div class="conversation-list">
        <div
          v-for="conv in conversations"
          :key="conv.conversationId"
          class="conversation-item"
          :class="{ active: currentConversationId === conv.conversationId }"
          @click="handleSelectConversation(conv.conversationId)"
        >
          <div class="conv-title">{{ conv.title }}</div>
          <div class="conv-meta">
            <span class="model-tag">{{ conv.serviceName || conv.modelName }}</span>
            <span class="time">{{ parseTime(conv.lastMessageTime, '{m}-{d} {h}:{i}') }}</span>
          </div>
          <el-button
            class="delete-btn"
            link
            icon="Delete"
            @click.stop="handleDeleteConversation(conv.conversationId)"
          />
        </div>
      </div>
    </div>

    <!-- 主聊天区域 -->
    <div class="chat-main">
      <!-- 顶部工具栏 -->
      <div class="chat-header">
        <div class="header-left">
          <el-select 
            v-model="selectedServiceId" 
            placeholder="请选择AI服务" 
            class="model-selector"
            @change="handleServiceChange"
            filterable
          >
            <el-option-group
              v-for="group in groupedServices"
              :key="group.label"
              :label="group.label"
            >
              <el-option
                v-for="service in group.options"
                :key="service.serviceId"
                :label="service.serviceName"
                :value="service.serviceId"
              >
                <span>{{ service.serviceName }}</span>
              </el-option>
            </el-option-group>
          </el-select>
        </div>
        <div class="header-right">
          <el-tooltip content="导出对话" placement="bottom">
            <el-button link icon="Download" @click="handleExportChat" />
          </el-tooltip>
        </div>
      </div>

      <!-- 消息列表 -->
      <div class="messages-container" ref="messagesContainerRef" @click="handleMessageAreaClick">
        <div v-if="messages.length === 0" class="empty-state">
          <el-icon :size="64"><ChatDotRound /></el-icon>
          <p>开始新的对话</p>
        </div>

        <div
          v-for="(msg, index) in messages"
          :key="index"
          class="message-item"
          :class="msg.role"
        >
          <div class="avatar">
            <el-icon v-if="msg.role === 'user'"><UserFilled /></el-icon>
            <el-icon v-else><ChatSquare /></el-icon>
          </div>
          
          <div class="message-wrapper">
            <div class="message-content">
              <!-- 思考内容（可折叠） -->
              <div v-if="msg.reasoning" class="reasoning-block">
                <div class="reasoning-header" @click="msg.showReasoning = !msg.showReasoning">
                  <el-icon><Reading /></el-icon>
                  <span>思考过程</span>
                  <el-icon class="arrow" :class="{ expanded: msg.showReasoning }"><ArrowDown /></el-icon>
                </div>
                <div v-show="msg.showReasoning" class="reasoning-content" v-html="formatMessage(msg.reasoning)"></div>
              </div>
              
              <!-- 用户上传的图片 -->
              <div v-if="msg.images && msg.images.length > 0" class="message-images">
                <img 
                  v-for="(imgUrl, imgIdx) in msg.images" 
                  :key="imgIdx" 
                  :src="imgUrl" 
                  class="uploaded-image"
                  @click="previewImage(imgUrl)"
                />
              </div>
              
              <!-- 用户上传的文件 -->
              <div v-if="msg.files && msg.files.length > 0" class="message-files">
                <div v-for="(fileName, fileIdx) in msg.files" :key="fileIdx" class="file-item">
                  <el-icon><Document /></el-icon>
                  <span>{{ fileName }}</span>
                </div>
              </div>
              
              <!-- 消息内容 -->
              <div v-if="msg.content" class="message-text" v-html="formatMessage(msg.content)"></div>
              
              <!-- 思考中状态 -->
              <div v-else-if="msg.isTyping && !msg.reasoning" class="typing-indicator">
                <span>AI正在思考中...</span>
              </div>
              
              <span v-if="msg.isTyping" class="typing-cursor"></span>
            </div>
            
            <!-- 底部信息栏（移出气泡） -->
            <div class="message-footer" v-if="msg.content">
              <div class="footer-left">
                <span class="message-time">{{ parseTime(msg.createTime, '{h}:{i}:{s}') }}</span>
              </div>
              <div class="footer-right">
                <el-button 
                  v-if="msg.role === 'assistant'" 
                  type="primary" 
                  link
                  class="action-btn"
                  @click="copyMessage(index)"
                >
                  <el-icon><DocumentCopy /></el-icon> 复制
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 输入框 -->
      <div class="chat-input-area">
        <!-- 功能选项栏 -->
        <div class="chat-options-bar">
          <!-- 深度思考 -->
          <el-tooltip content="深度思考 (R1)" placement="top" :show-after="500">
            <div 
              class="option-item" 
              :class="{ 
                active: chatOptions.thinking, 
                disabled: currentService?.supportsThinking !== '1' 
              }"
              @click="toggleOption('thinking')"
            >
              <el-icon><Cpu /></el-icon>
              <span>深度思考</span>
            </div>
          </el-tooltip>

          <!-- 联网搜索 -->
          <el-tooltip content="联网搜索" placement="top" :show-after="500">
            <div 
              class="option-item" 
              :class="{ 
                active: chatOptions.search, 
                disabled: currentService?.supportsSearch !== '1' 
              }"
              @click="toggleOption('search')"
            >
              <el-icon><Search /></el-icon>
              <span>联网搜索</span>
            </div>
          </el-tooltip>

          <!-- 上传文件 -->
          <el-tooltip content="上传文件" placement="top" :show-after="500">
            <div 
              class="option-item" 
              :class="{ 
                active: fileList.length > 0, 
                disabled: currentService?.supportsFiles !== '1' 
              }"
              @click="triggerUpload('file')"
            >
              <el-icon><Paperclip /></el-icon>
              <span>上传文件</span>
            </div>
          </el-tooltip>

          <!-- 上传图片 -->
          <el-tooltip content="上传图片" placement="top" :show-after="500">
            <div 
              class="option-item" 
              :class="{ 
                active: imageList.length > 0, 
                disabled: currentService?.supportsVision !== '1' 
              }"
              @click="triggerUpload('image')"
            >
              <el-icon><Picture /></el-icon>
              <span>上传图片</span>
            </div>
          </el-tooltip>
        </div>

        <!-- 文件预览区域 -->
        <div v-if="fileList.length > 0 || imageList.length > 0" class="file-preview-area">
          <el-tag
            v-for="(file, index) in fileList"
            :key="'file-'+index"
            closable
            @close="removeFile('file', index)"
            class="preview-tag"
          >
            <el-icon><Document /></el-icon> {{ file.name }}
          </el-tag>
          <el-tag
            v-for="(img, index) in imageList"
            :key="'img-'+index"
            closable
            @close="removeFile('image', index)"
            class="preview-tag"
            type="success"
          >
            <el-icon><Picture /></el-icon> {{ img.name }}
          </el-tag>
        </div>

        <!-- 隐藏的上传输入框 -->
        <input 
          type="file" 
          ref="fileInputRef" 
          style="display: none" 
          @change="handleFileChange" 
        />
        <input 
          type="file" 
          ref="imageInputRef" 
          style="display: none" 
          accept="image/*" 
          @change="handleImageChange" 
        />

        <div class="input-wrapper">
          <el-input
            v-model="inputMessage"
            type="textarea"
            :rows="3"
            placeholder="有什么我能帮您的吗？（Ctrl + Enter 发送）"
            @keydown="handleKeyDown"
            resize="none"
          />
          <el-button
            type="primary"
            icon="Top"
            :loading="loading"
            :disabled="!inputMessage.trim() || !selectedServiceId"
            @click="handleSendMessage"
            circle
            class="send-btn"
          />
        </div>
      </div>
    </div>
    
    <!-- 图片预览对话框 -->
    <el-dialog v-model="showImagePreview" title="图片预览" width="800px" append-to-body>
      <img :src="previewImageUrl" style="width: 100%; max-height: 70vh; object-fit: contain;" />
    </el-dialog>
  </div>
</template>

<script setup name="AiChat">
import { ChatDotRound, UserFilled, ChatSquare, DocumentCopy, Search, Cpu, Paperclip, Picture, Document, Delete, Plus, Top, Download, Reading, ArrowDown } from '@element-plus/icons-vue'
import { sendMessage, getHistory, createConversation, getConversations, deleteConversation } from '@/api/system/ai/chat'
import { listEnabledService } from '@/api/system/ai/service'
import { getToken } from '@/utils/auth'
import request from '@/utils/request'
import MarkdownIt from 'markdown-it'

const { proxy } = getCurrentInstance()

const conversations = ref([])
const currentConversationId = ref(null)
const messages = ref([])
const inputMessage = ref('')
const loading = ref(false)
const services = ref([])
const selectedServiceId = ref(null)
const messagesContainerRef = ref(null)

// 上传相关
const fileInputRef = ref(null)
const imageInputRef = ref(null)
const fileList = ref([])
const imageList = ref([])

// 聊天选项
const chatOptions = reactive({
  search: false,
  thinking: false
})

// 分组后的服务列表
const groupedServices = computed(() => {
  const groups = {}
  services.value.forEach(service => {
    const provider = service.providerName || '其他'
    if (!groups[provider]) {
      groups[provider] = []
    }
    groups[provider].push(service)
  })
  return Object.keys(groups).map(provider => ({
    label: provider,
    options: groups[provider]
  }))
})

// 当前选中的服务
const currentService = computed(() => {
  return services.value.find(s => s.serviceId === selectedServiceId.value)
})

// 监听服务切换，重置选项
watch(selectedServiceId, () => {
  chatOptions.search = false
  chatOptions.thinking = false
  // 清空文件列表？可选，这里暂时不清空，方便用户切换服务尝试
})

// Markdown解析器
const md = new MarkdownIt({
  html: true,
  linkify: true,
  breaks: true,
  highlight: function (str, lang) {
    return '<pre class="hljs"><code>' +
           md.utils.escapeHtml(str) +
           '</code></pre>';
  }
})

// 自定义代码块渲染
md.renderer.rules.fence = function (tokens, idx, options, env, self) {
  const token = tokens[idx]
  const code = token.content.trim()
  const lang = token.info ? md.utils.escapeHtml(token.info) : ''
  
  return `<div class="code-block"><div class="code-block-header"><span class="lang-name">${lang}</span><button class="copy-code-btn" data-code="${encodeURIComponent(code)}">复制</button></div><pre class="hljs language-${lang}"><code>${md.utils.escapeHtml(code)}</code></pre></div>`
}

/** 加载AI服务列表 */
async function loadServices() {
  try {
    const res = await listEnabledService()
    services.value = res.data || []
    if (services.value.length > 0 && !selectedServiceId.value) {
      // 优先选择默认服务
      const defaultService = services.value.find(s => s.isDefault === '1')
      selectedServiceId.value = defaultService ? defaultService.serviceId : services.value[0].serviceId
    }
  } catch (error) {
    proxy.$modal.msgError('加载AI服务失败')
  }
}

/** 加载会话列表 */
async function loadConversations() {
  try {
    const res = await getConversations()
    conversations.value = res.data || []
  } catch (error) {
    proxy.$modal.msgError('加载会话列表失败')
  }
}

/** 新建对话 */
async function handleNewChat() {
  if (!selectedServiceId.value) {
    proxy.$modal.msgWarning('请先选择AI服务')
    return
  }
  
  try {
    const res = await createConversation({
      serviceId: selectedServiceId.value,
      title: '新对话 - ' + new Date().toLocaleString()
    })
    
    currentConversationId.value = res.data.conversationId
    messages.value = []
    loadConversations()
    proxy.$modal.msgSuccess('创建成功')
  } catch (error) {
    proxy.$modal.msgError('创建会话失败')
  }
}

/** 选择会话 */
async function handleSelectConversation(conversationId) {
  currentConversationId.value = conversationId
  
  // 自动切换到该会话使用的模型
  const conv = conversations.value.find(c => c.conversationId === conversationId)
  if (conv && conv.serviceId) {
    selectedServiceId.value = conv.serviceId
  }
  
  await loadMessages(conversationId)
}

/** 加载消息历史 */
async function loadMessages(conversationId) {
  try {
    const res = await getHistory(conversationId)
    // 为每条消息添加 showReasoning 属性
    messages.value = (res.data || []).map(msg => ({
      ...msg,
      showReasoning: false
    }))
    nextTick(() => scrollToBottom())
  } catch (error) {
    proxy.$modal.msgError('加载消息失败')
  }
}

/** 选项切换 */
function toggleOption(key) {
  if (!currentService.value) return
  
  // 检查是否支持
  if (key === 'thinking' && currentService.value.supportsThinking !== '1') return
  if (key === 'search' && currentService.value.supportsSearch !== '1') return
  
  chatOptions[key] = !chatOptions[key]
}

/** 触发上传 */
function triggerUpload(type) {
  if (!currentService.value) return
  
  if (type === 'file') {
    if (currentService.value.supportsFiles !== '1') return
    fileInputRef.value.click()
  } else if (type === 'image') {
    if (currentService.value.supportsVision !== '1') return
    imageInputRef.value.click()
  }
}

/** 处理文件选择 */
function handleFileChange(e) {
  const files = Array.from(e.target.files)
  if (files.length > 0) {
    fileList.value.push(...files)
  }
  e.target.value = ''
}

/** 处理图片选择 */
function handleImageChange(e) {
  const files = Array.from(e.target.files)
  if (files.length > 0) {
    imageList.value.push(...files)
  }
  e.target.value = ''
}

/** 移除文件 */
function removeFile(type, index) {
  if (type === 'file') {
    fileList.value.splice(index, 1)
  } else {
    imageList.value.splice(index, 1)
  }
}

/** 上传文件到服务器 */
async function uploadFile(file) {
  const formData = new FormData()
  formData.append('file', file)
  
  try {
    const res = await request({
      url: '/common/upload',
      method: 'post',
      data: formData,
      headers: { 'Content-Type': 'multipart/form-data' }
    })
    if (res.code === 200) {
      return res.url || res.fileName
    }
    return null
  } catch (error) {
    console.error('文件上传失败:', error)
    return null
  }
}

/** 将图片转为 base64 */
function imageToBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = () => resolve(reader.result)
    reader.onerror = reject
    reader.readAsDataURL(file)
  })
}

/** 发送消息（流式输出） */
async function handleSendMessage() {
  if (!inputMessage.value.trim() || !selectedServiceId.value) return

  const message = inputMessage.value.trim()
  
  // 获取待发送的文件和图片
  const filesToSend = [...fileList.value]
  const imagesToSend = [...imageList.value]
  
  // 检查：如果有图片但模型不支持视觉，提示用户
  if (imagesToSend.length > 0 && currentService.value?.supportsVision !== '1') {
    proxy.$modal.msgWarning('当前模型不支持图片识别，已忽略图片')
    imageList.value = []
    imagesToSend.length = 0
  }
  
  inputMessage.value = ''
  fileList.value = []
  imageList.value = []
  
  // 添加用户消息（包含图片预览）
  const userMessage = {
    role: 'user',
    content: message,
    images: imagesToSend.length > 0 ? imagesToSend.map(img => URL.createObjectURL(img)) : [],
    files: filesToSend.map(f => f.name),
    createTime: new Date()
  }
  messages.value.push(userMessage)
  
  // 添加空的 AI 消息占位
  const aiMessageIndex = messages.value.length
  messages.value.push({
    role: 'assistant',
    content: '',
    reasoning: '',
    showReasoning: true,
    isTyping: true,
    createTime: new Date()
  })
  
  scrollToBottom()
  loading.value = true
  
  let abortController = null

  try {
    // 处理图片：转为 base64
    const imageBase64List = []
    for (const img of imagesToSend) {
      const base64 = await imageToBase64(img)
      imageBase64List.push(base64)
    }
    
    // 处理文件：上传到服务器
    const fileUrls = []
    for (const file of filesToSend) {
      const url = await uploadFile(file)
      if (url) {
        fileUrls.push(url)
      }
    }
    
    // 构建请求体
    const requestBody = {
      serviceId: selectedServiceId.value,
      message: message,
      conversationId: currentConversationId.value || null,
      thinkingType: chatOptions.thinking ? 'enabled' : 'disabled',
      enableSearch: chatOptions.search
    }
    
    // 添加图片（base64）
    if (imageBase64List.length > 0) {
      requestBody.images = JSON.stringify(imageBase64List)
    }
    
    // 添加文件URL
    if (fileUrls.length > 0) {
      requestBody.fileUrls = JSON.stringify(fileUrls)
    }
    
    const baseUrl = import.meta.env.VITE_APP_BASE_API
    abortController = new AbortController()
    
    // 使用 fetch + POST 请求
    const response = await fetch(`${baseUrl}/system/ai/chat/stream`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + getToken()
      },
      body: JSON.stringify(requestBody),
      signal: abortController.signal
    })
    
    if (!response.ok) {
      const errorText = await response.text()
      throw new Error(`请求失败: ${response.status} - ${errorText}`)
    }
    
    // 读取流式响应
    const reader = response.body.getReader()
    const decoder = new TextDecoder()
    let buffer = ''
    const showThinkingContent = chatOptions.thinking // 保存用户是否启用了深度思考
    
    while (true) {
      const { done, value } = await reader.read()
      if (done) break
      
      buffer += decoder.decode(value, { stream: true })
      const lines = buffer.split('\n')
      buffer = lines.pop() || ''
      
      for (const line of lines) {
        if (line.startsWith('data:')) {
          const dataStr = line.substring(5).trim()
          if (dataStr === '[DONE]' || dataStr === 'completed') {
            // 流结束
            messages.value[aiMessageIndex].isTyping = false
            loading.value = false
            loadConversations()
            continue
          }
          
          try {
            const data = JSON.parse(dataStr)
            
            // 更新会话ID
            if (data.conversationId && !currentConversationId.value) {
              currentConversationId.value = data.conversationId
            }
            
            // 追加内容
            if (data.content) {
              const currentMsg = messages.value[aiMessageIndex]
              if (currentMsg.showReasoning && currentMsg.reasoning) {
                currentMsg.showReasoning = false
              }
              
              messages.value[aiMessageIndex] = {
                ...currentMsg,
                content: currentMsg.content + data.content,
                showReasoning: currentMsg.showReasoning
              }
              scrollToBottom()
            }
            
            // 追加思考内容（仅在用户启用深度思考时显示）
            if (data.reasoning && showThinkingContent) {
              messages.value[aiMessageIndex] = {
                ...messages.value[aiMessageIndex],
                reasoning: messages.value[aiMessageIndex].reasoning + data.reasoning
              }
              scrollToBottom()
            }
          } catch (e) {
            // 非 JSON 数据
          }
        } else if (line.startsWith('event:done')) {
          messages.value[aiMessageIndex].isTyping = false
          loading.value = false
          loadConversations()
        } else if (line.startsWith('event:error')) {
          // 错误事件，解析错误信息
          const errorLine = lines.find(l => l.startsWith('data:'))
          if (errorLine) {
            throw new Error(errorLine.substring(5).trim())
          }
        }
      }
    }
    
    // 确保结束状态
    messages.value[aiMessageIndex].isTyping = false
    loading.value = false
    loadConversations()
    
  } catch (error) {
    console.error('发送消息失败:', error)
    // 移除失败的消息
    if (messages.value.length > 0 && messages.value[messages.value.length - 1].role === 'assistant') {
      messages.value.pop()
    }
    if (messages.value.length > 0 && messages.value[messages.value.length - 1].role === 'user') {
      messages.value.pop()
    }
    inputMessage.value = message
    fileList.value = filesToSend
    imageList.value = imagesToSend
    proxy.$modal.msgError(error.message || '发送失败')
    loading.value = false
  }
}

/** 删除会话 */
async function handleDeleteConversation(conversationId) {
  try {
    await proxy.$modal.confirm('确认删除该会话？')
    await deleteConversation(conversationId)
    
    if (currentConversationId.value === conversationId) {
      currentConversationId.value = null
      messages.value = []
    }
    
    loadConversations()
    proxy.$modal.msgSuccess('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      proxy.$modal.msgError('删除失败')
    }
  }
}

/** 服务切换 */
function handleServiceChange() {
  // 可添加服务切换逻辑
}

/** 键盘事件 */
function handleKeyDown(event) {
  if ((event.ctrlKey || event.metaKey) && event.key === 'Enter') {
    event.preventDefault()
    handleSendMessage()
  }
}

/** 处理消息区域点击事件（代码块复制） */
function handleMessageAreaClick(e) {
  if (e.target.classList.contains('copy-code-btn')) {
    const code = decodeURIComponent(e.target.dataset.code)
    navigator.clipboard.writeText(code).then(() => {
      const originalText = e.target.textContent
      e.target.textContent = '已复制'
      setTimeout(() => {
        e.target.textContent = originalText
      }, 2000)
      proxy.$modal.msgSuccess('复制成功')
    }).catch(() => {
      proxy.$modal.msgError('复制失败')
    })
  }
}

/** 格式化消息 */
function formatMessage(content) {
  if (!content) return ''
  return md.render(content)
}

/** 复制消息 */
function copyMessage(index) {
  const msg = messages.value[index]
  if (!msg) return
  
  navigator.clipboard.writeText(msg.content).then(() => {
    proxy.$modal.msgSuccess('已复制到剪贴板')
  }).catch(() => {
    proxy.$modal.msgError('复制失败')
  })
}

/** 图片预览 */
const previewImageUrl = ref('')
const showImagePreview = ref(false)
function previewImage(url) {
  previewImageUrl.value = url
  showImagePreview.value = true
}

/** 导出对话 */
function handleExportChat() {
  if (messages.value.length === 0) {
    proxy.$modal.msgInfo('当前对话为空')
    return
  }
  
  let markdown = '# AI 对话记录\n\n'
  markdown += `导出时间：${new Date().toLocaleString()}\n\n---\n\n`
  
  messages.value.forEach((msg) => {
    if (msg.role === 'user') {
      markdown += `## 👤 用户\n\n${msg.content}\n\n`
    } else {
      markdown += `## 🤖 AI 助手\n\n${msg.content}\n\n`
    }
    markdown += '---\n\n'
  })
  
  const blob = new Blob([markdown], { type: 'text/markdown;charset=utf-8' })
  const url = URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = `AI对话_${new Date().toISOString().slice(0, 10)}.md`
  link.click()
  URL.revokeObjectURL(url)
  
  proxy.$modal.msgSuccess('对话已导出')
}

/** 滚动到底部 */
function scrollToBottom() {
  nextTick(() => {
    if (messagesContainerRef.value) {
      messagesContainerRef.value.scrollTop = messagesContainerRef.value.scrollHeight
    }
  })
}

loadServices()
loadConversations()
</script>

<style lang="scss" scoped>
.ai-chat-container {
  display: flex;
  height: calc(100vh - 84px);
  background: #f5f7fa;
}

.chat-sidebar {
  width: 280px;
  background: #fff;
  border-right: 1px solid #e4e7ed;
  display: flex;
  flex-direction: column;

  .sidebar-header {
    padding: 16px;
    border-bottom: 1px solid #e4e7ed;
    
    .new-chat-btn {
      width: 100%;
    }
  }

  .conversation-list {
    flex: 1;
    overflow-y: auto;
    padding: 8px;
    
    .conversation-item {
      padding: 12px;
      border-radius: 6px;
      cursor: pointer;
      transition: all 0.2s;
      position: relative;
      margin-bottom: 4px;

      &:hover {
        background: #f5f7fa;
        
        .delete-btn {
          opacity: 1;
        }
      }

      &.active {
        background: #e6f1fc;
        
        .conv-title {
          color: var(--el-color-primary);
        }
      }

      .conv-title {
        font-size: 14px;
        color: #303133;
        margin-bottom: 4px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        padding-right: 20px;
      }

      .conv-meta {
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-size: 12px;
        color: #909399;

        .model-tag {
          background: #f0f2f5;
          padding: 2px 6px;
          border-radius: 4px;
        }
      }

      .delete-btn {
        position: absolute;
        right: 4px;
        top: 50%;
        transform: translateY(-50%);
        opacity: 0;
        transition: opacity 0.2s;
        
        &:hover {
          color: #f56c6c;
        }
      }
    }
  }
}

.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #fff;

  .chat-header {
    height: 60px;
    border-bottom: 1px solid #e4e7ed;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    background: #fff;
    
    .header-left {
      .model-selector {
        width: 240px;
      }
    }
  }

  .messages-container {
    flex: 1;
    overflow-y: auto;
    padding: 20px;
    
    .empty-state {
      height: 100%;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      color: #909399;
      
      p {
        margin-top: 16px;
        font-size: 16px;
      }
    }

    .message-item {
      display: flex;
      gap: 12px;
      margin-bottom: 24px;
      
      &.user {
        flex-direction: row-reverse;
        
        .message-content {
          background: #e6f1fc;
          border-radius: 12px 0 12px 12px;
        }
      }
      
      &.assistant {
        /* AI 消息占满剩余空间 */
        .message-wrapper {
          max-width: 100%;
          flex: 1;
          margin-right: 48px; /* 右侧预留头像空间 */
        }

        .message-content {
          background: #f4f4f5;
          border-radius: 0 12px 12px 12px;
        }
      }

      .avatar {
        width: 36px;
        height: 36px;
        border-radius: 50%;
        background: #f0f2f5;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-shrink: 0;
        
        .el-icon {
          font-size: 20px;
          color: #909399;
        }
      }

      .message-wrapper {
        max-width: 80%;
        display: flex;
        flex-direction: column;
        gap: 4px;
      }

      .message-content {
        padding: 12px 16px;
        position: relative;
        width: 100%;
        box-sizing: border-box;
        
        .reasoning-block {
          margin-bottom: 12px;
          border-radius: 8px;
          background: rgba(0, 0, 0, 0.03);
          border: 1px solid rgba(0, 0, 0, 0.05);
          
          .reasoning-header {
            display: flex;
            align-items: center;
            gap: 6px;
            padding: 6px 10px;
            cursor: pointer;
            font-size: 12px;
            color: #909399;
            transition: all 0.2s;
            border-radius: 8px;
            
            &:hover {
              background: rgba(0, 0, 0, 0.05);
              color: #606266;
            }
            
            .arrow {
              margin-left: auto;
              transition: transform 0.3s;
              
              &.expanded {
                transform: rotate(180deg);
              }
            }
          }
          
          .reasoning-content {
            padding: 8px 10px;
            border-top: 1px solid rgba(0, 0, 0, 0.05);
            font-size: 13px;
            line-height: 1.5;
            color: #606266;
            background: rgba(255, 255, 255, 0.5);
            border-radius: 0 0 8px 8px;
            
            :deep(p) {
              margin: 0 0 6px 0;
              &:last-child {
                margin-bottom: 0;
              }
            }
          }
          
          .message-images {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            margin-bottom: 8px;
            
            .uploaded-image {
              max-width: 200px;
              max-height: 150px;
              border-radius: 8px;
              cursor: pointer;
              object-fit: cover;
              border: 1px solid #e4e7ed;
              transition: transform 0.2s;
              
              &:hover {
                transform: scale(1.02);
              }
            }
          }
          
          .message-files {
            display: flex;
            flex-direction: column;
            gap: 4px;
            margin-bottom: 8px;
            
            .file-item {
              display: flex;
              align-items: center;
              gap: 6px;
              padding: 6px 10px;
              background: rgba(0, 0, 0, 0.03);
              border-radius: 6px;
              font-size: 13px;
              color: #606266;
            }
          }
        }
        
        .typing-indicator {
          color: #909399;
          font-size: 13px;
          display: inline-block;
          animation: pulse 2s infinite;
        }

        .typing-cursor {
          display: inline-block;
          width: 6px;
          height: 16px;
          background-color: #409eff;
          animation: blink 1s infinite;
          vertical-align: middle;
          margin-left: 4px;
        }

        .message-text {
          font-size: 14px;
          line-height: 1.6;
          word-break: break-all;
          
          :deep(p) {
            margin: 0 0 8px 0;
            &:last-child {
              margin-bottom: 0;
            }
          }

          /* 优化列表样式 */
          :deep(ul), :deep(ol) {
            padding-left: 1.5em;
            margin: 0 0 8px 0;
          }

          :deep(li) {
            margin-bottom: 4px;
          }
          
          :deep(.code-block) {
            margin: 8px 0;
            margin-left: 0 !important;
            border-radius: 6px;
            overflow: hidden;
            background: #282c34;
            .code-block-header {
              display: flex;
              justify-content: space-between;
              align-items: center;
              padding: 8px 12px;
              background: #21252b;
              border-bottom: 1px solid #181a1f;
              
              .lang-name {
                font-size: 12px;
                color: #abb2bf;
                text-transform: lowercase;
              }
              
              .copy-code-btn {
                font-size: 12px;
                color: #abb2bf;
                background: transparent;
                border: none;
                cursor: pointer;
                opacity: 0.7;
                padding: 4px 8px;
                border-radius: 4px;
                
                &:hover {
                  background: rgba(255, 255, 255, 0.1);
                  opacity: 1;
                }
              }
            }
            
            pre {
              margin: 0;
              padding: 12px;
              background: #282c34;
              color: #abb2bf;
              overflow-x: auto;
              
              code {
                font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace;
                font-size: 13px;
                line-height: 1.5;
              }
            }
          }
          
          :deep(pre:not(.code-block pre)) {
            background: #282c34;
            color: #abb2bf;
            padding: 12px;
            border-radius: 6px;
            overflow-x: auto;
            margin: 8px 0;
          }
          
          :deep(code) {
            font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace;
          }
          
          :deep(img) {
            max-width: 100%;
            border-radius: 4px;
          }
        }
      }
      
      .message-footer {
        display: flex;
        align-items: center;
        gap: 12px;
        padding: 0 4px;
        font-size: 12px;
        color: #909399;
        opacity: 0;
        transition: opacity 0.3s;
        
        .footer-left {
          display: flex;
          align-items: center;
        }
        
        .footer-right {
          display: flex;
          align-items: center;
        }
        
        .action-btn {
          font-size: 12px;
          padding: 0;
          height: auto;
          color: #909399;
          
          &:hover {
            color: #409eff;
          }
        }
      }
      
      &:hover .message-footer {
        opacity: 1;
      }
    }
  }

  .chat-input-area {
    padding: 16px 20px;
    border-top: 1px solid #e4e7ed;
    background: #fff;
    
    .chat-options-bar {
      display: flex;
      gap: 12px;
      margin-bottom: 12px;
      
      .option-item {
        display: flex;
        align-items: center;
        gap: 6px;
        font-size: 13px;
        color: #606266;
        cursor: pointer;
        padding: 6px 10px;
        border-radius: 6px;
        transition: all 0.2s;
        border: 1px solid transparent;

        &:hover {
          background: #f5f7fa;
        }

        &.active {
          color: var(--el-color-primary);
          background: var(--el-color-primary-light-9);
          border-color: var(--el-color-primary-light-7);
        }

        &.disabled {
          color: #c0c4cc;
          cursor: not-allowed;
          background: none;
          
          &:hover {
            background: none;
          }
        }
      }
    }

    .file-preview-area {
      margin-bottom: 12px;
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      
      .preview-tag {
        display: flex;
        align-items: center;
        gap: 4px;
      }
    }

    .input-wrapper {
      position: relative;
      
      .send-btn {
        position: absolute;
        right: 12px;
        bottom: 12px;
      }
      
      :deep(.el-textarea__inner) {
        padding-right: 50px;
        border-radius: 8px;
        min-height: 80px !important;
      }
    }
  }
}

@keyframes bounce {
  0%, 80%, 100% {
    transform: scale(0);
  }
  40% {
    transform: scale(1);
  }
}
@keyframes blink {
  0%, 100% { opacity: 1; }
  50% { opacity: 0; }
}
</style>
