import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getUserInfoApi, logoutApi } from '@/api'
// import type { smsLoginType, accountLoginType, updatePasswordType } from '@/api';
// import defaultAvatar from "@/static/default_avatar.png";
import { global } from '@/store'
import router from '@/router/router'
import db from '@/utils/db'

export const useUserStore = defineStore('user', () => {
  const userInfo = ref({} as any)
  const token = ref('')
  const { getDicts } = global()

  const afterLogin = async () => {
    await Promise.allSettled([getUserInfo(), getDicts()])
  }

  const logout = async () => {
    await logoutApi()
    clear()
    router.toLogin()
  }

  const getUserInfo = async () => {
    const mode = import.meta.env.MODE
    // 如果是正式环境 && 且缺少openid，直接跳回登录页面
    if (mode !== 'dev' && mode !== 'mp' && !db.get('wxUser')) {
      router.toLogin()
      return
    }

    const res = await getUserInfoApi()
    userInfo.value = res
    return res
  }

  const clear = async () => {
    token.value = ''
    userInfo.value = {}
  }

  const setToken = (data: string) => {
    token.value = data
  }

  return {
    userInfo,
    token,
    getUserInfo,
    logout,
    clear,
    afterLogin,
    setToken,
  }
})
