import { aiModelAvatar, customerAvatar } from "@/mock-data/mock-chat-view";
import { Client, type LLMService } from "@/models";
import { MODEL_CONFIGS } from "@/models/config";
import type { IMessage } from "@/types";
import dayjs from "dayjs";
import { defineStore } from "pinia";
import { ref } from "vue";
import { useChatHistoryStore } from "./history-store";
import { useChatModelStore } from "./model-store";
import { useChatStatusStore } from "./status-store";

import { eventBus } from "@/utils/event-bus";

import OpenAI from "openai";
import api from "@/services";

export const useChatMessageStore = defineStore("chat-message", () => {
  const chatStatusStore = useChatStatusStore();
  const chatHistoryStore = useChatHistoryStore();
  const chatModelStore = useChatModelStore();
  const messages = ref<IMessage[]>([]);
  const messageChangeCount = ref(0);
  let client: LLMService;

  const geogebraData = ref("");

  function cnEssayAsk(question: string, image_url: string, grade_name: string) {
    if (question === "") {
      return;
    }
    if (!messages.value.length) {
      chatStatusStore.startChat = true;
      chatStatusStore.newChatId();
    }
    chatHistoryStore.addHistory(
      chatStatusStore.currentChatId,
      dayjs().format("YYYY-MM-DD HH:mm"),
      messages.value,
      chatModelStore.currentModel
    );
    messages.value.push({
      from: "user",
      content: question,
      avatarPosition: "side-right",
      avatarConfig: { ...customerAvatar },
    });
    messageChangeCount.value++;
    getAIAnswer(image_url, 3, grade_name);
  }

  function enEssayAsk(question: string, image_url: string, grade_name: string) {
    if (question === "") {
      return;
    }
    if (!messages.value.length) {
      chatStatusStore.startChat = true;
      chatStatusStore.newChatId();
    }
    chatHistoryStore.addHistory(
      chatStatusStore.currentChatId,
      dayjs().format("YYYY-MM-DD HH:mm"),
      messages.value,
      chatModelStore.currentModel
    );
    messages.value.push({
      from: "user",
      content: question,
      avatarPosition: "side-right",
      avatarConfig: { ...customerAvatar },
    });
    messageChangeCount.value++;
    getAIAnswer(image_url, 4, grade_name);
  }

  function imgAsk(question: string, image_url: string) {
    if (question === "") {
      return;
    }
    if (!messages.value.length) {
      chatStatusStore.startChat = true;
      chatStatusStore.newChatId();
    }
    chatHistoryStore.addHistory(
      chatStatusStore.currentChatId,
      dayjs().format("YYYY-MM-DD HH:mm"),
      messages.value,
      chatModelStore.currentModel
    );
    messages.value.push({
      from: "user",
      content: question,
      avatarPosition: "side-right",
      avatarConfig: { ...customerAvatar },
    });
    messageChangeCount.value++;
    getAIAnswer(image_url, 1, "");
  }

  function ask(question: string) {
    if (question === "") {
      return;
    }
    if (!messages.value.length) {
      chatStatusStore.startChat = true;
      chatStatusStore.newChatId();
    }
    chatHistoryStore.addHistory(
      chatStatusStore.currentChatId,
      dayjs().format("YYYY-MM-DD HH:mm"),
      messages.value,
      chatModelStore.currentModel
    );
    messages.value.push({
      from: "user",
      content: question,
      avatarPosition: "side-right",
      avatarConfig: { ...customerAvatar },
    });
    messageChangeCount.value++;
    getAIAnswer(question, 2, "");
  }

  const getAIAnswer = async (
    content: string,
    type_id: number,
    grade_name: string
  ) => {
    messages.value.push({
      from: "ai-model",
      content: "",
      avatarPosition: "side-left",
      avatarConfig: { ...aiModelAvatar },
      loading: true,
      complete: false,
    });

    let completion;
    if (type_id === 1) {
      completion = await api.IMG_Outline(content);
    } else if (type_id === 2) {
      completion = await api.TXT_Outline(content);
    } else if (type_id === 3) {
      completion = await api.CnEssay_Outline(content, grade_name);
    } else if (type_id === 4) {
      completion = await api.EnEssay_Outline(content, grade_name);
    }

    const reader: ReadableStreamDefaultReader = completion.body.getReader();
    const decoder = new TextDecoder("utf-8");

    messages.value[messages.value.length - 1].loading = false;

    // 用于累积数据的缓冲区
    let buffer = "";

    const readStream = () => {
      reader.read().then(({ done, value }) => {
        messageChangeCount.value++;
        if (done) {
          console.log("完成");
          console.log(geogebraData.value);
          eventBus.emit("call-ggb-command", {
            ggb: geogebraData.value,
          });
          return;
        }
        const chunk = decoder.decode(value, { stream: true });

        console.log(chunk);

        const lines = chunk.trim().split("data: ");

        for (const line of lines) {
          try {
            const data = JSON.parse(line);
            if (data.content) {
              messages.value[messages.value.length - 1].content +=
                data.content.replace("```", "\n```");

              // 同时将内容添加到缓冲区用于geogebra数据提取
              buffer += data.content;
              extractGeogebraData(buffer);
            }
          } catch (e) {
            // console.log("忽略解析错误:", e);
          }
        }

        readStream();
      });
    };
    readStream();

    // 提取geogebra数据的函数
    const extractGeogebraData = (text: string) => {
      const regex = /```geogebra([\s\S]*?)```/g;
      const matches = text.match(regex);

      if (matches && matches.length > 0) {
        // 获取最后一个匹配的geogebra数据
        const lastMatch = matches[matches.length - 1];
        const geogebraContent = lastMatch
          .replace(/```geogebra\n?/, "")
          .replace(/```\n?$/, "")
          .trim();

        // 更新geogebra数据变量
        geogebraData.value = geogebraContent;

        // 触发事件通知其他组件
        eventBus.emit("geogebra-data-updated", {
          type: "geogebra-data",
          data: geogebraContent,
        });
      }
    };
  };

  return { messages, messageChangeCount, ask, imgAsk, cnEssayAsk, enEssayAsk };
});
