<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="template-section" v-if="!isChating">
      <div class="template-type">
        <div class="type-title">全文</div>
        <div class="type-list">
          <div class="type-item" v-for="item in templateList1" :key="item.id">
           <div class="type-item-title">
            <img :src="item.icon" alt="">
            <span class="ellipsis-1">{{ item.name }}</span>
            <span class="use-btn" @click="useTemplate(item.id)">使用</span>
           </div>
           <div class="type-item-content ellipsis-2">{{ item.content }}</div>
          </div>
        </div>
      </div>
      <div class="template-type">
        <div class="type-title">按章节</div>
        <div class="type-list">
          <div class="type-item" v-for="item in templateList2" :key="item.id">
            <div class="type-item-title">
              <img :src="item.icon" alt="">
              <span class="ellipsis-1">{{ item.name }}</span>
              <span class="use-btn" @click="useTemplate(item.id)">使用</span>
            </div>
            <div class="type-item-content ellipsis-2">{{ item.content }}</div>
          </div>
        </div>
      </div>
    </div>


  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { useRoute,useRouter } 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 router = useRouter()
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('')

import iconTemplate1 from '@/assets/icon-template-1.png'
import iconTemplate2 from '@/assets/icon-template-2.png'
import iconTemplate3 from '@/assets/icon-template-3.png'
const templateList1 = ref([
  { id: 1, name: '旅游行业方案模版', content: '你是一个企业管理顾问，现在有一家公 司请', icon: iconTemplate1 },
  { id: 2, name: '工作月报', content: '辅助生成内容全面、条理清晰的工作月 报.', icon: iconTemplate2 },
  { id: 3, name: '会议纪要', content: '全面分析市场需求、竞争环境、商业投 入.', icon: iconTemplate3 }
])
const templateList2 = ref([
  { id: 1, name: '商业计划书', content: '你是一个企业管理顾问，现在有一家公 司请', icon: iconTemplate1 },
])
const useTemplate = async (id) => {
  // 根据ID找到对应的模板
  const template = [...templateList1.value, ...templateList2.value].find(t => t.id === id)
  if (!template) return
  
  try {
    // 调用create接口
    const response = await post('/admin/user/chat/create', {
      userId: userStore.userInfo.id,
      datasetIds: selectedKnowledge.value.join(','),
      templateId: template.id
    })

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

// 对话模型列表
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

  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: message,
    time: new Date()
  })
  
  await scrollToBottom()

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

const simulateStreamResponse = async () => {
  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(inputMessage.value)}&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) {
       
        // accumulatedText = '<think>' + accumulatedText;
          console.log('数据流结束',accumulatedText);
        // 检查是否包含<think>标签
        if (accumulatedText.startsWith('<think>') && accumulatedText.endsWith('</think>')) {
          // 如果是think标签内容，直接显示原文
          messages.value[messageIndex].content = accumulatedText;
        } else {
          // 否则进行markdown渲染
          const formattedText = md.render(accumulatedText);
          messages.value[messageIndex].content = formattedText;
        }
        eventSource.close();
        loading.value = false;
        await scrollToBottom();
        // AI回答结束后跳转到solution-chat页面
        router.push(`/solution-chat?historyId=${chatId.value}`);
        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('连接已建立');
    // 清空输入框
    inputMessage.value = '';
  };
}

// 修改复制功能，去除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:"
          if (answerContent.startsWith('data:')) {
            answerContent = answerContent.substring(5)
          }

          // 尝试解析第一个 JSON 对象（包含实际回答）
          try {
            const firstBrace = answerContent.indexOf('{')
            const lastBrace = answerContent.indexOf('}{')
            if (firstBrace !== -1 && lastBrace !== -1) {
              const jsonStr = answerContent.substring(firstBrace, lastBrace + 1)
              const jsonData = JSON.parse(jsonStr)
              if (jsonData.data && jsonData.data.answer) {
                formattedAnswer = jsonData.data.answer
              }
            }
          } catch (e) {
            console.warn('解析回答内容失败:', e)
            formattedAnswer = answerContent
          }

          // 如果没有成功解析出任何内容，使用原始内容
          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('获取历史记录失败')
  }
}

onMounted(() => {
  const historyId = route.query.historyId
  if (historyId) {
    getHistoryChat(historyId)
  }
  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;
    }
  }
}
.template-section{
  margin: 24px auto;
  width: 800px;
  .template-type{
    .type-title{
      font-size: 20px;
      margin-bottom: 12px;
      font-weight: bold;
    }
    .type-list{
      display:grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 24px;
      .type-item{
        padding: 12px;
        background: #FFFFFF;
        box-shadow: 0px 2px 4px 0px rgba(216,216,216,0.5);
        border-radius: 10px;
        border: 1px solid #EBEBEB;
        margin-bottom: 24px;
        .type-item-title{
          display: flex;
          align-items: center;
          gap: 12px;
          font-size: 16px;
          margin-bottom: 11px;
          img{
            width: 24px;
            height: 24px;
          }
          .use-btn{
            margin-left: auto;
            color: $primary-color;
            font-size: 14px;
            cursor: pointer;
          }
        }
        .type-item-content{
          font-size: 14px;
          color: #777C8C;
          line-height: 1.5;
        }
      }
    }
  }
}
</style> 