import { defineStore } from 'pinia' import { MINI_PROGRAM_ID } from '@/config' import { devLogin, login } from '@/api/worldcup' import { storage, TOKEN_KEY, USER_KEY } from '@/utils/storage' export const useUserStore = defineStore('user', { state: () => ({ token: storage.get(TOKEN_KEY) || '', user: storage.get(USER_KEY) || null, loginPromise: null }), actions: { async silentLogin(force = false) { if (this.token && !force) return this.token if (this.loginPromise) return this.loginPromise this.loginPromise = new Promise((resolve, reject) => { // #ifdef MP-WEIXIN uni.login({ provider: 'weixin', success: async (res) => { try { const payload = await login({ mini_program_id: MINI_PROGRAM_ID, code: res.code }) this.saveLogin(payload.data) resolve(this.token) } catch (e) { reject(e) } finally { this.loginPromise = null } }, fail: (err) => { this.loginPromise = null reject(err) } }) // #endif // #ifndef MP-WEIXIN devLogin({ mini_program_id: MINI_PROGRAM_ID }) .then((payload) => { this.saveLogin(payload.data) resolve(this.token) }) .catch(reject) .finally(() => { this.loginPromise = null }) // #endif }) return this.loginPromise }, saveLogin(data) { this.token = data?.token || '' this.user = data?.user || null storage.set(TOKEN_KEY, this.token) storage.set(USER_KEY, this.user) } } })