<template>
  <div class="ai-agent" :class="{ expanded: !isBall }">
    <div v-if="isBall" class="ball-container" ref="ballRef">
            <!-- 悬浮球 -->
      <div 
        class="chat-ball" 
        @mousedown="startDrag"
        @touchstart="startDrag"
        @click="expandChat"
        :style="ballStyle"
      >
        <img src="@/assets/imgs/chat-ball.svg" alt="AI助手" class="ball-icon" />
        <!-- 未读消息提示 -->
        <div v-if="unreadCount > 0" class="unread-badge">{{ unreadCount }}</div>
      </div>
        </div>

        <div v-else class="ai-agent-content">
      <!-- 左侧：对话历史列表 -->
      <div class="ai-agent-history" :class="{ collapsed: historyCollapsed }">
        <div class="history-header">
          <h3>对话历史</h3>
          <button @click="historyCollapsed = !historyCollapsed" class="collapse-btn">
            {{ historyCollapsed ? '展开' : '收起' }}
          </button>
        </div>

        <div v-if="!historyCollapsed" class="history-list">
          <!-- 新建对话按钮 -->
          <button class="new-chat-btn" @click="createNewConversation">
            + 新建对话
          </button>

          <!-- 历史对话列表 -->
          <div 
            v-for="conv in conversations" 
            :key="conv.id"
            class="conversation-item"
            :class="{ active: currentConversation?.id === conv.id }"
            @click="selectConversation(conv)"
          >
            <div class="conv-title">{{ conv.title || '新对话' }}</div>
            <div class="conv-time">{{ formatTime(conv.updateTime) }}</div>
            <button 
              class="delete-conv-btn" 
              @click.stop="deleteConversationConfirm(conv.id || '')"
            >
              ×
            </button>
          </div>

          <!-- 加载更多 -->
          <div v-if="hasMoreConversations" class="load-more">
            <button @click="loadMoreConversations">加载更多</button>
          </div>
        </div>
            </div>

      <!-- 右侧：当前对话窗口 -->
            <div class="ai-agent-current-chat">
                <div class="current-chat-header">
                    <div class="current-chat-title">
            <input 
              v-if="editingTitle"
              v-model="editTitleValue"
              @blur="saveTitle"
              @keyup.enter="saveTitle"
              class="title-input"
              autofocus
            />
            <span v-else @dblclick="startEditTitle">
              {{ currentConversation?.title || '新对话' }}
            </span>
                    </div>
                    <div class="current-chat-action">
            <button @click="minimizeChat" class="action-btn" title="最小化">
              <span>−</span>
            </button>
            <button @click="clearCurrentConversation" class="action-btn" title="清空对话">
              <img src="@/assets/imgs/trashbin-grey.svg" alt="清空" class="icon">
            </button>
          </div>
        </div>

        <!-- 对话内容区域 -->
        <div class="current-chat-content" ref="chatContentRef">
          <!-- 欢迎消息 -->
          <div v-if="messages.length === 0" class="welcome-message">
            <div class="welcome-icon">🤖</div>
            <h2>你好！我是AI助手</h2>
            <p>有什么可以帮助你的吗？</p>
          </div>

          <!-- 消息列表 -->
          <div v-for="message in messages" :key="message.id" class="message-item">
            <!-- 用户消息 -->
            <div v-if="message.role === 'user'" class="message user-message">
              <div class="message-avatar">
                <div class="avatar-circle">👤</div>
              </div>
              <div class="message-content">
                <div class="message-text">{{ message.content }}</div>
                <div class="message-time">{{ formatMessageTime(message.createTime) }}</div>
              </div>
            </div>

            <!-- AI 消息 -->
            <div v-else class="message ai-message">
              <div class="message-avatar">
                <div class="avatar-circle ai-avatar">🤖</div>
              </div>
              <div class="message-content">
                <div class="message-text" v-html="formatMarkdown(message.content || '')"></div>
                <div class="message-footer">
                  <div class="message-time">{{ formatMessageTime(message.createTime) }}</div>
                  <div class="message-actions">
                    <button 
                      @click="copyMessage(message.content || '')" 
                      class="msg-action-btn"
                      title="复制"
                    >
                      📋
                    </button>
                    <button 
                      @click="regenerateMessage(message.id || '')" 
                      class="msg-action-btn"
                      title="重新生成"
                    >
                      🔄
                    </button>
                    <button 
                      @click="rateMessage(message.id || '', 1)" 
                      class="msg-action-btn"
                      :class="{ active: message.rating === 1 }"
                      title="好评"
                    >
                      👍
                    </button>
                    <button 
                      @click="rateMessage(message.id || '', -1)" 
                      class="msg-action-btn"
                      :class="{ active: message.rating === -1 }"
                      title="差评"
                    >
                      👎
                    </button>
                  </div>
                </div>
              </div>
                    </div>
                </div>

          <!-- 加载中提示 -->
          <div v-if="isGenerating" class="message ai-message generating">
            <div class="message-avatar">
              <div class="avatar-circle ai-avatar">🤖</div>
            </div>
            <div class="message-content">
              <div class="typing-indicator">
                <span></span>
                <span></span>
                <span></span>
              </div>
            </div>
          </div>
                </div>

        <!-- 输入区域 -->
                <div class="current-chat-input">
          <!-- 已上传文件列表 -->
          <div v-if="uploadedFiles.length > 0" class="input-files">
            <div 
              v-for="(file, index) in uploadedFiles" 
              :key="index"
              class="uploaded-file-item"
            >
              <span class="file-name">{{ file.name }}</span>
              <button @click="removeUploadedFile(index)" class="remove-file-btn">×</button>
            </div>
                    </div>

          <!-- 输入框 -->
          <div class="input-area">
            <textarea 
              v-model="inputMessage"
              class="input-text" 
              placeholder="请输入问题..."
              @keydown.enter.exact.prevent="sendMessage"
              @keydown.shift.enter="handleShiftEnter"
              ref="inputRef"
              rows="1"
            />
                    
                    <div class="input-action">
              <button @click="triggerFileUpload" class="action-icon-btn" title="上传文件">
                            <img src="@/assets/imgs/link.svg" alt="上传文件" class="link-icon"/>
                        </button>
              <button 
                @click="sendMessage" 
                class="action-icon-btn send-btn"
                :disabled="!canSend"
                title="发送 (Enter)"
              >
                            <img src="@/assets/imgs/send.svg" alt="发送" class="send-icon"/>
                        </button>
                    </div>
          </div>

          <!-- 隐藏的文件上传input -->
          <input 
            type="file" 
            ref="fileInputRef"
            @change="handleFileUpload"
            style="display: none"
            multiple
            accept=".txt,.pdf,.doc,.docx,.md"
          />
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { chatApi, chatHistoryApi } from '../../../apis/ai';
import type { AiConversation, AiMessage } from '../../../types/ai';

interface AIAgentProps {
  isBall?: boolean;
  expanded?: boolean;
  agentId?: string;
}

const props = withDefaults(defineProps<AIAgentProps>(), {
  isBall: true,
  expanded: false,
  agentId: 'default'
});

// ===== 悬浮球相关 =====
const isBall = ref(props.isBall);
const ballRef = ref<HTMLElement | null>(null);
const isDragging = ref(false);
const dragStartX = ref(0);
const dragStartY = ref(0);
const ballX = ref(0);
const ballY = ref(0);
const unreadCount = ref(0);

const ballStyle = computed(() => ({
  left: `${ballX.value}px`,
  top: `${ballY.value}px`
}));

// 初始化悬浮球位置
onMounted(() => {
  // 默认位置：右下角
  ballX.value = window.innerWidth - 100;
  ballY.value = window.innerHeight - 100;
  
  // 加载最近对话
  loadRecentConversations();
});

// 开始拖动
function startDrag(e: MouseEvent | TouchEvent) {
  isDragging.value = true;
  
  const clientX = 'touches' in e ? e.touches[0].clientX : e.clientX;
  const clientY = 'touches' in e ? e.touches[0].clientY : e.clientY;
  
  dragStartX.value = clientX - ballX.value;
  dragStartY.value = clientY - ballY.value;
  
  document.addEventListener('mousemove', onDrag);
  document.addEventListener('touchmove', onDrag);
  document.addEventListener('mouseup', stopDrag);
  document.addEventListener('touchend', stopDrag);
  
  e.preventDefault();
}

// 拖动中
function onDrag(e: MouseEvent | TouchEvent) {
  if (!isDragging.value) return;
  
  const clientX = 'touches' in e ? e.touches[0].clientX : e.clientX;
  const clientY = 'touches' in e ? e.touches[0].clientY : e.clientY;
  
  ballX.value = clientX - dragStartX.value;
  ballY.value = clientY - dragStartY.value;
  
  e.preventDefault();
}

// 停止拖动
function stopDrag() {
  if (!isDragging.value) return;
  
  isDragging.value = false;
  
  document.removeEventListener('mousemove', onDrag);
  document.removeEventListener('touchmove', onDrag);
  document.removeEventListener('mouseup', stopDrag);
  document.removeEventListener('touchend', stopDrag);
  
  // 自动吸附到左右两侧
  const windowWidth = window.innerWidth;
  const ballWidth = 80;
  
  if (ballX.value < windowWidth / 2) {
    // 吸附到左侧
    ballX.value = 20;
  } else {
    // 吸附到右侧
    ballX.value = windowWidth - ballWidth - 20;
  }
  
  // 限制垂直位置
  const windowHeight = window.innerHeight;
  const ballHeight = 80;
  
  if (ballY.value < 20) {
    ballY.value = 20;
  } else if (ballY.value > windowHeight - ballHeight - 20) {
    ballY.value = windowHeight - ballHeight - 20;
  }
}

// 展开对话
function expandChat() {
  if (isDragging.value) return; // 拖动时不触发
  isBall.value = false;
}

// 最小化对话
function minimizeChat() {
  isBall.value = true;
}

// ===== 对话历史相关 =====
const historyCollapsed = ref(false);
const conversations = ref<AiConversation[]>([]);
const currentConversation = ref<AiConversation | null>(null);
const hasMoreConversations = ref(false);
const conversationPage = ref(1);

// 加载最近对话
async function loadRecentConversations() {
  try {
    const result = await chatHistoryApi.getRecentConversations(10);
    if (result.success && result.dataList) {
      conversations.value = result.dataList;
      
      // 如果有对话，自动选中第一个
      if (conversations.value.length > 0 && !currentConversation.value) {
        await selectConversation(conversations.value[0]);
      }
    }
  } catch (error) {
    console.error('加载对话历史失败:', error);
  }
}

// 加载更多对话
async function loadMoreConversations() {
  conversationPage.value++;
  // TODO: 实现分页加载
}

// 新建对话
async function createNewConversation() {
  try {
    const result = await chatApi.createConversation(props.agentId);
    if (result.success && result.data) {
      currentConversation.value = result.data;
      conversations.value.unshift(result.data);
      messages.value = [];
      ElMessage.success('已创建新对话');
    }
  } catch (error) {
    console.error('创建对话失败:', error);
    ElMessage.error('创建对话失败');
  }
}

// 选择对话
async function selectConversation(conv: AiConversation) {
  currentConversation.value = conv;
  if (conv.id) {
    await loadMessages(conv.id);
  }
}

// 删除对话确认
async function deleteConversationConfirm(conversationId: string) {
  try {
    await ElMessageBox.confirm('确定要删除这个对话吗？', '提示', {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    const result = await chatApi.deleteConversation(conversationId);
    if (result.success) {
      conversations.value = conversations.value.filter(c => c.id !== conversationId);
      
      if (currentConversation.value?.id === conversationId) {
        currentConversation.value = null;
        messages.value = [];
        
        // 选择第一个对话
        if (conversations.value.length > 0) {
          await selectConversation(conversations.value[0]);
        }
      }
      
      ElMessage.success('对话已删除');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除对话失败:', error);
      ElMessage.error('删除对话失败');
    }
  }
}

// 清空当前对话
async function clearCurrentConversation() {
  try {
    await ElMessageBox.confirm('确定要清空当前对话吗？', '提示', {
      confirmButtonText: '清空',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    messages.value = [];
    ElMessage.success('对话已清空');
  } catch (error) {
    // 用户取消
  }
}

// 编辑标题
const editingTitle = ref(false);
const editTitleValue = ref('');

function startEditTitle() {
  if (!currentConversation.value) return;
  editingTitle.value = true;
  editTitleValue.value = currentConversation.value.title || '';
}

async function saveTitle() {
  if (!currentConversation.value) return;
  
  editingTitle.value = false;
  
  if (editTitleValue.value && editTitleValue.value !== currentConversation.value.title) {
    currentConversation.value.title = editTitleValue.value;
    
    try {
      await chatApi.updateConversation(currentConversation.value);
      ElMessage.success('标题已更新');
    } catch (error) {
      console.error('更新标题失败:', error);
      ElMessage.error('更新标题失败');
    }
  }
}

// ===== 消息相关 =====
const messages = ref<AiMessage[]>([]);
const inputMessage = ref('');
const isGenerating = ref(false);
const chatContentRef = ref<HTMLElement | null>(null);
const inputRef = ref<HTMLTextAreaElement | null>(null);

// 加载消息
async function loadMessages(conversationId: string) {
  try {
    const result = await chatApi.listMessages(conversationId);
    if (result.success && result.data) {
      messages.value = result.data;
      await nextTick();
      scrollToBottom();
    }
  } catch (error) {
    console.error('加载消息失败:', error);
  }
}

// 发送消息
async function sendMessage() {
  if (!canSend.value) return;
  
  const message = inputMessage.value.trim();
  if (!message) return;
  
  // 如果没有当前对话，创建新对话
  if (!currentConversation.value) {
    await createNewConversation();
    if (!currentConversation.value) return;
  }
  
  // 添加用户消息到界面
  const userMessage: AiMessage = {
    id: `temp-${Date.now()}`,
    conversationID: currentConversation.value.id,
    role: 'user',
    content: message,
    createTime: new Date().toISOString(),
    updateTime: new Date().toISOString()
  };
  
  messages.value.push(userMessage);
  inputMessage.value = '';
  
  await nextTick();
  scrollToBottom();
  
  // 调用API
  isGenerating.value = true;
  
  try {
    let aiMessageContent = '';
    
    await chatApi.streamChat(
      {
        agentId: props.agentId,
        conversationId: currentConversation.value.id,
        query: message,
        knowledgeIds: []
      },
      {
        onMessage: (chunk: string) => {
          aiMessageContent += chunk;
          
          // 更新或创建AI消息
          const lastMessage = messages.value[messages.value.length - 1];
          if (lastMessage && lastMessage.role === 'assistant') {
            lastMessage.content = aiMessageContent;
          } else {
            messages.value.push({
              id: `temp-ai-${Date.now()}`,
              conversationID: currentConversation.value!.id,
              role: 'assistant',
              content: aiMessageContent,
              createTime: new Date().toISOString(),
              updateTime: new Date().toISOString()
            });
          }
          
          nextTick(() => scrollToBottom());
        },
        onMessageEnd: () => {
          // 消息结束
          isGenerating.value = false;
        },
        onError: (error: Error) => {
          console.error('对话失败:', error);
          ElMessage.error('对话失败，请重试');
          isGenerating.value = false;
        }
      }
    );
  } catch (error) {
    console.error('发送消息失败:', error);
    ElMessage.error('发送消息失败');
    isGenerating.value = false;
  }
}

// Shift+Enter 换行
function handleShiftEnter() {
  // 允许默认行为（换行）
}

// 是否可以发送
const canSend = computed(() => {
  return inputMessage.value.trim().length > 0 && !isGenerating.value;
});

// 滚动到底部
function scrollToBottom() {
  if (chatContentRef.value) {
    chatContentRef.value.scrollTop = chatContentRef.value.scrollHeight;
  }
}

// 复制消息
async function copyMessage(content: string) {
  try {
    await navigator.clipboard.writeText(content);
    ElMessage.success('已复制到剪贴板');
  } catch (error) {
    ElMessage.error('复制失败');
  }
}

// 重新生成消息
async function regenerateMessage(messageId: string) {
  if (isGenerating.value) return;
  
  isGenerating.value = true;
  
  try {
    let aiMessageContent = '';
    
    await chatApi.regenerateAnswer(
      messageId,
      {
        onMessage: (chunk: string) => {
          aiMessageContent += chunk;
          
          // 找到对应消息并更新
          const messageIndex = messages.value.findIndex(m => m.id === messageId);
          if (messageIndex !== -1) {
            messages.value[messageIndex].content = aiMessageContent;
          }
          
          nextTick(() => scrollToBottom());
        },
        onMessageEnd: () => {
          isGenerating.value = false;
        },
        onError: (error: Error) => {
          console.error('重新生成失败:', error);
          ElMessage.error('重新生成失败');
          isGenerating.value = false;
        }
      }
    );
  } catch (error) {
    console.error('重新生成失败:', error);
    ElMessage.error('重新生成失败');
    isGenerating.value = false;
  }
}

// 评价消息
async function rateMessage(messageId: string, rating: number) {
  try {
    const message = messages.value.find(m => m.id === messageId);
    if (!message) return;
    
    // 如果已经评价相同，则取消评价
    const newRating = message.rating === rating ? 0 : rating;
    
    const result = await chatApi.rateMessage(messageId, newRating);
    if (result.success) {
      message.rating = newRating;
      ElMessage.success(newRating === 0 ? '已取消评价' : '评价成功');
    }
  } catch (error) {
    console.error('评价失败:', error);
    ElMessage.error('评价失败');
  }
}

// ===== 文件上传相关 =====
const uploadedFiles = ref<File[]>([]);
const fileInputRef = ref<HTMLInputElement | null>(null);

function triggerFileUpload() {
  fileInputRef.value?.click();
}

function handleFileUpload(e: Event) {
  const target = e.target as HTMLInputElement;
  const files = target.files;
  
  if (files && files.length > 0) {
    uploadedFiles.value.push(...Array.from(files));
    ElMessage.success(`已添加 ${files.length} 个文件`);
  }
  
  // 清空input，允许重复选择同一文件
  target.value = '';
}

function removeUploadedFile(index: number) {
  uploadedFiles.value.splice(index, 1);
}

// ===== 工具函数 =====
function formatTime(dateStr: string | undefined) {
  if (!dateStr) return '';
  
  const date = new Date(dateStr);
  const now = new Date();
  const diff = now.getTime() - date.getTime();
  
  const minutes = Math.floor(diff / 60000);
  const hours = Math.floor(diff / 3600000);
  const days = Math.floor(diff / 86400000);
  
  if (minutes < 1) return '刚刚';
  if (minutes < 60) return `${minutes}分钟前`;
  if (hours < 24) return `${hours}小时前`;
  if (days < 7) return `${days}天前`;
  
  return date.toLocaleDateString();
}

function formatMessageTime(dateStr: string | undefined) {
  if (!dateStr) return '';
  
  const date = new Date(dateStr);
  return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
}

function formatMarkdown(content: string) {
  // 简单的 Markdown 转换（可以使用 marked.js 等库进行更复杂的转换）
  let html = content;
  
  // 代码块
  html = html.replace(/```(\w+)?\n([\s\S]*?)```/g, '<pre><code>$2</code></pre>');
  
  // 行内代码
  html = html.replace(/`([^`]+)`/g, '<code>$1</code>');
  
  // 加粗
  html = html.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
  
  // 斜体
  html = html.replace(/\*([^*]+)\*/g, '<em>$1</em>');
  
  // 换行
  html = html.replace(/\n/g, '<br>');
  
  return html;
}

// 清理
onUnmounted(() => {
  document.removeEventListener('mousemove', onDrag);
  document.removeEventListener('touchmove', onDrag);
  document.removeEventListener('mouseup', stopDrag);
  document.removeEventListener('touchend', stopDrag);
});
</script>

<style scoped lang="scss">
.ai-agent {
  position: fixed;
  z-index: 9999;
  
  &.expanded {
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 90vw;
    max-width: 1200px;
    height: 80vh;
    max-height: 800px;
  }
}

/* ===== 悬浮球样式 ===== */
.ball-container {
  position: fixed;
  z-index: 9999;
}

.chat-ball {
    width: 80px;
    height: 80px;
    cursor: pointer;
  position: relative;
  transition: transform 0.3s ease;
  user-select: none;
  
  &:hover {
    transform: scale(1.1);
  }
  
  &:active {
    transform: scale(0.95);
  }
  
  .ball-icon {
    width: 100%;
    height: 100%;
    border-radius: 50%;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }
  
  .unread-badge {
    position: absolute;
    top: 0;
    right: 0;
    background: #E7000B;
    color: white;
    border-radius: 50%;
    width: 24px;
    height: 24px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
    font-weight: bold;
  }
}

/* ===== 展开的对话界面 ===== */
.ai-agent-content {
    width: 100%;
    height: 100%;
    background-color: #fff;
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  display: flex;
  overflow: hidden;
}

/* ===== 左侧对话历史 ===== */
.ai-agent-history {
  width: 280px;
  background: #F9FAFB;
  border-right: 1px solid #E5E7EB;
  display: flex;
  flex-direction: column;
  transition: width 0.3s ease;
  
  &.collapsed {
    width: 60px;
  }
  
  .history-header {
    padding: 20px;
    border-bottom: 1px solid #E5E7EB;
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    h3 {
      margin: 0;
      font-size: 16px;
      font-weight: 600;
      color: #101828;
    }
    
    .collapse-btn {
      background: none;
      border: none;
      cursor: pointer;
      font-size: 12px;
      color: #6B7280;
      
      &:hover {
        color: #E7000B;
      }
    }
  }
  
  .history-list {
    flex: 1;
    overflow-y: auto;
    padding: 12px;
  }
  
  .new-chat-btn {
    width: 100%;
    padding: 12px;
    background: #E7000B;
    color: white;
    border: none;
    border-radius: 8px;
    cursor: pointer;
    font-size: 14px;
    font-weight: 500;
    margin-bottom: 12px;
    
    &:hover {
      background: #C90009;
    }
  }
  
  .conversation-item {
    padding: 12px;
    background: white;
    border-radius: 8px;
    margin-bottom: 8px;
    cursor: pointer;
    position: relative;
    transition: all 0.2s;
    
    &:hover {
      background: #EFF6FF;
      
      .delete-conv-btn {
        opacity: 1;
      }
    }
    
    &.active {
      background: #E7000B;
      color: white;
      
      .conv-title,
      .conv-time {
        color: white;
      }
    }
    
    .conv-title {
      font-size: 14px;
      font-weight: 500;
      color: #101828;
      margin-bottom: 4px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    
    .conv-time {
      font-size: 12px;
      color: #6B7280;
    }
    
    .delete-conv-btn {
      position: absolute;
      top: 8px;
      right: 8px;
      background: rgba(0, 0, 0, 0.1);
      border: none;
      border-radius: 50%;
      width: 20px;
      height: 20px;
      cursor: pointer;
      opacity: 0;
      transition: opacity 0.2s;
      
      &:hover {
        background: rgba(0, 0, 0, 0.2);
      }
    }
  }
  
  .load-more {
    text-align: center;
    padding: 12px;
    
    button {
      background: none;
      border: none;
      color: #E7000B;
      cursor: pointer;
      font-size: 14px;
      
      &:hover {
        text-decoration: underline;
      }
    }
  }
}

/* ===== 右侧当前对话 ===== */
.ai-agent-current-chat {
  flex: 1;
  display: flex;
  flex-direction: column;
  
  .current-chat-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 24px;
    border-bottom: 1px solid #E5E7EB;
    
    .current-chat-title {
      font-size: 16px;
      font-weight: 600;
      color: #101828;
      flex: 1;
      
      .title-input {
        width: 100%;
        border: 1px solid #E5E7EB;
        border-radius: 8px;
        padding: 8px 12px;
        font-size: 16px;
        font-weight: 600;
        
        &:focus {
          outline: none;
          border-color: #E7000B;
        }
      }
      
      span {
        cursor: text;
        
        &:hover {
          color: #E7000B;
        }
      }
    }
    
    .current-chat-action {
      display: flex;
      gap: 8px;
      
      .action-btn {
        width: 32px;
        height: 32px;
        background: none;
        border: 1px solid #E5E7EB;
        border-radius: 8px;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        
        &:hover {
          background: #F3F4F6;
        }
        
        .icon {
          width: 18px;
          height: 18px;
        }
        
        span {
          font-size: 20px;
          color: #6B7280;
        }
      }
    }
  }
  
  .current-chat-content {
    flex: 1;
    overflow-y: auto;
    padding: 24px;
    
    .welcome-message {
      text-align: center;
      padding: 60px 20px;
      
      .welcome-icon {
        font-size: 64px;
        margin-bottom: 16px;
      }
      
      h2 {
        font-size: 24px;
        font-weight: 600;
        color: #101828;
        margin: 0 0 8px 0;
      }
      
      p {
        font-size: 16px;
        color: #6B7280;
        margin: 0;
      }
    }
    
    .message-item {
      margin-bottom: 24px;
      
      .message {
        display: flex;
        gap: 12px;
        
        .message-avatar {
          flex-shrink: 0;
          
          .avatar-circle {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            background: #E5E7EB;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 20px;
            
            &.ai-avatar {
              background: #EFF6FF;
            }
          }
        }
        
        .message-content {
          flex: 1;
          max-width: 70%;
          
          .message-text {
            padding: 12px 16px;
            border-radius: 12px;
            font-size: 14px;
            line-height: 1.6;
            word-wrap: break-word;
            
            :deep(code) {
              background: #F3F4F6;
              padding: 2px 6px;
              border-radius: 4px;
              font-family: 'Courier New', monospace;
              font-size: 13px;
            }
            
            :deep(pre) {
              background: #1F2937;
              color: #F9FAFB;
              padding: 12px;
              border-radius: 8px;
              overflow-x: auto;
              
              code {
                background: none;
                color: inherit;
                padding: 0;
              }
            }
          }
          
          .message-time {
            font-size: 12px;
            color: #9CA3AF;
            margin-top: 4px;
          }
          
          .message-footer {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 4px;
            
            .message-actions {
              display: flex;
              gap: 4px;
              opacity: 0;
              transition: opacity 0.2s;
              
              .msg-action-btn {
                background: none;
                border: none;
                cursor: pointer;
                font-size: 16px;
                padding: 4px;
                opacity: 0.6;
                
                &:hover {
                  opacity: 1;
                }
                
                &.active {
                  opacity: 1;
                }
              }
            }
          }
          
          &:hover .message-actions {
            opacity: 1;
          }
        }
      }
      
      .user-message {
        .message-content {
          margin-left: auto;
          
          .message-text {
            background: #E7000B;
            color: white;
          }
        }
      }
      
      .ai-message {
        .message-content {
          .message-text {
            background: #F9FAFB;
            color: #101828;
          }
        }
      }
    }
    
    .generating {
      .typing-indicator {
        display: flex;
        gap: 4px;
        padding: 12px 16px;
        background: #F9FAFB;
        border-radius: 12px;
        width: fit-content;
        
        span {
          width: 8px;
          height: 8px;
          border-radius: 50%;
          background: #9CA3AF;
          animation: typing 1.4s infinite;
          
          &:nth-child(2) {
            animation-delay: 0.2s;
          }
          
          &:nth-child(3) {
            animation-delay: 0.4s;
          }
        }
      }
    }
  }
  
  .current-chat-input {
    border-top: 1px solid #E5E7EB;
    padding: 16px 24px;
    
    .input-files {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      margin-bottom: 12px;
      
      .uploaded-file-item {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 6px 12px;
        background: #F3F4F6;
        border-radius: 6px;
        font-size: 13px;
        
        .file-name {
          color: #374151;
        }
        
        .remove-file-btn {
          background: none;
          border: none;
          cursor: pointer;
          color: #9CA3AF;
          font-size: 18px;
          
          &:hover {
            color: #E7000B;
          }
        }
      }
    }
    
    .input-area {
      display: flex;
      gap: 12px;
      align-items: flex-end;
      
      .input-text {
        flex: 1;
        padding: 12px 16px;
        border: 1px solid #E5E7EB;
        border-radius: 12px;
        font-size: 14px;
        resize: none;
        max-height: 120px;
        font-family: inherit;
        
        &:focus {
          outline: none;
          border-color: #E7000B;
        }
        
        &::placeholder {
          color: #9CA3AF;
        }
      }
      
      .input-action {
        display: flex;
        gap: 8px;
        
        .action-icon-btn {
          width: 40px;
          height: 40px;
          background: #F9FAFB;
          border: 1px solid #E5E7EB;
    border-radius: 10px;
          cursor: pointer;
    display: flex;
          align-items: center;
          justify-content: center;
          transition: all 0.2s;
          
          &:hover:not(:disabled) {
            background: #F3F4F6;
          }
          
          &:disabled {
            opacity: 0.5;
            cursor: not-allowed;
          }
          
          &.send-btn {
            background: #E7000B;
            border-color: #E7000B;
            
            &:hover:not(:disabled) {
              background: #C90009;
            }
          }
          
          .link-icon,
          .send-icon {
            width: 20px;
            height: 20px;
          }
        }
      }
    }
  }
}

@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
  }
  30% {
    transform: translateY(-8px);
  }
}

/* 滚动条样式 */
::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-track {
  background: transparent;
}

::-webkit-scrollbar-thumb {
  background: #D1D5DB;
  border-radius: 3px;
  
  &:hover {
    background: #9CA3AF;
  }
}
</style>
