2025-03-25 15:08:00 +08:00

100 lines
2.7 KiB
JavaScript

/**
* @description 用户信息数据持久化
*/
import { defineStore } from 'pinia'
import { getUserInfoRequest, getWebUrlRequest, 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,
webUrl: null
}
},
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, code: js_code } = params
const openid = await getStorage('openid')
if (!openid) {
return false
}
const { code, data } = await phoneLoginRequest({ iv, encryptedData, openid, js_code })
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)
}
})
}
})
})
},
async getWebUrl() {
if (this.webUrl) {
return { code: 0, data: this.webUrl }
}
const { code, data, message } = await getWebUrlRequest()
if (code === 0) {
this.webUrl = data
return { code, data }
}
return { code, message }
}
}
})