import pagesJson from '@/pages.json' import { getApiUrl } from '@/common/config.js' // 由于 store.js 在主包中,无法直接访问子包中的 config.js // 使用默认配置值 const config = { setPasswordAfterLogin: false // 默认值,如果需要修改,可以在这里调整 } // 获取用户信息,避免在模块加载时就执行 uni-app API let hostUserInfo = null function getHostUserInfo() { // 总是从存储中读取最新值,确保登录状态的实时性 // 特别是在微信小程序中,页面跳转可能导致模块重新加载 try { if (typeof uni !== 'undefined' && uni && typeof uni.getStorageSync === 'function') { const storedUserInfo = uni.getStorageSync('uni-id-pages-userInfo') || {}; return storedUserInfo; } } catch (e) { // 在模块初始化时,uni可能还未完全初始化,静默失败 } return {}; } // 初始化用户信息(只调用一次) const initialUserInfo = getHostUserInfo() || {}; const data = { userInfo: initialUserInfo, hasLogin: Object.keys(initialUserInfo).length != 0 } // 定义 mutations, 修改属性 export const mutations = { // 更新用户信息(简化版,不使用数据库) async updateUserInfo(data = false) { if (data) { // 直接更新本地用户信息 this.setUserInfo(data) if (typeof uni !== 'undefined' && uni.showToast) { uni.showToast({ title: "更新成功", icon: 'none', duration: 3000 }); } } else { // 如果没有传入数据,不做任何操作(不再从数据库获取) // #ifdef APP-PLUS || H5 || MP-ALIPAY console.log('updateUserInfo called without data, skipping database operation') // #endif } }, /** * 从本地存储中重新加载用户信息到store * 用于解决store初始化时uni未准备好导致的问题 */ syncUserInfoFromStorage() { try { if (typeof uni !== 'undefined' && uni && typeof uni.getStorageSync === 'function') { const storedUserInfo = uni.getStorageSync('uni-id-pages-userInfo') || {}; if (Object.keys(storedUserInfo).length > 0) { this.setUserInfo(storedUserInfo, { cover: true }); return true; } } } catch (e) { // 静默失败 } return false; }, setUserInfo(data, {cover}={cover:false}) { // 确保data是一个对象 const safeData = data && typeof data === 'object' ? data : {}; let userInfo = cover ? safeData : Object.assign({}, store.userInfo || {}, safeData); store.userInfo = Object.assign({}, userInfo); store.hasLogin = Object.keys(store.userInfo).length != 0; if (typeof uni !== 'undefined' && uni && typeof uni.setStorageSync === 'function') { try { uni.setStorageSync('uni-id-pages-userInfo', store.userInfo); } catch (e) { // 静默失败 } } return safeData; }, async logout() { // 检查 uni 是否可用 if (typeof uni === 'undefined') { console.warn('uni API not available for logout') return } // 优先调用后端自定义登出接口(/api/sys/auth/logout),失败也不影响本地清理 const backendUserId = uni.getStorageSync('backend-user-id') if (backendUserId) { try { await uni.request({ url: getApiUrl('/api/sys/auth/logout'), method: 'POST', header: { 'Content-Type': 'application/x-www-form-urlencoded' }, data: { userId: backendUserId } }) } catch (e) { console.error('后端登出接口调用失败:', e) } } // 清理本地登录状态(后端 token + 旧 uni-id token + tenantId) uni.removeStorageSync('backend-token') uni.removeStorageSync('backend-login-response') uni.removeStorageSync('backend-user-id') uni.removeStorageSync('backend-tenant-id') // 清除 tenantId uni.removeStorageSync('uni_id_token'); uni.setStorageSync('uni_id_token_expired', 0) this.setUserInfo({},{cover:true}) uni.$emit('uni-id-pages-logout') uni.redirectTo({ url: `/${pagesJson.uniIdRouter && pagesJson.uniIdRouter.loginPage ? pagesJson.uniIdRouter.loginPage: 'uni_modules/uni-id-pages/pages/login/login-withoutpwd'}`, }); }, loginBack (e = {}) { // 检查 uni 是否可用 if (typeof uni === 'undefined') { console.warn('uni API not available for loginBack') return } const {uniIdRedirectUrl = ''} = e let delta = 0; //判断需要返回几层 let pages = getCurrentPages(); // console.log(pages); pages.forEach((page, index) => { if (pages[pages.length - index - 1].route.split('/')[3] == 'login') { delta++ } }) // console.log('判断需要返回几层:', delta); if (uniIdRedirectUrl) { return uni.redirectTo({ url: uniIdRedirectUrl, fail: (err1) => { uni.switchTab({ url:uniIdRedirectUrl, fail: (err2) => { console.log(err1,err2) } }) } }) } // #ifdef H5 if (e.loginType == 'weixin') { // console.log('window.history', window.history); return window.history.go(-3) } // #endif if (delta) { const page = pagesJson.pages[0] return uni.reLaunch({ url: `/${page.path}` }) } uni.navigateBack({ delta }) }, loginSuccess(e = {}){ const { showToast = true, toastText = '登录成功', autoBack = true, uniIdRedirectUrl = '', passwordConfirmed } = e // console.log({toastText,autoBack}); // 检查 uni 是否可用 if (typeof uni === 'undefined') { console.warn('uni API not available for loginSuccess') return } if (showToast) { uni.showToast({ title: toastText, icon: 'none', duration: 3000 }); } // 异步调用(更新用户信息)防止获取头像等操作阻塞页面返回 this.updateUserInfo() uni.$emit('uni-id-pages-login-success') if (config.setPasswordAfterLogin && !passwordConfirmed) { return uni.redirectTo({ url: uniIdRedirectUrl ? `/uni_modules/uni-id-pages/pages/userinfo/set-pwd/set-pwd?uniIdRedirectUrl=${uniIdRedirectUrl}&loginType=${e.loginType}`: `/uni_modules/uni-id-pages/pages/userinfo/set-pwd/set-pwd?loginType=${e.loginType}`, fail: (err) => { console.log(err) } }) } if (autoBack) { this.loginBack({uniIdRedirectUrl}) } } } // #ifdef VUE2 import Vue from 'vue' // 通过Vue.observable创建一个可响应的对象 export const store = Vue.observable(data) // #endif // #ifdef VUE3 // 在小程序环境中,可能 reactive 不可用,使用简单的对象 export const store = data // #endif