import { defineStore } from 'pinia'
import cache from '~/utils/cache'
import { login, getUserInfo, logout } from '@/api/user'

export const useUserStore = defineStore('user', () => {
  const token = ref<string>(cache.get('token') || '')
  const userInfo = ref<Record<string, any>>({})

  // 登录
  const loginAction = (params: Record<string, any>) => {
    return new Promise((resolve, reject) => {
      login(params)
        .then((data) => {
          token.value = data.token
          cache.set('token', data.token || '')
          resolve(data)
        })
        .catch((err) => {
          reject(err)
        })
    })
  }

  // 退出登录
  const logoutAction = () => {
    try {
      logout()
    } catch (error) {
      console.log(error)
    }
    resetAuth()
  }

  // 获取用户信息
  const getUserAction = async () => {
    return new Promise((resolve, reject) => {
      getUserInfo()
        .then((data) => {
          userInfo.value = data
          resolve(data)
        })
        .catch((err) => {
          reject(err)
        })
    })
  }

  // 重置授权信息
  const resetAuth = () => {
    token.value = ''
    userInfo.value = {}
    cache.remove('token')
    useRouter().replace('/login')
  }

  return {
    token,
    userInfo,
    login: loginAction,
    logout: logoutAction,
    getUser: getUserAction,
    resetAuth
  }
})
