<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { Link, Search, Document, Close, Plus } from '@element-plus/icons-vue'
import MarkdownIt from 'markdown-it'
import { baseURL } from '@/utils/request'

// 初始化Markdown解析器
const md = MarkdownIt({
  html: true,
  linkify: true,
  typographer: true
})

// 会话状态管理
const showHistory = ref(false)
const sessionHistory = ref([])
const currentSessionId = ref(null)
const isNewSession = ref(true) // 标记是否为全新会话

// 模拟用户ID和IP（实际应用中应从认证系统获取）
const userId = ref(10)
const userIp = ref('192.168.1.100')

// 消息模型
const messages = ref([
  {
    id: 1,
    text: '您好！我是智能AI助手，很高兴为您服务。我可以回答各种问题，例如科技、编程、生活常识等。请问有什么可以帮您的吗？',
    mdText:
      '您好！我是智能AI助手，很高兴为您服务。我可以回答各种问题，例如科技、编程、生活常识等。请问有什么可以帮您的吗？',
    sender: 'ai',
    time: formatTime(new Date()),
    avatar: 'AI',
    isActive: true // 标记当前活跃的AI消息
  }
])

// 用户输入
const userInput = ref('')
const isThinking = ref(false)
const chatContainer = ref(null)
const isLoading = ref(false)
// 当前正在处理的AI消息ID
const currentAiMessageId = ref(null)
// 控制终止按钮显示
const showStopButton = ref(false)
// 用于中止流请求
const abortController = ref(null)

// 加载会话历史
const loadSessionHistory = async () => {
  try {
    // 调用后端API获取会话历史
    const response = await fetch(
      `${baseURL}/session/list?userId=${userId.value}`
    )

    if (!response.ok) {
      throw new Error(`获取会话历史失败: ${response.status}`)
    }

    const data = await response.json()
    sessionHistory.value = data
  } catch (error) {
    console.error('加载会话历史失败:', error)
  }
}

// 格式化时间 (HH:MM)
function formatTime(date) {
  const hours = date.getHours().toString().padStart(2, '0')
  const minutes = date.getMinutes().toString().padStart(2, '0')
  return `${hours}:${minutes}`
}

// 格式化日期时间
function formatDateTime(dateString) {
  const date = new Date(dateString)
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${formatTime(date)}`
}

// 加载单个会话
const loadSession = async (session) => {
  try {
    // 调用后端API获取指定会话的完整消息
    const response = await fetch(`${baseURL}/session/message/${session.id}`)

    if (!response.ok) {
      throw new Error(`获取会话消息失败: ${response.status}`)
    }

    const messagesData = await response.json()

    // 更新当前消息 - 补充头像和时间信息
    messages.value = messagesData.map((msg) => {
      const createdAt = new Date(msg.createdAt)
      return {
        ...msg,
        mdText: msg.content,
        text: msg.sender === 'ai' ? md.render(msg.content) : msg.content,
        avatar: msg.sender === 'user' ? 'U' : 'AI',
        time: formatTime(createdAt)
      }
    })

    currentSessionId.value = session.id
    isNewSession.value = false // 标记为已有会话
    showHistory.value = false
    scrollToBottom()
  } catch (error) {
    console.error('加载会话失败:', error)
  }
}

// 创建新会话按钮处理
const createNewConversation = () => {
  // 清空当前对话
  messages.value = []
  userInput.value = ''
  currentSessionId.value = null
  isNewSession.value = true

  // 添加默认的AI欢迎消息
  const now = new Date()
  messages.value.push({
    id: Date.now(),
    text: '您好！我是智能AI助手，很高兴为您服务。我可以回答各种问题，例如科技、编程、生活常识等。请问有什么可以帮您的吗？',
    mdText:
      '您好！我是智能AI助手，很高兴为您服务。我可以回答各种问题，例如科技、编程、生活常识等。请问有什么可以帮您的吗？',
    sender: 'ai',
    time: formatTime(now),
    avatar: 'AI',
    isActive: true
  })

  scrollToBottom()
}

// 初始化
onMounted(() => {
  loadSessionHistory()
  scrollToBottom()

  // 检查URL参数是否包含会话ID
  const urlParams = new URLSearchParams(window.location.search)
  const sessionIdParam = urlParams.get('session')
  if (sessionIdParam) {
    // 查找会话
    const targetSession = sessionHistory.value.find(
      (s) => s.id === parseInt(sessionIdParam)
    )
    if (targetSession) {
      loadSession(targetSession)
    }
  }
})

// 添加用户消息
const addUserMessage = async (message) => {
  if (!message.trim()) return

  const now = new Date()
  const newMessage = {
    id: Date.now(),
    text: message.trim(),
    mdText: message.trim(),
    sender: 'user',
    time: formatTime(now),
    avatar: 'U'
  }

  // 如果是第一次消息（全新会话）
  if (isNewSession.value) {
    // 移除默认的AI欢迎消息
    if (messages.value.length === 1 && messages.value[0].sender === 'ai') {
      messages.value = []
    }

    // 保存用户消息并创建新会话
    messages.value.push(newMessage)
    await saveMessageToBackend(newMessage, true)
    isNewSession.value = false
  } else {
    // 普通消息
    messages.value.push(newMessage)
    await saveMessageToBackend(newMessage)
  }

  userInput.value = ''
  isThinking.value = true
  scrollToBottom()

  // 调用API获取AI回复
  callBackendAPI(message)
}

// 保存消息到后端
const saveMessageToBackend = async (message, createSession = false) => {
  try {
    // 创建新会话（如果需要）
    if (createSession) {
      const sessionData = {
        userId: userId.value,
        userIp: userIp.value,
        sessionToken: `sess_${Date.now()}`,
        title: message.text.substring(0, 20) + '...'
      }

      // 创建新会话
      const sessionResponse = await fetch(`${baseURL}/session/create`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(sessionData)
      })

      if (!sessionResponse.ok) {
        throw new Error(`创建会话失败: ${sessionResponse.status}`)
      }

      const sessionDataResult = await sessionResponse.json()
      currentSessionId.value = sessionDataResult.id

      // 设置消息的会话ID
      message.sessionId = currentSessionId.value
    }

    // 准备消息数据
    const messageData = {
      sessionId: currentSessionId.value,
      content: message.mdText,
      sender: message.sender
    }

    // 保存消息
    const response = await fetch(`${baseURL}/session/message/create`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(messageData)
    })

    if (!response.ok) {
      throw new Error(`保存消息失败: ${response.status}`)
    }

    // 更新消息ID
    const data = await response.json()
    message.id = data.id

    // 更新会话历史
    if (createSession) {
      loadSessionHistory()
    }
  } catch (error) {
    console.error('保存消息失败:', error)
  }
}

// 调用后端API - 使用fetch API
// 调用后端API - 使用fetch API
const callBackendAPI = async (userMessage) => {
  isLoading.value = true
  showStopButton.value = true
  abortController.value = new AbortController()

  try {
    // 创建初始AI消息
    createAiMessage()

    // 替换为你的实际API密钥（此处保留示例密钥，实际需替换为有效令牌）
    const apiKey =
      'eyJ0eXBlIjoiSldUIiwiYWxnIjoiSFM1MTIifQ.eyJqdGkiOiI4NjMwNjcyNyIsInJvbCI6IlJPTEVfUkVHSVNURVIiLCJpc3MiOiJPcGVuWExhYiIsImlhdCI6MTc1MTUzOTEzNCwiY2xpZW50SWQiOiJlYm1ydm9kNnlvMG5semFlazF5cCIsInBob25lIjoiMTc4NzAzNDI2ODUiLCJvcGVuSWQiOm51bGwsInV1aWQiOiIzNDg5ZTJkOC04ZGI4LTQyNDUtOTFiZC03YmRkN2Y3MTI0ZDEiLCJlbWFpbCI6IiIsImV4cCI6MTc2NzA5MTEzNH0.-Bfg41q0v4RDjN6mgfLmga1isL02KF5DdoA1LoiNmUQg8I19FjEMz2w9dOJsql3-MavE6UB5QlECQiDvk4t6XQ' // 请替换为实际的Bearer Token

    // 构造完整的messages数组（包含历史对话）
    const formattedMessages = [
      // 系统提示（可选，根据需求保留或移除）
      // { role: 'system', content: 'You are a helpful assistant.' },

      // 转换历史消息为API所需格式
      ...messages.value.map((msg) => ({
        role: msg.sender === 'user' ? 'user' : 'assistant',
        content: msg.mdText
      })),

      // 当前用户消息
      { role: 'user', content: userMessage }
    ]

    // 使用fetch API调用API（格式与curl一致）
    const response = await fetch(
      'https://chat.intern-ai.org.cn/api/v1/chat/completions',
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${apiKey}`
        },
        body: JSON.stringify({
          model: 'internlm3-latest',
          messages: formattedMessages,
          temperature: 0.8,
          top_p: 0.9,
          stream: true
        }),
        signal: abortController.value.signal
      }
    )

    if (!response.ok) {
      throw new Error(`请求失败: ${response.status}`)
    }

    // 处理流式响应（与原逻辑一致）
    const reader = response.body.getReader()
    const decoder = new TextDecoder('utf-8')
    let partialData = ''
    let aiMessageContent = ''
    var trimmedChunk = 'start'
    while (trimmedChunk !== '[DONE]') {
      const { value, done } = await reader.read()
      if (done) break

      // 解码并处理数据块
      const chunk = decoder.decode(value, { stream: true })
      partialData += chunk

      // 处理可能包含多个数据块的情况
      const dataChunks = partialData.split('data: ')
      partialData = dataChunks.pop() || '' // 保留未完成的部分

      for (const dataChunk of dataChunks) {
        if (dataChunk.trim() === '') continue
        trimmedChunk = dataChunk.trim()
        if (trimmedChunk === '[DONE]') {
          // 流结束
          break
        }

        try {
          const dataObj = JSON.parse(trimmedChunk)
          const content = dataObj.choices?.[0]?.delta?.content || ''
          if (content) {
            updateAiMessage(content)
            aiMessageContent += content
          }
        } catch (error) {
          console.warn('JSON解析错误:', error)
        }
      }
    }

    // 保存完整的AI消息到后端
    if (currentAiMessageId.value) {
      saveMessageToBackend({
        id: currentAiMessageId.value,
        mdText: aiMessageContent,
        sender: 'ai',
        time: formatTime(new Date())
      })
    }
  } catch (error) {
    if (error.name !== 'AbortError') {
      console.error('API调用失败:', error)
      // 更新最后一条AI消息显示错误
      const aiMessageIndex = messages.value.findIndex(
        (msg) => msg.id === currentAiMessageId.value
      )
      if (aiMessageIndex !== -1) {
        messages.value[aiMessageIndex].mdText =
          `抱歉，处理请求时出错: ${error.message}`
        messages.value[aiMessageIndex].text = md.render(
          messages.value[aiMessageIndex].mdText
        )
        scrollToBottom()
      }
    }
  } finally {
    isLoading.value = false
    isThinking.value = false
    showStopButton.value = false
    abortController.value = null
  }
}
// 创建初始AI消息
const createAiMessage = () => {
  const now = new Date()
  const newMessage = {
    id: Date.now(),
    text: '',
    mdText: '',
    sender: 'ai',
    time: formatTime(now),
    avatar: 'AI',
    isActive: true // 标记当前活跃的AI消息
  }

  // 重置所有消息为非活跃状态
  messages.value.forEach((msg) => {
    msg.isActive = false
  })

  messages.value.push(newMessage)
  currentAiMessageId.value = newMessage.id
  scrollToBottom()

  return newMessage.id
}

// 更新AI消息内容
const updateAiMessage = (contentChunk) => {
  const aiMessageIndex = messages.value.findIndex(
    (msg) => msg.id === currentAiMessageId.value
  )

  if (aiMessageIndex !== -1) {
    // 更新原始Markdown文本
    messages.value[aiMessageIndex].mdText += contentChunk
    // 重新解析整个Markdown
    messages.value[aiMessageIndex].text = md.render(
      messages.value[aiMessageIndex].mdText
    )

    // 滚动到底部
    scrollToBottom()
  }
}

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

// 发送消息
const sendMessage = () => {
  if (!userInput.value.trim() || isThinking.value) return
  addUserMessage(userInput.value)
}

// 停止当前回答
const stopResponse = () => {
  if (abortController.value) {
    abortController.value.abort()
    showStopButton.value = false
    isThinking.value = false
    isLoading.value = false

    // 在AI消息中添加终止提示
    const aiMessageIndex = messages.value.findIndex(
      (msg) => msg.id === currentAiMessageId.value
    )
    if (aiMessageIndex !== -1 && messages.value[aiMessageIndex].text === '') {
      messages.value[aiMessageIndex].mdText = '已终止回答'
      messages.value[aiMessageIndex].text = md.render('已终止回答')
      scrollToBottom()
    }
  }
}

// 快捷键发送（Ctrl+Enter）
const handleKeydown = (e) => {
  if (e.ctrlKey && e.key === 'Enter' && userInput.value.trim()) {
    sendMessage()
  }
}
</script>

<template>
  <div class="ai-container">
    <!-- 头部标题区域 -->
    <div class="ai-header">
      <el-page-header icon="" title=" ">
        <template #title>
          <div class="ai-title">
            <el-icon size="30" color="#3498db">
              <component :is="Search" />
            </el-icon>
            <span>AI智能问答助手</span>
          </div>
        </template>
        <template #content>
          <div class="ai-subtitle">支持Markdown格式的智能问答系统</div>
        </template>
        <template #extra>
          <el-button @click="showHistory = true" style="margin-right: 10px">
            <el-icon><Document /></el-icon>
            <span>会话历史</span>
          </el-button>
          <el-button type="primary" @click="createNewConversation">
            <el-icon><Plus /></el-icon>
            <span>创建新会话</span>
          </el-button>
        </template>
      </el-page-header>
    </div>

    <!-- 历史记录面板 -->
    <el-drawer v-model="showHistory" title="会话历史记录" :size="400">
      <div class="history-panel">
        <el-scrollbar height="100%">
          <div
            v-for="session in sessionHistory"
            :key="session.id"
            class="session-item"
            @click="loadSession(session)"
          >
            <div class="session-title">{{ session.title }}</div>
            <div class="session-date">
              {{ formatDateTime(session.startTime) }}
            </div>
          </div>

          <div v-if="sessionHistory.length === 0" class="empty-history">
            <el-empty description="暂无历史会话" />
          </div>
        </el-scrollbar>
      </div>
    </el-drawer>

    <!-- 聊天区域 -->
    <div class="chat-container" ref="chatContainer">
      <div
        v-for="(message, index) in messages"
        :key="index"
        :class="['message', message.sender]"
      >
        <div class="message-header">
          <el-avatar :class="message.sender" :size="36">
            <span>{{ message.avatar }}</span>
          </el-avatar>
          <div>
            <div class="message-sender">
              {{ message.sender === 'user' ? '用户' : 'AI助手' }}
            </div>
            <div class="message-time">{{ message.time }}</div>
          </div>
        </div>

        <div
          class="message-content"
          :class="[message.sender, { active: message.isActive }]"
        >
          <!-- 用户消息直接显示文本，AI消息显示解析后的HTML -->
          <span v-if="message.sender === 'user'">{{ message.text }}</span>
          <div v-else class="markdown-content" v-html="message.text"></div>
        </div>
      </div>

      <!-- 终止按钮 -->
      <div v-if="showStopButton" class="stop-response">
        <el-button type="danger" size="small" @click="stopResponse" round>
          <el-icon><Close /></el-icon>
          <span>终止回答</span>
        </el-button>
      </div>

      <!-- 加载状态 -->
      <div v-if="isThinking && !isLoading" class="thinking">
        <div class="loader">
          <div></div>
          <div></div>
          <div></div>
        </div>
        <span>思考中...</span>
      </div>
      <div v-if="isLoading" class="thinking">
        <div class="loader">
          <div></div>
          <div></div>
          <div></div>
        </div>
        <span>正在获取回答...</span>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="input-container">
      <el-input
        v-model="userInput"
        type="textarea"
        :rows="4"
        placeholder="输入您的问题（支持普通文本），按 Ctrl+Enter 发送"
        :disabled="isThinking"
        @keydown="handleKeydown"
        resize="none"
      />
      <el-button
        class="send-btn"
        type="primary"
        @click="sendMessage"
        :disabled="isThinking || !userInput.trim()"
      >
        <el-icon>
          <el-link type="primary">
            <component :is="Link" />
          </el-link>
        </el-icon>
        <span>发送</span>
      </el-button>
    </div>
  </div>
</template>
<style scoped>
/* 新增历史记录面板样式 */
.history-panel {
  height: 100%;
  padding: 15px;
}

.session-item {
  padding: 15px;
  margin-bottom: 10px;
  border-radius: 8px;
  background-color: #f8f9fa;
  cursor: pointer;
  transition: background-color 0.3s;
}

.session-item:hover {
  background-color: #e9ecef;
}

.session-title {
  font-weight: bold;
  margin-bottom: 5px;
  color: #212529;
}

.session-date {
  font-size: 12px;
  color: #6c757d;
}

.empty-history {
  text-align: center;
  padding: 20px;
}

/* 原有样式保持不变 */
.ai-container {
  margin: 0 auto;
  padding: 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  height: 80vh;
  display: flex;
  flex-direction: column;
}

.ai-header {
  margin-bottom: 20px;
  border-bottom: 1px solid #eee;
  padding-bottom: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.ai-title {
  display: flex;
  align-items: center;
  gap: 10px;
  font-weight: bold;
  font-size: 22px;
  color: #3498db;
}

.ai-subtitle {
  font-size: 14px;
  color: #7f8c8d;
}

.chat-container {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
  border: 1px solid #eee;
  border-radius: 10px;
  margin-bottom: 15px;
  background: #fafafa;
  position: relative;
}

.message {
  margin-bottom: 20px;
  border-radius: 10px;
  padding: 15px;
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.message-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.message-header > div {
  margin-left: 12px;
}

.message-sender {
  font-weight: bold;
  font-size: 16px;
  color: #2c3e50;
}

.message-time {
  font-size: 12px;
  color: #95a5a6;
}

.message-content {
  padding: 10px;
  border-radius: 8px;
  font-size: 15px;
  line-height: 1.6;
}

.message-content.user {
  background-color: #e8f4f8;
  border-left: 4px solid #3498db;
}

.message-content.ai {
  background-color: #f5f7fa;
  border-left: 4px solid #9b59b6;
}

.message-content.ai.active {
  background-color: #edf6ff;
  border-left: 4px solid #3498db;
}

:deep(.markdown-content) h1,
:deep(.markdown-content) h2,
:deep(.markdown-content) h3 {
  margin: 15px 0 10px;
  color: #2c3e50;
  font-weight: bold;
}

:deep(.markdown-content) p {
  margin-bottom: 10px;
}

:deep(.markdown-content) ul,
:deep(.markdown-content) ol {
  margin-left: 20px;
  margin-bottom: 15px;
}

:deep(.markdown-content) li {
  margin-bottom: 5px;
}

:deep(.markdown-content) code {
  background-color: #f8f8f8;
  padding: 2px 6px;
  border-radius: 4px;
  font-family: Consolas, monospace;
}

:deep(.markdown-content) pre {
  background-color: #2c3e50;
  color: #ecf0f1;
  padding: 10px;
  border-radius: 6px;
  overflow-x: auto;
  margin: 15px 0;
}

:deep(.markdown-content) pre code {
  background: none;
  padding: 0;
  border-radius: 0;
}

:deep(.markdown-content) a {
  color: #3498db;
  text-decoration: none;
}

:deep(.markdown-content) a:hover {
  text-decoration: underline;
}

.input-container {
  display: flex;
  gap: 10px;
}

.send-btn {
  height: 90px;
  width: 100px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 0;
}

.thinking {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px;
  color: #95a5a6;
}

.stop-response {
  display: flex;
  justify-content: center;
  margin: 10px 0;
}

.avatar-user {
  background-color: #3498db;
  color: white;
}

.avatar-ai {
  background-color: #9b59b6;
  color: white;
}

.loader {
  display: inline-flex;
  gap: 5px;
  margin-right: 10px;
}

.loader div {
  width: 10px;
  height: 10px;
  background: #3498db;
  border-radius: 50%;
  display: inline-block;
  animation: bounce 1.4s infinite ease-in-out both;
}

.loader div:nth-child(1) {
  animation-delay: -0.32s;
}

.loader div:nth-child(2) {
  animation-delay: -0.16s;
}

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