<template>
  <div class="chat-container">
    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 历史面板切换按钮 -->
        <div :class="['toggle-history-btn', { 'btn-hidden': !isHistoryVisible }]" @click="toggleHistoryPanel">
          <el-icon>
            <ArrowLeft v-if="isHistoryVisible" />
            <ArrowRight v-else />
          </el-icon>
        </div>
      <!-- 左侧历史对话面板 -->
      <div class="history-panel" :class="{ 'hidden': !isHistoryVisible }">
        <div class="history-content">
          <div class="history-header">
            <div class="header-left">
              <el-icon><Clock /></el-icon>
              <h3>聊天</h3>
            </div>
            <div class="header-right">
              <el-button type="primary" @click="createNewConversation">
                <el-icon><Plus /></el-icon>
                新对话
              </el-button>
              <el-button type="default" @click="clearChatHistory">
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </div>
          
          <!-- 搜索框 -->
          <div class="history-search">
            <el-input
              :model-value="chatStore.searchQuery"
              @input="handleSearch"
              placeholder="搜索对话..."
              size="small"
              clearable
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
          
          <div class="history-list">
            <div 
              v-for="conversation in filteredConversations" 
              :key="conversation.id"
              class="history-item"
              @click="selectConversation(conversation)"
            >
              <div class="conversation-info">
                <div class="conversation-title">{{ conversation.title }}</div>
                <div class="conversation-meta">
                  <span class="conversation-time">{{ formatConversationTime(conversation.updated_at) }}</span>
                  <span class="conversation-count">{{ conversation.message_count }}条消息</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 中间对话区域 -->
      <div class="chat-area">
        <!-- 消息列表 -->
        <div class="messages-container" ref="messagesContainer">
          <!-- 欢迎消息 -->
          <div v-if="messages.length === 0" class="welcome-message">
            <div class="welcome-content">
              <h3>{{ chatModes.find(m => m.key === currentMode)?.label }}模式</h3>
              <p>{{ chatModes.find(m => m.key === currentMode)?.description }}</p>
              
              <div class="quick-actions">
                <div class="quick-action-title">快速开始：</div>
                <div class="quick-buttons">
                  <el-button 
                    v-for="action in quickActions" 
                    :key="action.text"
                    size="small"
                    type="primary"
                    plain
                    @click="inputMessage = action.text; sendMessage()"
                  >
                    {{ action.text }}
                  </el-button>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 真实消息 -->
          <div v-for="message in messages" :key="message.id" class="message-item">
            <div :class="['message', message.role]">
              <div class="message-avatar">
                <el-avatar v-if="message.role === 'user'" :size="32">
                  <el-icon><User /></el-icon>
                </el-avatar>
                <el-avatar v-else :size="32" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%)">
                  <el-icon><Service /></el-icon>
                </el-avatar>
              </div>
              
              <div class="message-content">
                <!-- 智能体模式下的简化状态显示 -->
                <div v-if="message.role === 'assistant' && currentMode === 'agent' && message.agent_data && message.agent_data.status !== 'completed'" class="agent-status-simple">
                  <!-- 显示最新步骤的图标和状态文字，但只在未完成时显示 -->
                  <div v-if="message.agent_data.steps && message.agent_data.steps.length > 0" class="agent-current-status">
                    <template v-for="(step, index) in message.agent_data.steps" :key="step.id">
                      <div v-if="index === message.agent_data.steps.length - 1 && step.type !== 'response' && !hasResponseStep(message.agent_data.steps)" class="current-step-display">
                        <span v-if="step.type === 'thinking'" class="step-status">
                          <span class="type-icon">🤔</span>
                          <span class="status-text">大模型思考中</span>
                        </span>
                        <span v-else-if="step.type.includes('tool')" class="step-status">
                          <span class="type-icon">🔧</span>
                          <span class="status-text">正在调用工具: {{ step.tool_name || '未知工具' }}</span>
                        </span>
                        <span v-else class="step-status">
                          <span class="type-icon">📝</span>
                          <span class="status-text">处理中</span>
                        </span>
                      </div>
                    </template>
                  </div>
                </div>
                
                <!-- 如果有状态信息，显示状态 -->
                <div v-if="message.status" class="message-status">
                  <el-icon class="status-icon"><Loading /></el-icon>
                  <span>{{ message.status }}</span>
                </div>
                <!-- 如果是空的assistant消息且没有状态，显示打字指示器 -->
                <div v-else-if="message.role === 'assistant' && message.content === ''" class="typing-indicator" @click="showAgentDrawer = true">
                  <span></span>
                  <span></span>
                  <span></span>
                </div>
                <!-- 智能体模式：只显示最后一个response类型的内容 -->
                <div v-else-if="message.role === 'assistant' && currentMode === 'agent'" class="message-text">
                  <!-- 检查是否有response类型的步骤，如果有则显示最后一个response的内容 -->
                  <div v-if="message.agent_data && message.agent_data.steps">
                    <div v-if="getLastResponseStep(message.agent_data.steps)" v-html="renderMarkdown(getLastResponseStep(message.agent_data.steps).content)"></div>
                  </div>
                  <!-- 如果没有response步骤但有消息内容，显示消息内容 -->
                  <div v-else-if="message.content" v-html="renderMarkdown(message.content)"></div>
                </div>
                <!-- 普通模式显示正常消息内容 -->
                <div v-else class="message-text" v-html="renderMarkdown(message.content)"></div>
                <div class="message-time">{{ formatTime(message.created_at) }}</div>
              </div>
            </div>
          </div>
          
          <!-- 加载中状态 - 只在没有空的assistant消息时显示 -->
          <div v-if="isLoading && !hasEmptyAssistantMessage" class="message-item">
            <div class="message assistant">
              <div class="message-avatar">
                <el-avatar :size="32" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%)">
                  <el-icon><Service /></el-icon>
                </el-avatar>
              </div>
              <div class="message-content">
                <div class="typing-indicator" @click="showAgentDrawer = true">
                  <span></span>
                  <span></span>
                  <span></span>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 输入区域 -->
        <div class="input-area">
          <div class="input-container">
            <el-input
              v-model="inputMessage"
              type="textarea"
              :rows="3"
              placeholder="输入您的问题..."
              @keydown.ctrl.enter="sendMessage"
              :disabled="isLoading"
            />
            <div class="input-actions">

              <!-- 对话模式切换下拉按钮 -->
              <div style="display: flex; gap: 10px; align-items: center;">
                <el-dropdown @command="switchMode">
                  <span class="el-dropdown-link" style="cursor: pointer; padding: 4px 8px; border-radius: 4px; transition: background-color 0.3s; display: flex; align-items: center; gap: 4px; color: white;">
                    <el-icon><component :is="chatModes.find(m => m.key === currentMode)?.icon" /></el-icon>
                    {{ chatModes.find(m => m.key === currentMode)?.label }}
                    <el-icon class="el-icon--right"><ArrowDown /></el-icon>
                  </span>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item 
                        v-for="mode in chatModes" 
                        :key="mode.key"
                        :command="mode.key"
                        style="display: flex; align-items: center; gap: 4px;"
                      >
                        <el-icon><component :is="mode.icon" /></el-icon>
                        <span>{{ mode.label }}</span>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
              <div style="display: flex; gap: 10px; align-items: center;">
                <div style="margin-right: auto;">
                  <el-upload
                    class="avatar-uploader"
                    :show-file-list="false"
                    :before-upload="handleImageUpload"
                    accept="image/*"
                  >
                    <el-icon><Microphone /></el-icon>
                  </el-upload>
                </div>
                <div style="margin-right: auto;">
                <el-upload
                  class="avatar-uploader"
                  :show-file-list="false"
                  :before-upload="handleImageUpload"
                  accept="image/*"
                >
                  <el-icon><Paperclip /></el-icon>
                </el-upload>
              </div>
              <div style="margin-right: auto;">
                <el-upload
                  class="avatar-uploader"
                  :show-file-list="false"
                  :before-upload="handleImageUpload"
                  accept="image/*"
                >
                  <el-icon><Picture /></el-icon>
                </el-upload>
              </div>
              <el-button 
                type="primary" 
                @click="sendMessage"
                :loading="isLoading"
                :disabled="!inputMessage.trim()"
              >
                发送
              </el-button>
                <div class="input-tips">
                  <span>Ctrl + Enter 发送</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
 
    </div> 
    
    <!-- 智能体思考流程抽屉 -->
    <el-drawer
      v-model="showAgentDrawer"
      title="🤖 智能体思考流程"
      :direction="'rtl'"
      :size="400"
      :show-close="true"
      :with-header="true"
    >
      <div class="agent-header" style="margin-bottom: 16px;">
        <el-tag :type="getAgentStatusType(currentAgentData?.status || 'idle')" size="small">
          {{ getAgentStatusText(currentAgentData?.status || 'idle') }}
        </el-tag>
      </div>
      
      <div v-if="currentAgentData?.steps?.length > 0" class="agent-content">
        <!-- 智能体思考流程列表 -->
        <div class="thinking-steps">
          <div 
            v-for="(step, index) in getUniqueSteps(currentAgentData.steps)" 
            :key="step.id || index" 
            class="thinking-step"
            :class="`step-${step.type}`"
          >
            <!-- 简化的步骤显示 -->
            <div class="step-header">
              <div class="step-type-info">
                <span v-if="step.type === 'thinking'" class="type-icon">🤔</span>
                <span v-else-if="step.type === 'tools_end'" class="type-icon">🔧</span>
                <span v-else-if="step.type === 'response_start'" class="type-icon">💬</span>
                <span v-else-if="step.type === 'complete'" class="type-icon">✅</span>
                <span v-else class="type-icon">📝</span>
                
                <span class="type-name">
                  <span v-if="step.type === 'thinking'">思考中</span>
                  <span v-else-if="step.type === 'tools_end'">调用工具</span>
                  <span v-else-if="step.type === 'response_start'">正在输出</span>
                  <span v-else-if="step.type === 'complete'">本次对话过程完成</span>
                  <span v-else>处理中</span>
                </span>
                
                <span v-if="step.type.includes('tool') && step.tool_name" class="tool-info">
                  : {{ step.tool_name }}
                </span>
              </div>
            </div>
            
            <!-- 内容 -->
             <div v-if="step.content && step.type !== 'response'" class="step-content">
               {{ step.content }}
             </div>
             
             <!-- 工具输出 -->
             <div v-if="step.type === 'tools_end' && step.tool_output" class="tool-output">
               <div class="output-label">工具输出:</div>
               <div class="output-content">{{ step.tool_output }}</div>
             </div>
              
              <!-- 时间戳 -->
              <div class="step-timestamp">
                <el-icon><Clock /></el-icon>
                <span>{{ formatTime(step.timestamp) }}</span>
              </div>
          </div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, ElDropdown, ElDropdownMenu, ElDropdownItem } from 'element-plus'
import { 
  ChatDotRound, 
  Collection, 
  Service,
  Promotion,
  Setting,
  Check,
  Loading,
  Clock,
  User,
  Close,
  Search,
  Tools,
  Share,
  Picture,
  Microphone,
  Plus,
  Paperclip,
  Delete,
  ArrowLeft,
  ArrowRight,
  ArrowDown
} from '@element-plus/icons-vue'
import { useChatStore } from '@/stores/chat'
import { useKnowledgeStore } from '@/stores/knowledge'
import { formatTime } from '@/utils'
import MarkdownIt from 'markdown-it'
import hljs from 'highlight.js'
import 'highlight.js/styles/github.css'
import type { ThinkingData } from '@/types'

const router = useRouter()
const chatStore = useChatStore()
const knowledgeStore = useKnowledgeStore()

// 配置markdown渲染器
const md = new MarkdownIt({
  html: true,
  linkify: true,
  typographer: true,
  highlight: function (str, lang) {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return hljs.highlight(str, { language: lang }).value
      } catch (__) {}
    }
    return '' // 使用外部默认转义
  }
})

// 渲染markdown内容的方法
const renderMarkdown = (content: string) => {
  if (!content) return ''
  return md.render(content)
}

// 历史对话相关 - 使用chatStore中的真实数据
const conversations = computed(() => chatStore.conversations)
const filteredConversations = computed(() => {
  if (!chatStore.searchQuery.trim()) {
    return conversations.value
  }
  const query = chatStore.searchQuery.toLowerCase()
  return conversations.value.filter(conv => 
    conv.title.toLowerCase().includes(query)
  )
})

// 对话模式相关
const currentMode = ref('free')
const selectedKnowledgeBase = ref('')
const selectedAgent = ref('')

// 基础状态
const inputMessage = ref('')
const isLoading = ref(false)
const messagesContainer = ref<HTMLElement>()
// 历史面板显示状态
const isHistoryVisible = ref(true)

// 智能体思考流程抽屉显示状态
const showAgentDrawer = ref(false)

// 切换历史面板显示/隐藏
const toggleHistoryPanel = () => {
  isHistoryVisible.value = !isHistoryVisible.value
}

// 检测是否有空的assistant消息（流式传输占位符）
const hasEmptyAssistantMessage = computed(() => {
  const lastMessage = messages.value[messages.value.length - 1]
  return lastMessage && lastMessage.role === 'assistant' && lastMessage.content === ''
})

// 对话模式配置
const chatModes = [
  {
    key: 'free',
    label: '自由对话',
    description: '自然语言交流',
    icon: ChatDotRound
  },
  {
    key: 'agent',
    label: '智能体对话',
    description: '智能体协作处理复杂任务',
    icon: Service
  }
]


// 模拟智能体数据
const availableAgents = ref([
  { id: '1', name: '客服助手', description: '专业的客户服务支持' },
  { id: '2', name: '技术顾问', description: '技术问题解答专家' },
  { id: '3', name: '销售助理', description: '产品推荐和销售支持' }
])

// 快速操作按钮
const quickActions = computed(() => {
  switch (currentMode.value) {
    case 'free':
      return [
        { text: '你好，请介绍一下自己' },
        { text: '帮我写一份工作总结' },
        { text: '推荐一些学习资源' }
      ]
    case 'agent':
      return [
        { text: '杭州和北京现在的天气如何？' },
        { text: '帮我计算 25 * 34 + 67' },
        { text: '搜索最新的AI技术发展' }
      ]
    default:
      return []
  }
})



// 智能体对话相关数据 - 从当前消息的agent_data获取
const currentAgentData = computed(() => {
  const lastMessage = messages.value[messages.value.length - 1]
  if (lastMessage && lastMessage.role === 'assistant' && lastMessage.agent_data) {
    return lastMessage.agent_data
  }
  return {
    status: 'idle',
    steps: [],
    current_tool: null
  }
})

// 获取智能体状态类型
const getAgentStatusType = (status: string) => {
  switch (status) {
    case 'thinking': return 'warning'
    case 'tool_calling': return 'primary'
    case 'responding': return 'success'
    default: return 'info'
  }
}

// 获取智能体状态文本
const getAgentStatusText = (status: string) => {
  switch (status) {
    case 'thinking': return '思考中'
    case 'tool_calling': return '工具调用中'
    case 'responding': return '回复中'
    default: return '空闲'
  }
}

// 获取步骤类型文本
const getStepTypeText = (type) => {
  switch (type) {
    case 'thinking': return '🤔 思考'
    case 'tool_end': return '✅ 工具完成'
    case 'response': return '💬 回复'
    default: return type
  }
}

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
}

// 检查步骤中是否包含response类型
const hasResponseStep = (steps: any[]) => {
  return steps && steps.some(step => step.type === 'response')
}

// 获取最后一个response类型的步骤
const getLastResponseStep = (steps: any[]) => {
  if (!steps) return null
  // 从后往前查找最后一个response类型的步骤
  for (let i = steps.length - 1; i >= 0; i--) {
    if (steps[i].type === 'response') {
      return steps[i]
    }
  }
  return null
}

// 获取所有步骤列表，按时间顺序显示
const getUniqueSteps = (steps: any[]) => {
  if (!steps) return []
  
  // 直接返回所有步骤，按时间顺序排序
  return steps.sort((a, b) => {
    const timeA = new Date(a.timestamp || 0).getTime()
    const timeB = new Date(b.timestamp || 0).getTime()
    return timeA - timeB
  })
}

const messages = computed(() => chatStore.messages)
const knowledgeBases = computed(() => knowledgeStore.knowledgeBases)

onMounted(async () => {
  await Promise.all([
    chatStore.loadConversations(),
    knowledgeStore.loadKnowledgeBases()
  ])
})

// 监听消息变化，自动滚动到底部
watch(messages, () => {
  nextTick(() => {
    scrollToBottom()
  })
}, { deep: true })

// 切换对话模式
const switchMode = (mode: string) => {
  currentMode.value = mode
  
  if (mode !== 'agent') {
    selectedAgent.value = ''
  }
  
  // 强制触发重新渲染
  nextTick(() => {
    // 确保DOM更新
  })
  
  // ElMessage.success(`已切换到${chatModes.find(m => m.key === mode)?.label}模式`)
}

const createNewConversation = async () => {
  try {
    const newConversation = await chatStore.createConversation({
      title: '新对话',
      model_name: 'doubao-lite-4k',
      temperature: '0.7',
      max_tokens: 2048
    })
    
    if (newConversation) {
      chatStore.clearMessages()
    }
  } catch (error) {
    ElMessage.error('创建对话失败')
  }
}

const clearChatHistory = async () => {
  try {
    await chatStore.deleteAllConversations()
    // ElMessage.success('聊天记录列表已清理')
  } catch (error) {
    console.error('Clear chat history failed:', error)
    ElMessage.error('清理聊天记录失败')
  }
}

  // 处理图片上传
  const handleImageUpload = (file: File) => {
    // 这里可以添加图片上传逻辑
    console.log('上传图片:', file);
    // 例如：将图片转换为base64或上传到服务器
    const reader = new FileReader();
    reader.onload = (e) => {
      const imageUrl = e.target?.result as string;
      // 可以将图片URL添加到消息中
      // inputMessage.value += `![图片](${imageUrl})`;
      // 或者单独发送图片消息
      sendMessageWithImage(imageUrl, file.name);
    };
    reader.readAsDataURL(file);
    return false; // 阻止自动上传
  };

  // 发送带图片的消息
  const sendMessageWithImage = async (imageUrl: string, fileName: string) => {
    // 实现发送图片消息的逻辑
    console.log('发送图片消息:', imageUrl, fileName);
    // 可以添加到消息列表中
    messages.value.push({
      id: Date.now().toString(),
      type: 'user',
      content: `![${fileName}](${imageUrl})`,
      image: { url: imageUrl, name: fileName },
      timestamp: new Date().toISOString(),
      status: 'sent'
    });
    // 清空输入框
    inputMessage.value = '';
    // 滚动到底部
    nextTick(() => {
      const messageContainer = document.querySelector('.messages-container');
      if (messageContainer) {
        messageContainer.scrollTop = messageContainer.scrollHeight;
      }
    });
    // 调用API发送图片消息
    try {
      isLoading.value = true;
      // 这里需要根据实际API调整
      const formData = new FormData();
      formData.append('image', imageUrl);
      formData.append('message', inputMessage.value);
      const response = await chatService.sendMessage(formData);
      // 处理响应
    } catch (error) {
      console.error('发送图片消息失败:', error);
    } finally {
      isLoading.value = false;
    }
  };

const sendMessage = async () => {
  if (!inputMessage.value.trim() || isLoading.value) {
    return
  }
  
  const messageContent = inputMessage.value.trim()
  inputMessage.value = ''
  isLoading.value = true
  
  try {
    let conversationId = chatStore.currentConversation?.id
    
    // 如果没有当前对话，创建新对话
    if (!conversationId) {
      const newConversation = await chatStore.createConversation({
        title: messageContent.length > 20 ? messageContent.substring(0, 20) + '...' : messageContent,
        model_name: 'doubao-lite-4k',
        temperature: '0.7',
        max_tokens: 2048
      })
      
      if (!newConversation) {
        throw new Error('创建对话失败')
      }
      
      conversationId = newConversation.id
    }
    
    // 根据当前模式构建消息数据
    const messageData: any = {
      message: messageContent,
      conversation_id: conversationId
    }
    console.log('currentMode.value='+currentMode.value)
    // 如果是智能体模式，添加use_agent参数
    if (currentMode.value === 'agent') {
      messageData.use_langgraph = true
    }
    
    
    // 发送消息
    await chatStore.sendMessageStream(messageData)
    
  } catch (error) {
    console.error('发送消息失败:', error)
    ElMessage.error('发送消息失败，请重试')
  } finally {
    isLoading.value = false
  }
}

const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

// 初始化加载对话列表
onMounted(async () => {
  await Promise.all([
    chatStore.loadConversations(),
    knowledgeStore.loadKnowledgeBases()
  ])
})

const selectConversation = async (conversation: any) => {
  try {
    // 设置当前对话并加载消息
    await chatStore.setCurrentConversation(conversation.id)
    await chatStore.loadMessages(conversation.id, true)
    console.log("conversation::", conversation.id)
    showHistoryPanel.value = false
    // ElMessage.success(`已切换到对话: ${conversation.title}`)
  } catch (error) {
    console.error('切换对话失败:', error)
    // ElMessage.error('切换对话失败')
  }
}

const handleSearch = (query: string) => {
  chatStore.setSearchQuery(query)
}

const formatConversationTime = (timeStr: string) => {
  const time = new Date(timeStr)
  
  // 所有消息都显示完整的年月日时分秒
  return time.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}
</script>

<style scoped>
.chat-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #0f172a;
  color: #e2e8f0;
  flex: 1;
  min-height: 0;
}

/* 模式选择器样式 */
.mode-selector {
  background: #1e293b;
  border-bottom: 1px solid #475569;
  padding: 12px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-shrink: 0;
}

/* 对话模式下拉菜单样式 */
.el-dropdown-link {
  color: white;
}

.el-dropdown-link:hover {
  background-color: rgba(99, 102, 241, 0.1);
  color: white;
}

/* 下拉菜单容器样式 */
.el-dropdown-menu {
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  border: 1px solid #ebeef5;
}

/* 下拉菜单项样式 */
.el-dropdown-item {
  color: #303133;
  transition: all 0.2s ease;
}

.el-dropdown-item:hover {
  background-color: #f5f7fa;
  color: #6366f1;
}

/* 下拉菜单项激活状态 */
.el-dropdown-item.is-active {
  background-color: #ecf5ff;
  color: #6366f1;
}

.mode-config {
  display: flex;
  align-items: center;
  gap: 12px;
}

.config-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 历史面板头部布局优化 */
.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #334155;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
}

.header-left h3 {
  margin: 0;
  font-size: 18px;
  color: #e2e8f0;
  font-weight: 600;
  flex: 1;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 10px;
}

.header-right .el-button {
  font-size: 13px;
  padding: 6px 12px;
}

/* 主要内容区域 */
.main-content {
  display: flex;
  flex: 1;
  width: 100%;
  overflow: hidden;
  gap: 16px;
  padding: 16px;
  box-sizing: border-box;
  position: relative;
}

/* 历史面板切换按钮 */
.toggle-history-btn {
  position: absolute;
  top: 50%;
  left: 0px;
  transform: translateY(-50%);
  width: 30px;
  height: 60px;
  background-color: #2d3748;
  border-radius: 0 8px 8px 0;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.3);
  z-index: 10;
  transition: left 0.3s ease;
  color: #e2e8f0;
}

/* 历史面板隐藏时按钮的样式 */
.toggle-history-btn.btn-hidden {
  left: 0px;
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.3);
  border-radius: 0 8px 8px 0;
}

.toggle-history-btn:hover {
  background-color: #334155;
}

/* 左侧对话区域 - 卡片式设计 */
.main-content .chat-area {
  flex: 4; /* 占比4份 */
  display: flex;
  flex-direction: column;
  background: #2d3748;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);
  border: 1px solid #334155;
  overflow: hidden;
  transition: flex 0.3s ease;
}

/* 智能体模式下的样式 - 保持与自由对话模式一致 */


/* 消息容器 */
.main-content .messages-container {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
  background: #2d3748;
}

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

.messages-container::-webkit-scrollbar-track {
  background: #334155;
  border-radius: 3px;
}

.messages-container::-webkit-scrollbar-thumb {
  background: #64748b;
  border-radius: 3px;
}

.messages-container::-webkit-scrollbar-thumb:hover {
  background: #8b5cf6;
}

/* 欢迎消息样式 */
.welcome-message {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  text-align: center;
}

.welcome-content {
  max-width: 600px;
  padding: 40px;
}

.welcome-content h3 {
  margin: 0 0 12px 0;
  color: #e2e8f0;
  font-size: 24px;
  font-weight: 600;
}

.welcome-content p {
  margin: 0 0 32px 0;
  color: #94a3b8;
  font-size: 16px;
  line-height: 1.6;
}

.quick-actions {
  text-align: left;
}

.quick-action-title {
  margin-bottom: 16px;
  color: #e2e8f0;
  font-size: 16px;
  font-weight: 600;
}

.quick-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  justify-content: center;
}

/* 消息样式 */
.message-item {
  display: flex;
  margin-bottom: 16px;
}

.message {
  display: flex;
  gap: 12px;
  max-width: 80%;
  align-items: flex-start;
}

.message.user {
  margin-left: auto;
  flex-direction: row-reverse;
}

.message.assistant {
  margin-right: auto;
}

.message-avatar {
  flex-shrink: 0;
}

.message-content {
  flex: 1;
  min-width: 0;
}

.message-text {
  background: #2d3748;
  padding: 15px 20px;
  border-radius: 8px;
  color: #e2e8f0;
  line-height: 1.5;
  word-wrap: break-word;
  border-top-left-radius: 5px;
  border: 1px solid #334155;
}

/* Markdown样式 */
.message-text h1,
.message-text h2,
.message-text h3,
.message-text h4,
.message-text h5,
.message-text h6 {
  margin: 16px 0 8px 0;
  font-weight: 600;
  line-height: 1.4;
}

.message-text h1 { font-size: 1.5em; }
.message-text h2 { font-size: 1.3em; }
.message-text h3 { font-size: 1.1em; }

.message-text p {
  margin: 8px 0;
}

.message-text ul,
.message-text ol {
  margin: 8px 0;
  padding-left: 20px;
}

.message-text li {
  margin: 4px 0;
}

.message-text pre {
  background: #1e293b;
  border: 1px solid #475569;
  border-radius: 6px;
  padding: 12px;
  margin: 12px 0;
  overflow-x: auto;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 14px;
  line-height: 1.4;
  color: #e2e8f0;
}

.message-text code {
  background: #1e293b;
  border: 1px solid #475569;
  border-radius: 3px;
  padding: 2px 4px;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 0.9em;
  color: #e2e8f0;
}

.message-text pre code {
  background: none;
  border: none;
  padding: 0;
}

.message-text blockquote {
  border-left: 4px solid #dfe2e5;
  padding-left: 16px;
  margin: 12px 0;
  color: #6a737d;
  font-style: italic;
}

.message-text table {
  border-collapse: collapse;
  margin: 12px 0;
  width: 100%;
}

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

.message-text th {
  background: #f6f8fa;
  font-weight: 600;
}

.message-text a {
  color: #0366d6;
  text-decoration: none;
}

.message-text a:hover {
  text-decoration: underline;
}

.message-text img {
  max-width: 100%;
  height: auto;
  border-radius: 8px;
  margin: 8px 0;
}

.message.user .message-text {
  background: #8b5cf6;
  color: white;
  border-top-right-radius: 5px;
  border-top-left-radius: 12px;
  border-color: #8b5cf6;
}

.message-time {
  font-size: 12px;
  color: #94a3b8;
  margin-top: 8px;
  text-align: right;
  opacity: 0.7;
}

.message.user .message-time {
  text-align: left;
}

/* 消息状态显示 */
.message-status {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  background: #e6f7ff;
  border: 1px solid #91d5ff;
  border-radius: 8px;
  color: #1890ff;
  font-size: 14px;
  margin-bottom: 8px;
}

.status-icon {
  animation: spin 1s linear infinite;
}

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

/* 打字指示器 */
.typing-indicator {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 15px 20px;
  background: #2d3748;
  border-radius: 5px 8px 8px;
  border: 1px solid #475569;
  cursor: pointer;
  transition: all 0.3s ease;
}

.typing-indicator:hover {
  background: #3f4a5f;
  border-color: #64748b;
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #94a3b8;
  animation: typing 1.4s infinite ease-in-out;
}

.typing-indicator span:nth-child(1) {
  animation-delay: -0.32s;
}

.typing-indicator span:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes typing {
  0%, 80%, 100% {
    transform: scale(0.8);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

/* 智能体状态显示样式 */
.agent-status-simple {
  margin-bottom: 8px;
}

.agent-current-status {
  display: flex;
  align-items: center;
}

.current-step-display {
  display: flex;
  align-items: center;
}

.step-status {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 4px 8px;
  background: rgba(99, 102, 241, 0.1);
  border: 1px solid rgba(99, 102, 241, 0.2);
  border-radius: 12px;
  font-size: 12px;
  color: #6366f1;
}

.step-status .type-icon {
  font-size: 14px;
}

.step-status .status-text {
  font-weight: 500;
}

.agent-status-inline {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
  padding: 8px 0;
}

.agent-status-tag {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  font-weight: 500;
}

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

.current-tool {
  font-size: 12px;
  color: #94a3b8;
  background: rgba(148, 163, 184, 0.1);
  padding: 2px 8px;
  border-radius: 4px;
  border: 1px solid rgba(148, 163, 184, 0.2);
}



/* 输入区域样式 */
.input-area {
  border-top: 1px solid #334155;
  padding: 20px 30px;
  background: #2d3748;
  flex-shrink: 0;
}

.input-container {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.input-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.input-tips {
  font-size: 12px;
  color: #94a3b8;
}

/* 自定义按钮样式 - 与CreativeStudio保持一致 */
:deep(.el-button--primary) {
  background: #409eff;
  border: none;
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);
}

:deep(.el-button--primary:hover) {
  background: #66b1ff;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
}

:deep(.el-button--primary:active) {
  transform: translateY(0);
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);
}

:deep(.el-button--primary.is-loading) {
  background: #409eff;
}

/* 新对话按钮特殊样式 */
.chat-header :deep(.el-button--primary) {
  background: rgba(99, 102, 241, 0.1);
  color: #6366f1;
  border: 1px solid rgba(99, 102, 241, 0.3);
  font-size: 13px;
  padding: 6px 12px;
}

.chat-header :deep(.el-button--primary:hover) {
  background: rgba(99, 102, 241, 0.2);
  border-color: #6366f1;
  transform: none;
  box-shadow: 0 2px 8px rgba(99, 102, 241, 0.2);
}

/* Element Plus 组件深色主题覆盖 - 与CreativeStudio保持一致 */
:deep(.el-tabs__header) {
  background: #2d3748;
  margin: 0;
  padding: 0 0 16px 0;
}

:deep(.el-tabs__nav-wrap::after) {
  background: #334155;
}

:deep(.el-tabs__item) {
  color: #cbd5e1;
  border-bottom: 2px solid transparent;
}

:deep(.el-tabs__item.is-active) {
  color: #409eff;
}

:deep(.el-input__wrapper) {
  background-color: #334155;
  border-color: #475569;
}

:deep(.el-input__inner) {
  color: #e2e8f0;
}

/* Textarea 样式覆盖 */
:deep(.el-textarea__inner) {
  background-color: #334155;
  border-color: #475569;
  color: #e2e8f0;
  resize: vertical;
}

:deep(.el-collapse-item__header) {
  color: #e2e8f0;
  background-color: #2d3748;
  border-bottom: 1px solid #334155;
}

:deep(.el-collapse-item__content) {
  background-color: #2d3748;
  color: #e2e8f0;
}

:deep(.el-select__wrapper) {
  background-color: #334155;
  border-color: #475569;
}

:deep(.el-select__placeholder) {
  color: #94a3b8;
}

:deep(.el-select__input) {
  color: #e2e8f0;
}

:deep(.el-option) {
  color: #e2e8f0;
}

:deep(.el-option:hover) {
  background-color: #334155;
}

:deep(.el-upload__tip) {
  color: #94a3b8;
}

/* 下拉菜单样式 */
:deep(.el-select-dropdown) {
  background-color: #2d3748 !important;
  border: 1px solid #334155 !important;
  border-radius: 8px !important;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.3) !important;
}

:deep(.el-select-dropdown .el-select-dropdown__item) {
  color: #e2e8f0 !important;
  background-color: transparent !important;
  transition: all 0.2s ease;
}

:deep(.el-select-dropdown .el-select-dropdown__item:hover) {
  background-color: #334155 !important;
  color: #e2e8f0 !important;
}

:deep(.el-select-dropdown .el-select-dropdown__item.selected) {
  background-color: #334155 !important;
  color: #409eff !important;
  font-weight: 500;
}

:deep(.el-select-dropdown .el-popper__arrow::before) {
  background-color: #2d3748 !important;
  border: 1px solid #334155 !important;
}

/* 全局 Element Plus 选择器样式覆盖 */
:deep(.el-popper.is-light .el-popper__arrow::before) {
  background-color: #1e293b !important;
  border: 1px solid #475569 !important;
}

/* 快速开始按钮特殊样式优化 */
.quick-buttons :deep(.el-button--primary.is-plain) {
  background: rgba(99, 102, 241, 0.08) !important;
  border: 1px solid rgba(99, 102, 241, 0.25) !important;
  color: #8b5cf6 !important;
  border-radius: 20px !important;
  padding: 8px 16px !important;
  font-size: 13px !important;
  font-weight: 500 !important;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
  box-shadow: 0 1px 3px rgba(99, 102, 241, 0.1) !important;
  backdrop-filter: blur(8px) !important;
}

.quick-buttons :deep(.el-button--primary.is-plain:hover) {
  background: rgba(99, 102, 241, 0.15) !important;
  border-color: rgba(139, 92, 246, 0.4) !important;
  color: #a855f7 !important;
  transform: translateY(-2px) scale(1.02) !important;
  box-shadow: 0 4px 12px rgba(99, 102, 241, 0.25), 0 2px 6px rgba(139, 92, 246, 0.15) !important;
}

.quick-buttons :deep(.el-button--primary.is-plain:active) {
  transform: translateY(-1px) scale(1.01) !important;
  box-shadow: 0 2px 8px rgba(99, 102, 241, 0.2) !important;
}

.quick-buttons :deep(.el-button--primary.is-plain:focus) {
  outline: none !important;
  box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.12) !important;
}

/* 快速按钮容器优化 */
.quick-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  justify-content: center;
  margin-top: 8px;
}

/* 快速按钮动画效果 */
.quick-buttons :deep(.el-button--primary.is-plain) {
  position: relative;
  overflow: hidden;
}

.quick-buttons :deep(.el-button--primary.is-plain::before) {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.1), transparent);
  transition: left 0.6s ease;
}

.quick-buttons :deep(.el-button--primary.is-plain:hover::before) {
  left: 100%;
}

:deep(.el-popper.is-light) {
  background-color: #1e293b !important;
  border: 1px solid #475569 !important;
}

/* 历史对话面板样式 - 与CreativeStudio保持一致 */
.main-content .history-panel {
  width: 280px;
  background-color: #2d3748;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);
  overflow: hidden;
  transition: transform 0.3s ease;
  flex-shrink: 0;
  position: relative;
  top: auto;
  right: auto;
  height: auto;
  border-left: none;
  transform: translateX(0);
  display: flex;
  flex-direction: column;
}

/* 隐藏历史面板 */
.main-content .history-panel.hidden {
  transform: translateX(-100%);
  margin-left: -280px; /* 完全隐藏面板空间 */
  padding: 0;
  overflow: hidden;
}

/* 当历史面板隐藏时，聊天区域占满宽度并消除左侧间距 */
.main-content .history-panel.hidden + .chat-area {
  margin-left: -16px;
}

.main-content .history-content {
  background: #2d3748;
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.main-content .history-header {
  padding: 20px;
  border-bottom: 1px solid #334155;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.main-content .history-header h3 {
  margin: 0;
  font-size: 16px;
  color: #e2e8f0;
  font-weight: 600;
}

.main-content .history-list {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
}

.main-content .history-list::-webkit-scrollbar {
  width: 8px;
}

.main-content .history-list::-webkit-scrollbar-track {
  background: #334155;
}

.main-content .history-list::-webkit-scrollbar-thumb {
  background: #475569;
  border-radius: 4px;
}

.main-content .history-list::-webkit-scrollbar-thumb:hover {
  background: #64748b;
}

.main-content .history-search {
  padding: 16px 20px;
}

.main-content .history-search .el-input__wrapper {
  background: #1e293b;
  border-color: #475569;
  box-shadow: none;
  height: 44px;
  padding: 0 16px;
  border-radius: 8px;
}

.main-content .history-search .el-input__inner {
  color: #e2e8f0;
  background: #1e293b;
  font-size: 14px;
  height: 44px;
  line-height: 44px;
}

.main-content .history-search .el-input__inner::placeholder {
  color: #94a3b8;
}

.main-content .history-search .el-input__prefix {
  color: #94a3b8;
  font-size: 16px;
}

.main-content .history-search .el-input__suffix {
  color: #94a3b8;
  font-size: 16px;
}

.main-content .history-search .el-input__wrapper:hover {
  border-color: #6366f1;
}

.main-content .history-search .el-input__wrapper.is-focus {
  border-color: #6366f1;
  box-shadow: 0 0 0 2px rgba(99, 102, 241, 0.2);
}

.main-content .history-item {
  padding: 16px;
  margin: 0 8px 8px 8px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid transparent;
  border-bottom: 1px solid #334155;
  position: relative;
  overflow: hidden;
}

.main-content .history-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(99, 102, 241, 0.1), transparent);
  transition: left 0.5s ease;
}

.main-content .history-item:hover::before {
  left: 100%;
}

.main-content .history-item:hover {
  background: #334155;
  border-color: #475569;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(99, 102, 241, 0.15);
}

.history-item:last-child {
  border-bottom: none;
}

.history-item.active {
  background: rgba(99, 102, 241, 0.1);
  border-color: #6366f1;
  box-shadow: 0 2px 8px rgba(99, 102, 241, 0.2);
}

.conversation-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.conversation-title {
  font-size: 14px;
  color: #e2e8f0;
  font-weight: 500;
}

.conversation-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #94a3b8;
}

.conversation-time {
  color: #6366f1;
}

.conversation-count {
  color: #67c23a;
}



/* 移除旋转动画 */

/* 右侧智能体思考流程面板样式 - 与CreativeStudio保持一致 */
.agent-panel {
  /* 抽屉样式已由Element Plus的el-drawer组件提供 */
}

.agent-header {
  padding: 16px;
  border-bottom: 1px solid #334155;
  background: #2d3748;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.agent-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #e2e8f0;
}

.agent-content {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
}

.thinking-steps {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.thinking-step {
  background: #2d3748;
  border: 1px solid #334155;
  border-radius: 8px;
  padding: 16px;
  transition: all 0.3s ease;
  position: relative;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);
}

.thinking-step:hover {
  background: #334155;
  border-color: #409eff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
}

.thinking-step.step-thinking {
  border-left: 4px solid #409eff;
}

.thinking-step.step-tool_end {
  border-left: 4px solid #10b981;
}

.thinking-step.step-response {
  border-left: 4px solid #8b5cf6;
}

.step-header {
  margin-bottom: 8px;
}

.step-type-info {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 6px 10px;
  background: #334155;
  border-radius: 6px;
}

.step-type-info .type-icon {
  font-size: 16px;
}

.step-type-info .type-name {
  font-weight: 600;
  color: #e2e8f0;
  font-size: 13px;
}

.step-type-info .tool-info {
  color: #409eff;
  font-weight: 500;
  font-size: 13px;
}

.step-content {
  color: #e2e8f0;
  background: #334155;
  padding: 10px;
  border-radius: 6px;
  border-left: 3px solid #409eff;
  font-size: 13px;
  line-height: 1.5;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.tool-output {
  margin-top: 8px;
}

.output-label {
  font-size: 12px;
  font-weight: 600;
  color: #409eff;
  margin-bottom: 4px;
}

.output-content {
  color: #6ee7b7;
  background: #334155;
  padding: 8px 10px;
  border-radius: 6px;
  border-left: 3px solid #10b981;
  font-size: 12px;
  line-height: 1.4;
  white-space: pre-wrap;
  word-wrap: break-word;
  font-family: 'Courier New', monospace;
  max-height: 200px;
  overflow-y: auto;
}

.step-timestamp {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-top: 8px;
  padding-top: 8px;
  border-top: 1px solid #334155;
  font-size: 11px;
  color: #94a3b8;
}

.agent-empty {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 200px;
  color: #94a3b8;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 12px;
}

.empty-text {
  font-size: 14px;
}


</style>