<template>
  <div class="chat-container">

    <div class="chat-box" ref="chatBox">
      <!-- 显示用户消息 -->
      <div v-for="(msg, index) in messages" :key="index" class="message">
        <span v-if="msg.role === 'user'" class="user-msg">{{ msg.content }}</span>
        <div v-if="msg.role === 'bot'" class="bot-msg">
          <!-- mavon-editor 显示机器人回复 -->
          <mavon-editor
            v-model="msg.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);"
          />
        </div>
      </div>

    </div>
    <div class="input-box">
      <el-input
        v-model="userInput"
        :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 {
      userInput: "",
      messages: [],
      eventSource: null,
      conversationId: null,
      eventData: null, // 存储解析后的JSON对象
    }
  },
  methods: {
    formatMarkdown(content) {
      const html = marked(content); // 先解析 Markdown
      return DOMPurify.sanitize(html); // 再清理 HTML
    },
    async sendMessage() {
      if (!this.userInput.trim()) return;

      // 显示用户输入
      this.messages.push({ role: "user", content: this.userInput });

      // 初始化流式请求
      this.eventSource = new EventSource(`http://127.0.0.1:9581/client-api/v1/chat/sendMsg?message=${encodeURIComponent(this.userInput)}&conversationId=${this.conversationId}`);

      let botMessage = { role: "bot", content: "" };
      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;
          }
          if (this.eventData.event.value === "conversation.message.delta") {
            var contentStr = this.eventData.message.content;
            botMessage.content += contentStr;
          }
        } catch (error) {
          console.error("JSON 解析错误:", error);
          console.log("原始数据:", event.data);
        }

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

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

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

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

      this.userInput = "";
    },
  },
  beforeDestroy() {
    if (this.eventSource) {
      this.eventSource.close();
    }
  },
};
</script>

<style>
textarea {
  flex: 1;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 5px;
  resize: none; /* 禁止用户调整大小 */
  min-height: 50px; /* 设置最小高度 */
  max-height: 150px; /* 设置最大高度 */
  overflow-y: auto; /* 内容超出时显示滚动条 */
}

button {
  margin-left: 10px;
  padding: 8px 15px;
  border: none;
  background-color: #007bff;
  color: white;
  border-radius: 5px;
  cursor: pointer;
  align-self: flex-end; /* 按钮与输入框底部对齐 */
}

/* 移除 scoped，让 Markdown 样式生效 */
.chat-container {
  max-width: 800px;
  margin: auto;
  border: 1px solid #ddd;
  border-radius: 10px;
  overflow: auto;
  display: flex;
  flex-direction: column;
  margin-top: 20px;
  margin-bottom: 20px;
  height: 580px;
}

.chat-box {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
  background: #fff;
  min-height: 400px;
}

.input-box {
  display: flex;
  border-top: 1px solid #ddd;
  padding: 10px;
}

input {
  flex: 1;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

button {
  margin-left: 10px;
  padding: 8px 15px;
  border: none;
  background-color: #007bff;
  color: white;
  border-radius: 5px;
  cursor: pointer;
}

button:hover {
  background-color: #0056b3;
}

.message {
  margin-bottom: 10px;
}

.user-msg {
  display: block;
  text-align: right;
  color: #4caf50;
  font-weight: bold;
  padding: 10px;
}

.bot-msg {
  display: block;
  text-align: left;
  /*background: #f0f0f0;*/
  padding: 10px;
  border-radius: 5px;
}

/* 添加 Markdown 样式 */
.bot-msg h1 {
  font-size: 20px;
  font-weight: bold;
  margin-top: 10px;
}

.bot-msg h2 {
  font-size: 18px;
  font-weight: bold;
  margin-top: 10px;
}

.bot-msg h3 {
  font-size: 16px;
  font-weight: bold;
  margin-top: 10px;
}

.bot-msg p {
  margin: 10px 0;
}

.bot-msg ul,
.bot-msg ol {
  padding-left: 20px;
}

.bot-msg pre {
  background: #272822;
  color: #fff;
  padding: 10px;
  border-radius: 5px;
  overflow-x: auto;
}

.bot-msg code {
  font-family: monospace;
  padding: 2px 5px;
  border-radius: 3px;
}

.bot-msg blockquote {
  border-left: 4px solid #ccc;
  padding-left: 10px;
  color: #666;
}

/* 去掉 scoped 属性，样式全局生效 */
.app-container.mavon-editor.ivu-editor {
  border: none;
}
</style>
