import { defineStore } from 'pinia'
import { reactive } from 'vue'
import { setToken, removeToken } from '@/utils/auth'
import { smsLogin, passwordLogin } from '@/api/common/index'
import { logout } from '@/api/common/index'
import { getUserInfo } from '@/api/personal/user'
import Snackbar from '@/plugins/snackbar'

export const useUserStore = defineStore('user',
  () => {
    let accountInfo = reactive({}) // 登录返回的信息
    let userInfo = reactive({}) // 当前登录账号信息

    // 短信登录
    const handleSmsLogin = async (data) => {
      return new Promise((resolve, reject) => {
        smsLogin(data).then(res => {
          console.log(res, 'login-phone')
          setToken(res.accessToken)
          accountInfo = res
          localStorage.setItem('accountInfo', JSON.stringify(res))
          localStorage.setItem('expiresTime', res.expiresTime) // token过期时间
          getUserInfos()
          resolve()
        }).catch(err => { reject(err) })
      })
    }

    // 密码登录
    const handlePasswordLogin = async (data) => {
      return new Promise((resolve, reject) => {
        passwordLogin(data).then(res => {
          console.log(res, 'login-password')
          setToken(res.accessToken)
          accountInfo = res
          localStorage.setItem('accountInfo', JSON.stringify(res))
          localStorage.setItem('expiresTime', res.expiresTime) // token过期时间
          getUserInfos()
          resolve()
        }).catch(err => { reject(err) })
      })
    }

    // 获取当前登录账户信息
    const getUserInfos = async () => {
      try {
        const data = await getUserInfo({ id: accountInfo.userId })
        userInfo = data
        localStorage.setItem('userInfo', JSON.stringify(data))
      } catch (error) {
        Snackbar.error(error.msg)
      }
    }

    // 退出登录
    const userLogout = async () => {
      await logout()
      removeToken()
      userInfo = {}
      accountInfo = {}
      localStorage.clear()
    }
    return {
      userInfo,
      handleSmsLogin,
      userLogout,
      handlePasswordLogin
    }
  },
  {
    persist: true,
  }
)

