import { defineStore } from "pinia";
import {
  deleteMessages,
  updateConversationTitle,
  type Message,
} from "@/api/conversation";
import { userStore } from "./user";
import { ChatConversationState } from "@/types/chatConversation";

const useConversationStore = defineStore("conversation", {
  state: (): ChatConversationState => {
    return {
      conversationId: "",
      conversationList: [],
      currentConversationMessages: [],
      isReadyNewConversation: false,
    };
  },
  actions: {
    newConversation() {
      const user = userStore();

      //如果没有会话id，说明是新会话
      if (this.conversationId === "") {
        this.isReadyNewConversation = true;
        this.conversationList.push({
          conversationId: "-1",
          userId: parseInt(user.token),
          startedAt: new Date().toISOString(),
          endedAt: "",
          status: "ongoing",
          messages: "",
          messageList: [],
        });
      } else {
        //从现有对话中新建对话前，清空当前对话消息
        this.currentConversationMessages = [];
        localStorage.removeItem("currentMessages");
      }
    },
    saveConversationList(list) {
      this.conversationList = list;
      localStorage.setItem("CONVERSATIONLIST", JSON.stringify(list));
    },
    clearConversationList() {
      this.conversationList = [];
      localStorage.removeItem("CONVERSATIONLIST");
    },
    /**
     *  * 更新会话标题
     *  * 请求成功响应后，更新本地会话列表
     * @param messageId 会话id
     * @param message 待更新的会话标题
     */
    async updateConversationMesg(messageId: number, message: string) {
      await updateConversationTitle(messageId, message);
      this.conversationList.find((conversation) => {
        if (conversation.messageId === messageId) {
          conversation.messages = message;
        }
      });
      localStorage.setItem(
        "CONVERSATIONLIST",
        JSON.stringify(this.conversationList)
      );
      console.log("update conversation message");
    },
    async deleteConversation(conversationId: string) {
      await deleteMessages(conversationId);

      this.conversationList = this.conversationList.filter(
        (conversation) => conversation.conversationId !== conversationId
      );
      localStorage.setItem(
        "CONVERSATIONLIST",
        JSON.stringify(this.conversationList)
      );
      console.log("delete conversation");
    },
    clearConversationAll() {
      this.conversationList = [];
      this.currentConversationMessages = [];
      localStorage.removeItem("CONVERSATIONLIST");
    },
  },
});

export default useConversationStore;
