import LoginModal from "@/components/LoginModal";
import MarkdownIt from "markdown-it";
import { pcInnerAi } from "@/api/api";
const md = new MarkdownIt();

export default {
  components: {
    LoginModal,
  },
  data() {
    return {
      messages: [
        {
          user: "bot",
          messageType: "TEXT",
          message: "欢迎使用轻良智能AI助理",
          html: "",
          time: "",
          done: true,
        },
      ],
      generating: false,
      userInput: "",
      websocket: null,
      wsUrl:'http://58.246.234.210:7860/api/v1/run/951e3ba4-c66a-496c-9497-7dbddc2647f8?stream=false',
      tweaks:{},
      showLoginModal: false,
      isLoggedIn: false, // 添加登录状态标志
    };
  },
  created() {
    this.connectWebSocket();
  },
  mounted() {
    if(this.$route.name=='ai'){
      /* 外部知识库 */
      const AIData=JSON.parse(localStorage.getItem("AIData"))
      this.wsUrl=AIData.data.url
      this.tweaks=AIData.data.tweaks
    }else{
      /* 内部知识库 */
      pcInnerAi().then(res=>{
        if(res.status!==200) return
        this.wsUrl=res.data.url
        this.tweaks=res.data.tweaks
        
      })
      
    }
  },
  methods: {
    handleLoginSuccess() {
      this.showLoginModal = false;
      this.isLoggedIn = true;
      // 登录成功后，可以继续发送消息
      this.sendMessage();
    },
    getUuid() {
      return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(
        /[xy]/g,
        function (c) {
          var r = (Math.random() * 16) | 0,
            v = c == "x" ? r : (r & 0x3) | 0x8;
          return v.toString(16);
        }
      );
    },
    connectWebSocket() {
      const wsUrl = this.wsUrl//'http://58.246.234.210:7860/api/v1/run/951e3ba4-c66a-496c-9497-7dbddc2647f8?stream=false'
      // 这里做一个简单的鉴权，只有符合条件的鉴权才能握手成功
      // 移除这里的fetch调用，改用WebSocket
      this.websocket = new WebSocket(wsUrl);
    
      this.websocket.onerror = (event) => {
        console.error("WebSocket 连接错误:", event);
      };
    
      this.websocket.onclose = (event) => {
        console.log("WebSocket 连接关闭:", event);
      };
    
      this.websocket.onopen = (event) => {
        console.log("WebSocket 连接已建立:", event);
      };
      this.websocket.onmessage = (event) => {
        // 解析收到的消息
        const result = JSON.parse(event.data);

        console.log(result.content);

        // 检查消息是否完结
        if (result.done) {
          this.messages[this.messages.length - 1].done = true;
          return;
        }

        if (this.messages[this.messages.length - 1].done) {
          // 添加新的消息
          this.messages.push({
            time: Date.now(),
            message: result.content,
            messageType: "TEXT",
            user: "bot",
            done: false,
          });
        } else {
          // 更新最后一条消息
          let lastMessage = this.messages[this.messages.length - 1];
          lastMessage.message += result.content;
          this.messages[this.messages.length - 1] = lastMessage;
        }
      };
    },
    async sendMessage() {
      if(this.$route.name=='ai'){
        if(!localStorage.getItem('AIData')){
          this.showLoginModal=true
          return
        }
      }
      const chatId = this.getUuid();
      const wsUrl =this.wsUrl//'http://58.246.234.210:7860/api/v1/run/951e3ba4-c66a-496c-9497-7dbddc2647f8?stream=false'
      let message = this.userInput.trim();
      if (message) {
        // Markdown换行：在每个换行符之前添加两个空格
        message = message.replace(/(\r\n|\r|\n)/g, "  \n");

        this.messages.push({
          time: Date.now(),
          message: message,
          messageType: "TEXT",
          user: "user",
          done: true,
        });
        this.userInput = "";
        console.log(this.messages);
        // 通过 HTTP 发送消息
        try {
          ///send-message
          const response = await fetch(`${wsUrl}`, {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify({
              chatId: chatId,
              input_value: message,
              output_type: "chat",
              input_type: "chat",
              tweaks:this.tweaks/*  {
                "ChatInput-dDbhW": {},
              "Prompt-1stgH": {},
              "ChatOutput-b1zWw": {},
              "OllamaModel-5n7vc": {},
              "Milvus-1X7fT": {},
              "OllamaEmbeddings-V29wK": {},
              "Memory-GrHZr": {},
              "ParseData-0dk9n": {}
              } */,
            }),
          });

          if (!response.ok) {
            const errorText = await response.text(); // 获取错误文本
            throw new Error(
              `HTTP error! status: ${response.status}, message: ${errorText}`
            );
          }

          const result = await response.json();
          this.handleResponse(result);
        } catch (error) {
          console.error("Error sending message:", error);
        }
      }
    },
    handleResponse(value) {
       const data =value.outputs[0].outputs[0].results.message
      this.messages.push({
        user: "bot",
        messageType: data.text_key,
        message: data.text,
        html: "",
        time: data.timestamp,
        done: true,
      });
    },
    renderMarkdown(rawMarkdown) {
      return md.render(rawMarkdown);
    },
    handleKeydown(event) {
      // Check if 'Enter' is pressed without the 'Alt' key
      if (event.key === "Enter" && !(event.shiftKey || event.altKey)) {
        event.preventDefault(); // Prevent the default action to avoid line break in textarea
        this.sendMessage();
      } else if (event.key === "Enter" && event.altKey) {
        // Allow 'Alt + Enter' to insert a newline
        const cursorPosition = event.target.selectionStart;
        const textBeforeCursor = this.userInput.slice(0, cursorPosition);
        const textAfterCursor = this.userInput.slice(cursorPosition);

        // Insert the newline character at the cursor position
        this.userInput = textBeforeCursor + "\n" + textAfterCursor;

        // Move the cursor to the right after the inserted newline
        this.$nextTick(() => {
          event.target.selectionStart = cursorPosition + 1;
          event.target.selectionEnd = cursorPosition + 1;
        });
      }
    },
    beforeDestroy() {
      if (this.websocket) {
        this.websocket.close();
      }
    },
  },
  updated() {
    const messagesContainer = this.$el.querySelector(".messages");
    messagesContainer.scrollTop = messagesContainer.scrollHeight;
  },
};
