<template>
  <div class="chat-container">
    <!-- 欢迎界面 -->
    <div v-if="!isChating" class="welcome-section">
      <h1 class="welcome-title">Hi, 欢迎回来~</h1>
      <p class="welcome-subtitle">我是您的AI助理，能帮你编写整理资料，快来试试吧</p>
    </div>

    <!-- 聊天记录区域 -->
    <div class="chat-messages"  v-show="isChating" ref="messagesRef" :class="{ 'chat-active': isChating }">
      <div v-for="(message, index) in messages" :key="index" 
           :class="['message', message.role === 'user' ? 'user' : 'assistant']">
        <div class="avatar" v-if="message.content">
          <img :src="message.role === 'user' ? userAvatar : assistantAvatar" :alt="message.role">
        </div>
        <div class="content" v-if="message.content">
          <div class="text markdown-body" v-html="message.content"></div>
          <div class="message-actions" v-if="message.role === 'assistant'">
            <div class="left-actions">
              <button class="action-btn" @click="copyContent(message.content)">
                <img src="@/assets/icon-copy.png" alt="复制">
              </button>
              <!-- <button class="action-btn" @click="toggleFavorite(message.id)">
                <img src="@/assets/icon-star.png" alt="收藏">
              </button> -->
              <button class="action-btn reanswer" @click="reAnswer(message.id)">
                <img src="@/assets/icon-reanswer.png" alt="重新回答">
                <span>重新回答</span>
              </button>
            </div>
            <!-- <div class="right-actions">
              <button class="action-btn" @click="handleLike(message.id, true)">
                <img src="@/assets/icon-like.png" alt="点赞">
              </button>
              <button class="action-btn" @click="handleLike(message.id, false)">
                <img src="@/assets/icon-dislike.png" alt="反对">
              </button>
            </div> -->
          </div>
          <!-- <div class="time">{{ formatTime(message.time) }}</div> -->
        </div>
      </div>
      <div v-if="loading" class="message assistant">
        <div class="avatar">
          <img :src="assistantAvatar" alt="assistant">
        </div>
        <div class="content">
          <div class="typing">正在输入...</div>
        </div>
      </div>
    </div>
    
    <!-- 输入区域 -->
    <div class="chat-input" :class="{ 'chat-active': isChating }">
      <div class="input-container">
        <textarea 
          v-model="inputMessage" 
          @keydown.enter.prevent="handleSend"
          placeholder="输入消息，按Enter发送"
          rows="3"
        ></textarea>
        <div class="input-actions">
          <div class="select-wrap">
            <el-select v-model="selectedModel" class="model-select" :disabled="isChating">
              <el-option v-for="model in models" :key="model.id" :value="model.id" :label="model.name">
                {{ model.name }}
              </el-option>
            </el-select>
          </div>
          <button @click="handleSend" :disabled="loading || !inputMessage.trim()" class="send-button">
            <img src="@/assets/icon-send.png" alt="发送">
            立即生成
          </button>
        </div>
      </div>
    </div>
    <!-- 知识库列表 -->
    <div class="knowledge-base" v-if="!isChating">
        <div class="knowledge-tags">
          <button 
            v-for="(item, index) in knowledgeList" 
            :key="index"
            :class="['knowledge-tag', { active: selectedKnowledge.includes(item.datasetId) }]"
            @click="toggleKnowledge(item.datasetId)"
          >
            {{ item.name }}
          </button>
        </div>
      </div>

      <!-- 页面底部文字提示 -->
      <div class="page-bottom-tips" :class="{ 'is-collapse': userStore.isCollapse }">
        <p v-if="!isChating">该AI工具仅限内部使用，严禁外泄知识库资料</p>
        <p>所有内容均由AI生成，仅供参考</p>
      </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, watch } from 'vue'
import { useRoute } from 'vue-router'
import userAvatar from '@/assets/user-avatar.png'
import assistantAvatar from '@/assets/assistant-avatar.png'
import { post,get } from '@/utils/request'
import { ElMessage } from 'element-plus'
import MarkdownIt from 'markdown-it'
import hljs from 'highlight.js'
import 'highlight.js/styles/github.css'
import { useUserStore } from '../stores/user'

const userStore = useUserStore()
const route = useRoute()
const messagesRef = ref(null)
const inputMessage = ref('')
const loading = ref(false)
const isChating = ref(false)
const selectedKnowledge = ref([])
const selectedModel = ref('DeepSeek')
const sessionId = ref('')
const chatId = ref('')

// 对话模型列表
const models = ref([
  { id: 'DeepSeek', name: 'DeepSeek' },
  { id: 'gpt-4', name: 'GPT-4' },
  { id: 'qwen', name: 'Qwen' }
])

// 知识库列表
const knowledgeList = ref([])

// 获取知识库列表
const getKnowledgeList = async () => {
  try {
    const userId = userStore.userInfo.id
    const response = await get('/admin/user/chat/knowInfoList?userId='+userId)
    // console.log('response', response);
    if (response.data) {
      knowledgeList.value = response.data
      // 默认选中第一个知识库
      selectedKnowledge.value = [knowledgeList.value[0].datasetId]
    } else {
      ElMessage.error('获取知识库列表失败')
    }
  } catch (error) {
    console.error('获取知识库列表失败:', error)
    ElMessage.error('获取知识库列表失败')
  }
}

const messages = ref([])

// 创建 markdown-it 实例，配置代码高亮
const md = new MarkdownIt({
  html: false,
  breaks: true,
  linkify: true,
  highlight: function (str, lang) {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return `<pre class="hljs"><code>${hljs.highlight(str, { language: lang, ignoreIllegals: true }).value}</code></pre>`
      } catch (__) {}
    }
    // 使用默认的转义
    return `<pre class="hljs"><code>${md.utils.escapeHtml(str)}</code></pre>`
  }
})

const formatTime = (time) => {
  return new Date(time).toLocaleTimeString()
}

const toggleKnowledge = (id) => {
  const index = selectedKnowledge.value.indexOf(id)
  if (index === -1) {
    selectedKnowledge.value.push(id)
  } else {
    selectedKnowledge.value.splice(index, 1)
  }
}

const scrollToBottom = async () => {
  await nextTick()
  if (messagesRef.value) {
    messagesRef.value.scrollTop = messagesRef.value.scrollHeight
  }
}

const handleSend = async () => {
  if (selectedKnowledge.value.length === 0) {
      ElMessage.warning('请先选择知识库')
      return
    }
  const message = inputMessage.value.trim()
  if (!message || loading.value) return

  // 保存当前消息，供后续使用
  const currentMessage = message

  if (!isChating.value) {
    isChating.value = true
  }

  // 如果没有session_id和chat_id，先获取它们
  if (!sessionId.value || !chatId.value) {
    try {
      const response = await post('/admin/user/chat/create', {
        userId: userStore.userInfo.id,
        datasetIds: selectedKnowledge.value.join(',')
      })

      if (response.data) {
        sessionId.value = response.data.sessionId
        chatId.value = response.data.chatId
      } else {
        ElMessage.error('初始化对话失败')
        return
      }
    } catch (error) {
      console.error('初始化对话失败:', error)
      ElMessage.error('初始化对话失败，请重试')
      return
    }
  }

  // 添加用户消息
  messages.value.push({
    role: 'user',
    content: currentMessage,
    time: new Date()
  })
  
  // 清空输入框
  inputMessage.value = ''
  
  await scrollToBottom()

  // 开始流式响应
  loading.value = true
  simulateStreamResponse(currentMessage)
}

const simulateStreamResponse = async (question) => {
  loading.value = true;
  
  const messageIndex = messages.value.length;
  messages.value.push({
    id: Date.now(),
    role: 'assistant',
    content: '',
    time: new Date()
  });

  const token = localStorage.getItem('token')
  
  let accumulatedText = ''; // 用于累积接收到的文本

  // /admin/user/chat/converse
  // /admin/ragflow/chat/converse
  
  //请求ai聊天接口
  const eventSource = new EventSource(`${import.meta.env.VITE_API_BASE_URL}/admin/user/chat/converse?chat_id=${chatId.value}&question=${encodeURIComponent(question)}&stream=true&session_id=${sessionId.value}&user_id=${userStore.userInfo.id}&token=${token}`);

  eventSource.onmessage = async (event) => {  
    try {
      const data = JSON.parse(event.data);
      
      if (data.data === true) {
       
        // 处理think标签
        let processedText = accumulatedText;
        const thinkEndRegex = /([^<])<\/think>/g;
        const matches = [...processedText.matchAll(thinkEndRegex)];
        
        for (const match of matches) {
          const beforeThinkEnd = processedText.substring(0, match.index + match[1].length);
          const afterThinkEnd = processedText.substring(match.index + match[1].length);
          console.log('beforeThinkEnd',beforeThinkEnd);
          console.log('afterThinkEnd',afterThinkEnd);
          // 在对应的</think>标签前添加<think>标签
          processedText = '<think>' +  beforeThinkEnd + afterThinkEnd;
        }

        console.log('processedText',processedText);
        
        // 如果内容包含think标签，分别处理think标签内外的内容
        if (processedText.includes('<think>') && processedText.includes('</think>')) {
          let finalContent = '';
          let currentPos = 0;
          
          while (true) {
            const thinkStart = processedText.indexOf('<think>', currentPos);
            const thinkEnd = processedText.indexOf('</think>', currentPos);
            
            if (thinkStart === -1 || thinkEnd === -1) {
              // 处理剩余的文本
              if (currentPos < processedText.length) {
                finalContent += md.render(processedText.substring(currentPos));
              }
              break;
            }
            
            // 处理think标签之前的内容（需要markdown渲染）
            if (thinkStart > currentPos) {
              finalContent += md.render(processedText.substring(currentPos, thinkStart));
            }
            
            // 添加think标签内的内容（原样保留）
            const thinkContent = processedText.substring(thinkStart, thinkEnd + 8);
            finalContent += thinkContent;
            
            currentPos = thinkEnd + 8;
          }
          
          messages.value[messageIndex].content = finalContent;
        } else {
          // 如果没有think标签，进行普通的markdown渲染
          messages.value[messageIndex].content = md.render(processedText);
        }
        
        eventSource.close();
        // 发送事件通知更新历史记录
        window.dispatchEvent(new Event('updateHistory'));
        loading.value = false;
        await scrollToBottom();
        return;
      }

      if (data.data && data.data.answer) {
        console.log('data.data.answer',data.data.answer);
        // 累积接收到的文本
        accumulatedText += data.data.answer;
        // 临时显示文本
        messages.value[messageIndex].content = accumulatedText;
        await nextTick();
        await scrollToBottom();
      }
    } catch (error) {
      console.error('Parse error:', error);
    }
  };

  eventSource.onerror = (error) => {
    console.error('EventSource error:', error);
    eventSource.close();
    loading.value = false;
    if (!messages.value[messageIndex].content) {
      ElMessage.error('对话请求失败，请重试');
    }
  };

  eventSource.onopen = () => {
    console.log('连接已建立');
  };
}

// 修改复制功能，去除HTML标签
const copyContent = (content) => {
  // 创建临时元素来去除HTML标签
  const temp = document.createElement('div')
  temp.innerHTML = content
  const plainText = temp.textContent || temp.innerText
  navigator.clipboard.writeText(plainText)
  ElMessage.success('复制成功')
}

const toggleFavorite = (messageId) => {
  // TODO: 实现收藏功能
}

const reAnswer = (messageId) => {
  // 找到当前消息的索引
  const currentIndex = messages.value.findIndex(msg => msg.id === messageId);
  if (currentIndex === -1) return;

  // 找到这条消息之前最近的用户消息
  let userMessageIndex = currentIndex - 1;
  while (userMessageIndex >= 0) {
    if (messages.value[userMessageIndex].role === 'user') {
      // 获取用户的问题
      const question = messages.value[userMessageIndex].content;
      // 设置输入框的内容
      inputMessage.value = question;
      // 触发发送
      handleSend();
      break;
    }
    userMessageIndex--;
  }
  scrollToBottom();
}

const handleLike = (messageId, isLike) => {
  // TODO: 实现点赞/反对功能
}

// 获取历史记录
const getHistoryChat = async (historyId) => {
  try {
    const response = await get(`/admin/userHistoryLog/selectById?id=${historyId}`)
    if (response.data) {
      const { chatId: historyChatId, sessionId: historySessionId, askList } = response.data
      chatId.value = historyChatId
      sessionId.value = historySessionId

      // 清空现有消息
      messages.value = []

      // 按照 askSeq 排序对话记录
      const sortedMessages = askList.sort((a, b) => Number(a.askSeq) - Number(b.askSeq))

      // 添加所有对话记录
      for (const message of sortedMessages) {
        // 添加用户问题
        messages.value.push({
          role: 'user',
          content: message.askContent,
          time: new Date(message.createTime)
        })

        // 处理AI回答
        try {
          let answerContent = message.answerContent
          let formattedAnswer = ''

          // 按照 data: 分割字符串
          const responses = answerContent.split('data:')
          console.log('responses',responses);
          
          // 遍历所有分割后的响应
          for (const response of responses) {
            console.log('response==========',response);
            if (response.trim() && !response.includes('"data": true')) {
              console.log('response.trim()',response.trim());
              try {
                const jsonData = JSON.parse(response.trim())
                console.log('jsonData',jsonData);
                if (jsonData.data && jsonData.data.answer) {
                  formattedAnswer += jsonData.data.answer
                }
              } catch (e) {
                console.warn('解析单条回答内容失败:', e)
              }
            }
          }

          // 如果没有成功解析出任何内容，使用原始内容
          if (!formattedAnswer.trim()) {
            formattedAnswer = answerContent
          }

          // 添加AI回答
          messages.value.push({
            id: message.id,
            role: 'assistant',
            content: md.render(formattedAnswer),
            time: new Date(message.createTime)
          })
        } catch (error) {
          console.error('处理回答内容失败:', error)
          // 如果处理失败，直接显示原始内容
          messages.value.push({
            id: message.id,
            role: 'assistant',
            content: answerContent,
            time: new Date(message.createTime)
          })
        }
      }

      isChating.value = true
      await nextTick()
      scrollToBottom()
    }
  } catch (error) {
    console.error('获取历史记录失败:', error)
    ElMessage.error('获取历史记录失败')
  }
}

// 初始化对话
const initChat = async () => {
  messages.value = []
  await getKnowledgeList() // 获取最新的知识库列表
  chatId.value = ''
  sessionId.value = ''
  isChating.value = false
}

// 监听路由参数变化
watch(() => route.query.newChat, async (newVal) => {
  if(newVal) {
    await initChat()
  }
}, { immediate: true })

onMounted(async () => {
  const historyId = route.query.historyId
  if (historyId) {
    await getHistoryChat(historyId)
  } else {
    await getKnowledgeList() // 如果不是历史记录，需要获取知识库列表
  }
  scrollToBottom()
})
</script>

<style lang="scss" scoped>
.chat-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: url('@/assets/ai-chat-bg.png') no-repeat center center;
  background-size: cover;
  &:has(.chat-active){
    background: #fff;
  }

  .welcome-section {
    margin-top: 100px;
    text-align: center;
    padding: 40px 20px;

    .welcome-title {
      font-size: 28px;
      margin-bottom: 12px;
    }

    .welcome-subtitle {
      color: #635a5a;
    }
  }

  .knowledge-base {
    width: 800px;
    margin: 24px auto 0;

    .knowledge-tags {
      display: flex;
      flex-wrap: wrap;
      gap: 12px;
      justify-content: left;

      .knowledge-tag {
        padding: 8px 16px;
        border: 1px solid #DADDE8;
        border-radius: 15px;
        background: transparent;
        cursor: pointer;
        transition: all 0.3s;
        color: #414967;

        &:hover {
          background: #f5f7fa;
        }

        &.active {
          color: #FF7575;
          border-color: #FF7575;
        }
      }
    }
  }

  .chat-messages {
    flex: 1;
    overflow-y: auto;
    padding: 20px 20%;
    transition: all 0.3s;

    &.chat-active {
      padding-bottom: 100px;
    }

    .message {
      display: flex;
      margin-bottom: 100px;
      .avatar{
          img{
            width: 40px;
            height: 40px;
          }
        }
      .text {
        padding: 10px 20px;
        font-size: 16px;
      }
      &.user {
        flex-direction: row-reverse;
        .content {
          margin-right: 12px;
          margin-left: 0;
          
          .text {
            background: #FFF5F5;
            color: #1B1C21;
            border-radius: 10px 2px 10px 10px;
          }
          
          .time {
            text-align: right;
          }
        }
      }
      
      &.assistant{
        .avatar{
          margin-right: 10px;
        }
      }
      &.assistant .content .text {
        // background: rgba(255, 255, 255, 0.9);
        border-radius: 2px 10px 10px 10px;
      }

      .message-actions {
        display: flex;
        justify-content: space-between;
        margin-top: 8px;

        .left-actions, .right-actions {
          display: flex;
          gap: 8px;
        }

        .action-btn {
          background: none;
          border: none;
          padding: 4px;
          cursor: pointer;
          display: flex;
          align-items: center;
          gap: 4px;

          img {
            width: 16px;
            height: 16px;
          }

          &.reanswer span {
            font-size: 12px;
            color: #666;
          }
        }
      }
    }
  }

  .chat-input {
    // width: fit-content;
    margin: 0 auto;
    padding: 20px;
    background: rgba(255, 255, 255, 0.9);
    box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.1);
    backdrop-filter: blur(10px);
    border-radius: 20px;
    min-width: 800px;
    &.chat-active{
      position: fixed;
      bottom: 0;
      left: $sidebar-width;
      right: 0;
      padding: 20px;
      box-shadow: none;
    }

    .input-container {
      max-width: 800px;
      margin: 0 auto;

      textarea {
        width: 100%;
        padding: 12px;
        border: 1px solid #dcdfe6;
        border-radius: 15px;
        background: rgba(255, 255, 255, 0.9);
        resize: none;
        font-size: 14px;
        line-height: 1.5;
        
        &:focus {
          outline: none;
          border-color: $primary-color;
        }
      }

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

        .select-wrap{
          width: 300px;
          .el-select{
            color: #414967;
          }
          :deep(.el-select__wrapper){
            height: 46px;
            width: 176px;
            border-radius: 80px;
            background: #FFE9E9;
            border: none;
            box-shadow: none;
            
            .el-select__placeholder{
              color: #414967;
              font-size: 20px;
            }
            .el-select__caret{
              font-size: 20px;
            }
          }
        }

        .send-button {
          display: flex;
          align-items: center;
          gap: 14px;
          padding: 5px 20px 5px 8px;
          background: linear-gradient(135deg, #F89494 0%, #FE3636 100%);
          border: none;
          border-radius: 60px;
          color: white;
          font-size: 18px;
          cursor: pointer;
          font-weight: 500;
          transition: background 0.3s;

          img {
            width: 30px;
            height: 30px;
          }

          &:disabled {
            background: #f7b0b0;
            cursor: not-allowed;
          }
        }
      }
    }
  }

  // 添加 markdown 样式
  .markdown-body {
    line-height: 1.6;
    font-size: 14px;
    
    p {
      margin: 8px 0;
    }

    h1, h2, h3, h4, h5, h6 {
      margin: 16px 0 8px;
      font-weight: 600;
    }

    code {
      background-color: rgba(175, 184, 193, 0.2);
      padding: 0.2em 0.4em;
      border-radius: 6px;
      font-family: monospace;
    }

    pre {
      background-color: #f6f8fa;
      border-radius: 6px;
      padding: 16px;
      overflow: auto;
      margin: 16px 0;

      code {
        background-color: transparent;
        padding: 0;
        font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, Courier, monospace;
        font-size: 14px;
        line-height: 1.45;
        tab-size: 4;
      }

      &.hljs {
        background: #f6f8fa;
        border: 1px solid #e1e4e8;
      }
    }

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

    table {
      border-collapse: collapse;
      margin: 8px 0;
      
      th, td {
        border: 1px solid #d0d7de;
        padding: 6px 13px;
      }

      th {
        background-color: #f6f8fa;
      }
    }

    blockquote {
      border-left: 4px solid #d0d7de;
      padding-left: 16px;
      margin: 8px 0;
      color: #656d76;
    }

    img {
      max-width: 100%;
      height: auto;
    }

    a {
      color: #0969da;
      text-decoration: none;
      
      &:hover {
        text-decoration: underline;
      }
    }

    code {
      font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, Courier, monospace;
      font-size: 0.9em;
      padding: 0.2em 0.4em;
      margin: 0;
      background-color: rgba(175, 184, 193, 0.2);
      border-radius: 6px;
    }
  }
}
</style> 