<template>
  <div class="ai-chat-container">
    <!-- 消息容器 -->
    <div ref="messageContainer" class="message-list">
      <div v-for="(message, index) in messages" :key="index" :class="['message-item', message.isAI ? 'ai-message' : 'user-message']">
        <!-- 消息内容 -->
        <div class="message-content">
          <div class="message-text" v-if="!message.isAI" v-html="formatMarkdown(message.content)"/>
          <div class="message-text" v-else style=" padding: 5px 0px">
            <mavon-editor
              v-model="message.content"
              :subfield="false"
              :defaultOpen="'preview'"
              :editable="false"
              :toolbarsFlag="false"
              :autosize="true"
              :toolbars="{}"
              style="box-shadow: 0px 0px 0px 0px rgba(0, 0, 0, 0.2); min-height: 50px"
            />
          </div>
        </div>
      </div>
      <!-- 预设问题列表 -->
      <div class="preset-questions" v-if="questionLoading">
        <div
          v-for="(question, index) in presetQuestions"
          :key="index"
          class="preset-question"
          @click="fillInputWithQuestion(question)"
        >
          {{ question }}
        </div>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-indicator">
        <i class="el-icon-loading"></i>
        AI正在思考中...
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="input-area">
      <el-input
        v-model="inputMessage"
        :rows="3"
        placeholder="请输入您的问题..."
        @keydown.enter.native="sendMessage"
      ></el-input>
      <el-button type="primary" @click="sendMessage" :disabled="loading" icon="el-icon-upload2" circle />
    </div>
  </div>
</template>

<script>
import {marked} from 'marked';
import hljs from 'highlight.js/lib/core' // 核心库
import 'highlight.js/styles/atom-one-dark.css' // 引入样式
import DOMPurify from 'dompurify';

import {mavonEditor} from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'

// 注册语言(可扩展其他语言)
import javascript from 'highlight.js/lib/languages/javascript'
import python from 'highlight.js/lib/languages/python'

hljs.registerLanguage('javascript', javascript)
hljs.registerLanguage('python', python)

// 配置marked
marked.setOptions({
  highlight: function (code, lang) {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return hljs.highlight(code, {
          language: lang, // ✅ 新版必须指定language参数
          ignoreIllegals: true
        }).value
      } catch (e) {
        console.error('高亮错误:', e)
        return code
      }
    }
    return hljs.highlightAuto(code).value
  }
})

export default {
  components: {
    mavonEditor
  },
  data() {
    return {
      inputMessage: '',
      messages: [],
      loading: false,
      eventSource: null,
      conversationId: null,//回话ID
      eventData: null, // 存储解析后的JSON对象
      presetQuestions: [],
      questionLoading: true
    }
  },
  methods: {
    formatMarkdown(content) {
      const html = marked(content); // 先解析 Markdown
      return DOMPurify.sanitize(html); // 再清理 HTML
    },
    async sendMessage() {
      if (!this.inputMessage.trim()) return;
      this.questionLoading = false;
      // 添加用户消息
      this.messages.push({content: this.inputMessage, isAI: false});

      this.loading = true;
      // 初始化流式请求
      this.eventSource = new EventSource(process.env.VUE_APP_BASE_API+`/chat/checkChat/chatStream?message=${encodeURIComponent(this.inputMessage)}&conversationId=${this.conversationId}`);

      // 添加AI消息
      let botMessage = {content: "思考中...", isAI: true};
      this.messages.push(botMessage);

      this.eventSource.onmessage = (event) => {
        try {
          this.eventData = JSON.parse(event.data);
          if (this.eventData.event.value === "conversation.chat.created") {
            this.conversationId = this.eventData.chat.conversationID;
            botMessage.content = "";
          }
          if (this.eventData.event.value === "conversation.message.delta") {
            var contentStr = this.eventData.message.content;
            this.loading = false;
            //botMessage.content += this.parseMarkdown(contentStr);
            botMessage.content += contentStr;
          }
        } catch (error) {
          console.error("JSON 解析错误:", error);
          console.log("原始数据:", event.data);
        }

        // 强制 Vue 响应式更新
        this.$forceUpdate();

        // 自动滚动到底部
        this.$nextTick(() => {
          const chatBox = this.$refs.messageContainer;
          if (chatBox) {
            chatBox.scrollTop = chatBox.scrollHeight;
          }
        });
      };

      this.eventSource.onerror = (error) => {
        console.error("SSE 错误:", error);
        this.eventSource.close();
      };

      this.eventSource.onclose = () => {
        this.eventSource.close();
      };

      this.inputMessage = "";
    },

    // 使用DOMPurify防止XSS攻击
    parseMarkdown(text) {
      return DOMPurify.sanitize(marked.parse(text));
    },
    //设置开场白和预设问题
    previewDebugReq(prologue, suggested_questions) {
      this.messages.push({content: prologue, isAI: true});//给机器人设置开场白和预设问题
      this.presetQuestions = suggested_questions;
    },
    //点击预设问题
    fillInputWithQuestion(question) {
      this.inputMessage = question;
    }
  },
  beforeDestroy() {
    if (this.eventSource) {
      this.eventSource.close();
    }
  },
  updated() {
    this.$nextTick(() => {
      hljs.highlightAll()
    })
  }
}
</script>

<style>
.ai-chat-container {
  height: calc(100vh - 215px);
  display: flex;
  flex-direction: column;
  max-width: 550px;
}

.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.message-item {
  display: flex;
  margin-bottom: 20px;
  gap: 15px;
}

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

.message-content {
  position: relative;
}

.message-text {
  padding: 2px 10px;
  border-radius: 8px;
  line-height: 1.2;
}

.user-message .message-text {
  background: #0000000a;
  color: #000000d9;
}

.ai-message .message-text {
  background: white;
  /*border: 1px solid #ebeef5;*/
}

.loading-indicator {
  text-align: center;
  color: #909399;
  padding: 10px;
  font-size: 12px;
}

.input-area {
  padding: 10px;
  background: white;
  box-shadow: 0 -2px 12px rgba(0, 0, 0, 0.1);
  display: flex;
  gap: 15px;
  border-radius: 10px;
  border: 1px solid #ebeef5;
}

/* 确保pre元素保留空白格式 */
.message-text pre {
  background: #282c34 !important; /* 匹配主题色 */
  padding: 15px !important;
  border-radius: 6px !important;
  overflow-x: auto !important;
}

.message-text code {
  font-family: 'Fira Code', monospace !important;
}

.preset-questions {
  padding: 0px 16px;
  font-size: 14px;

  .preset-question {
    border: 1px solid #ebeef5;
    line-height: 1.6;
    padding: 10px;
    margin-bottom: 10px;
    border-radius: 5px;
  }

  .preset-question:hover {
    cursor: pointer;
    background: #0000000a;
  }
}

.message-text pre code.language-PlainText {
  display: block;
  background-color: #282c34; /* 与代码块背景色保持一致 */
  color: #abb2bf; /* 代码文本颜色 */
  padding: 15px;
  border-radius: 6px;
  overflow-x: auto;
  font-family: 'Fira Code', monospace;
  white-space: pre-wrap;
  word-break: break-all;
}
.message-text .v-note-wrapper .v-note-panel .v-note-show .v-show-content{
  padding: 8px 10px 15px 10px;
  background-color:#fff !important
}
</style>
