import {defineStore} from "pinia";
import FriendApi from "@/api/FriendApi";
import type Friend from "@/mode/Friend";
import type User from "@/mode/User";
import SendCode from '@/utils/SendCode'
import {useUserStore} from '@/store/userStore'
import ChatType from '@/utils/ChatType'
import MessageType from '@/utils/MessageType'
import {useWsStore} from '@/store/WsStore'

export interface State {
  friendList: User[];
  waitValidateList: Friend[];
}

export const useFriendStore = defineStore({
  id: "friend_store",
  state: (): State => ({
    friendList: [],
    waitValidateList:[]
  }),
  actions: {
   loadData() {
       const userStore = useUserStore()
       FriendApi.friends().then((res) => {
           this.friendList = res.data
           //缓存好友，用于聊天时头像名称显示
           res.data.forEach((item: User) => {
               userStore.storeUser(item.id, {
                     name: item.name,
                     avatar: item.avatar
               })
           })
       })
    },
   loadValidateList() {
      FriendApi.validateList().then((res) => {
        this.waitValidateList = res.data;
      });
    },
    /**
     * 告诉对方需要刷新store
     * @param userId 对方id
     */
    notifyFlushFriendStore(userId: string) {
      const fromId = useUserStore().getUser()?.id
      if (fromId) {
        const sendInfo = {
          code: SendCode.NEW_FRIEND,
          message: {
            mine: true,
            fromId: fromId,
            chatId: userId,
            type: ChatType.FRIEND,
            messageType: MessageType.text,
            content: '',
            timestamp: new Date().getTime()
          }
        }
        useWsStore().send(JSON.stringify(sendInfo))
      }
    }
  },
});
