2025-02-06 11:37:41 +08:00

88 lines
2.4 KiB
JavaScript

/**
* @description 用户信息数据持久化
*/
import { defineStore } from 'pinia'
import { getUserInfoRequest, loginRequest, phoneLoginRequest } from '@/api/user'
import { useLockStore } from '@/stores/lock'
import { setStorage, getStorage } from '@/utils/storage'
import { useNotificationStore } from '@/stores/notification'
export const useUserStore = defineStore('user', {
state() {
return {
// 用户信息
userInfo: {},
// 登录状态
isLogin: false
}
},
actions: {
updateUserInfo(data) {
this.userInfo = data
},
updateLoginStatus(status) {
this.isLogin = status
},
// 获取用户信息
async getUserInfo() {
const { code, data } = await getUserInfoRequest()
if (code === 0) {
setStorage('userInfo', data)
this.updateUserInfo(data)
this.updateLoginStatus(true)
}
return code
},
async phoneLogin(params) {
const { iv, encryptedData } = params
const openid = await getStorage('openid')
if (!openid) {
return false
}
const { code, data } = await phoneLoginRequest({ iv, encryptedData, openid })
if (code === 0) {
setStorage('token', data.accessToken)
this.getUserInfo()
useLockStore().updateLockSearch({
...useLockStore().lockSearch,
pageNo: 1
})
useLockStore().getLockList(useLockStore().lockSearch)
useNotificationStore().updateNotificationSearch({
...useNotificationStore().notificationSearch,
pageNo: 1
})
useNotificationStore().getNotificationList(useNotificationStore().notificationSearch)
return true
}
return false
},
async checkSession() {
return new Promise(resolve => {
uni.checkSession({
success() {
resolve(true)
},
fail() {
uni.login({
provider: 'weixin',
async success(loginRes) {
const { code, data } = await loginRequest({
js_code: loginRes.code
})
if (code === 0) {
setStorage('openid', data.openid)
}
resolve(false)
},
fail() {
resolve(false)
}
})
}
})
})
}
}
})