import { defineStore } from "pinia";
import { deleteImageConversation, updateImageTitle } from "@/api/aiImage";
import { SVGConversationState } from "@/types/svgConversation";
//TODO 该文件的代码复制自imageConversation.ts，后续需要重构
const useSVGConversationStore = defineStore("svgConversation", {
  state: (): SVGConversationState => {
    return {
      conversationId: "",
      conversationList: [],
      currentConversationMessages: [],
      isReadyNewConversation: false,
    };
  },
  actions: {
    newConversation() {
      //如果没有会话id，说明是新会话
      if (this.conversationId === "") {
        this.isReadyNewConversation = true;
      } else {
        //从现有对话中新建对话前，清空当前对话消息
        this.currentConversationMessages = [];
        localStorage.removeItem("currentMessages");
      }
    },
    saveConversationList(list) {
      this.conversationList = list;
      localStorage.setItem("CREATECONVERSATIONLIST", JSON.stringify(list));
    },
    clearConversationList() {
      this.conversationList = [];
      localStorage.removeItem("CREATECONVERSATIONLIST");
    },
    /**
     *  * 更新会话标题
     *  * 请求成功响应后，更新本地会话列表
     * @param messageId 会话id
     * @param message 待更新的会话标题
     */
    async updateConversationMesg(messageId: number, message: string) {
      //   const messageIdStr = messageId.toString();
      //   await updateImageTitle({ messageId: messageIdStr, message });
      //   this.conversationList.find((conversation) => {
      //     if (conversation.messageId === messageId) {
      //       console.log("replcae");
      //       conversation.messages = message;
      //     }
      //   });
      //   localStorage.setItem(
      //     "CONVERSATIONLIST",
      //     JSON.stringify(this.conversationList)
      //   );
      //   console.log("update conversation message");
    },
    async deleteConversation(conversationId: string) {
      //   await deleteImageConversation(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");
      console.log("clear conversation all");
    },
  },
});

export default useSVGConversationStore;
interface baseImageMessage {
  sender: string;
  sentAt: string;
}

interface ResAIImageMessage extends baseImageMessage {
  id: number;
  url: string;
}

interface ReqUserMessage extends baseImageMessage {
  text: string;
}

// 合并这三个接口为一个 ImageMessage 类型
export type ImageMessage = ResAIImageMessage | ReqUserMessage;
