import type {
  CategorySpeakers,
  IChatWithLLMRequest,
  ModelInfo,
  ModelListInfo,
  Speaker,
  UsageInfo
} from "@/interfaces";
import { ChatService } from "@/services";

export const useChatStore = defineStore("chat", () => {
  const router = useRouter();
  const token = "sk-fkGVZBrAqvIxLjlF3b5f19EfBb63486c90Fa5a1fBd7076Ee";

  // 默认模型
  const modelInfo = ref<ModelInfo | null>(null);
  // 历史消息
  const historyMessages = ref<IChatWithLLMRequest["messages"]>([]);
  // 是否正在响应
  const completing = ref<boolean>(false);
  // 是否正在思考
  const thinking = ref<boolean>(false);
  // 模型列表
  const modelList = ref<ModelListInfo[]>([]);
  // 音色列表
  const speakerList = ref<CategorySpeakers[]>([]);
  // 当前音色信息
  const speakerInfo = ref<Speaker | null>(null);
  // 在线人数
  const onlineCount = ref<number>(0);

  // 生成消息ID方法
  const generateMessageId = () => new Date().getTime().toString();

  // 获取最后一条消息
  const getLastMessage = () =>
    historyMessages.value[historyMessages.value.length - 1];

  // 与 LLM 聊天
  const chatWithLLM = async (
    request: IChatWithLLMRequest,
    onProgress: (content: string) => void,
    getUsageInfo: (object: UsageInfo) => void = () => {},
    getThinking: (thinkingContent: string) => void = () => {}
  ) => {
    if (completing.value) throw new Error("正在响应中");

    completing.value = true;
    try {
      await ChatService.ChatWithLLM(
        token,
        request,
        onProgress,
        getUsageInfo,
        getThinking
      );
    } catch (error) {
      console.error("请求失败:", error);
    } finally {
      completing.value = false;
    }
  };

  // 添加消息到历史记录
  const addMessageToHistory = (
    message: string,
    role: "user" | "assistant" = "user",
    type: "chat" | "voice" = "chat"
  ) => {
    const content = message.trim();
    if (!content) return;

    historyMessages.value.push({
      role,
      content,
      type,
      id: generateMessageId()
    });
  };

  // 清除历史消息
  const clearHistoryMessages = (type?: "chat" | "voice") => {
    historyMessages.value = type
      ? historyMessages.value.filter((msg) => msg.type !== type)
      : [];
  };

  // 确保最后一条消息是助手消息
  const ensureAssistantMessage = () => {
    const lastMessage = getLastMessage();
    if (!lastMessage || lastMessage.role !== "assistant") {
      historyMessages.value.push({
        role: "assistant",
        content: ""
      });
    }
  };

  // 处理聊天响应的逻辑
  const handleChatResponse = async (
    messages: IChatWithLLMRequest["messages"]
  ) => {
    if (!modelInfo.value) return;

    // 过滤出type为chat的聊天消息
    const filteredMessages = computed(() =>
      messages.filter((msg) => msg.type === "chat" || !msg.type)
    );

    await chatWithLLM(
      { messages: filteredMessages.value, model: modelInfo.value.model_id },
      // 处理文本内容
      (content) => {
        ensureAssistantMessage();
        thinking.value = false;
        getLastMessage().content = content;
      },
      // 处理使用信息
      (usageInfo: UsageInfo) => {
        const lastMessage = getLastMessage();
        if (lastMessage?.role === "assistant") {
          lastMessage.usage = usageInfo;
        }
      },
      // 处理思维链
      (thinkingContent: string) => {
        ensureAssistantMessage();
        thinking.value = true;
        getLastMessage().thinking = thinkingContent;
      }
    );

    // 设置消息ID
    getLastMessage().id = generateMessageId();
  };

  watch(
    historyMessages,
    (newVal) => {
      if (newVal.length > 0 && router.currentRoute.value.path === "/") {
        const lastMessage = newVal[newVal.length - 1];
        if (lastMessage.role === "user") {
          handleChatResponse(newVal);
        }
      }
    },
    { deep: true }
  );

  // 获取模型列表
  const getModelList = async () => {
    try {
      const response = await ChatService.GetModelList();
      modelList.value = response.data.data;
    } catch (error) {
      console.error("获取模型列表失败:", error);
    }
  };

  // 获取音色列表
  const getSpeakerList = async () => {
    try {
      const response = await ChatService.GetSpeakerList();
      speakerList.value = response.data.data;
    } catch (error) {
      console.error("获取音色·列表失败:", error);
    }
  };

  return {
    token,
    completing,
    thinking,
    modelInfo,
    modelList,
    historyMessages,
    chatWithLLM,
    addMessageToHistory,
    clearHistoryMessages,
    getModelList,
    onlineCount,
    speakerList,
    getSpeakerList,
    speakerInfo
  };
});
