import { defineStore } from "pinia";
import { store } from "@/stores";
import https from "@/https";
import storage, { actions } from "@/utils/storage";
import socketApi from '@/socket/socketApi'
import router from "@/router";
import { toast } from "@/utils/toast";
import http from "@/https";
export const useUserStore = defineStore("user", {
  state() {
    return {
      userInfo: <any>{},
      vipInfo: <any>{},
      // 新邮件
      newMail:<number> 0,
      noticesShow:<number> 0,
      // 拼单单中奖信息
      pddAward:<Array<any>>[],
    };
  },
  actions: {
    setUserInfo(data: any) {
      this.userInfo = { ...data }
    },
    setPddAward(data:any) {
      this.pddAward = [...data]
    },
    async getUserInfo() {
      const { data, code, txt }: ResultData = await https.userInfo();
      console.log(data, code, txt, 'getUserInfogetUserInfo')
      data.totalPay = data.totalPay || 0;
      if (code !== 0) {
        router.push('/login')
        this.clearUser()
        toast(txt)
        return { status: false, msg: txt, code }
      };
      storage.setStorage(actions.USER_INFO, JSON.stringify(data))
      this.setUserInfo(data)
      this.getVipLvInfo()
      await this.getNewNotice()
      await this.checkNewMail()
      return { status: true, msg: txt, code };
    },
    clearUser() {
      storage.removeStorage(actions.USER_INFO);
      storage.removeStorage(actions.USER_TOEKN);
      storage.removeSessionStorage(actions.DRAW_POPUP);
      this.setUserInfo({})
    },
    // vip详情
    getVipLvInfo() {
      http.getVipLvInfo().then((res: any) => {
        if (res.code !== 0) return;
        this.vipInfo = res.data;
      });
    },
    async getNewNotice(){
      const res = await http.checkNewNotice();
      this.noticesShow = res.data.newNotice || 0;
    },
    async checkNewMail () {
      const res = await http.checkNewMail();
      if (res.code == 0) {
        this.newMail = res.data.newMail;
      }
    },
    // 监听是否有新邮件
    hasNewMail(num: number) {
      this.newMail = num
    },
    hasNewNotice(num: number) {
      this.noticesShow += num
    }
  }
})

// Need to be used outside the setup
export const useUserStoreWithOut = () => {
  return useUserStore(store);
};