const authApi = require('./api/auth') const cartApi = require('./api/cart') const shopApi = require('./api/shop') const userApi = require('./api/user') const auth = require('./utils/auth') const idleSession = require('./utils/idle-session') const theme = require('./utils/theme') const file = require('./utils/file') const { IDLE_TIMEOUT_MS, IDLE_WARNING_MS } = require('./utils/config') App({ globalData: { userInfo: null, isLoggedIn: false, cartCount: 0, shopTheme: theme.DEFAULT_SHOP_THEME, pendingProductFilter: null, pendingWechatMiniLogin: null, wechatMiniAutoLoginState: 'idle' }, onLaunch() { idleSession.init({ timeoutMs: IDLE_TIMEOUT_MS, warningMs: IDLE_WARNING_MS, isLoggedIn: () => auth.isLoggedIn(), onLogout: () => this.handleIdleLogout() }) this.bootstrapSession() if (!auth.isLoggedIn()) { this.tryWechatMiniAutoLogin() } }, onShow() { idleSession.onAppShow() }, onHide() { idleSession.onAppHide() }, bootstrapSession() { const userInfo = auth.getStoredUserInfo() const isLoggedIn = auth.isLoggedIn() this.globalData.userInfo = userInfo this.globalData.isLoggedIn = isLoggedIn this.refreshShopTheme(userInfo) if (userInfo && userInfo.shopId) { auth.setPreferredMiniLoginShopId(userInfo.shopId) } if (isLoggedIn) { this.refreshSessionUserInfo() this.updateCartBadge() return } this.clearCartBadge() }, async tryWechatMiniAutoLogin() { if (auth.isLoggedIn()) { return true } if (this._wechatMiniAutoLoginPromise) { return this._wechatMiniAutoLoginPromise } if (typeof wx === 'undefined' || typeof wx.login !== 'function') { return false } this.globalData.wechatMiniAutoLoginState = 'pending' this._wechatMiniAutoLoginPromise = this.requestWechatMiniCode() .then(code => authApi.wechatMiniAutoLogin({ wxCode: code, preferredShopId: auth.getPreferredMiniLoginShopId() || undefined })) .then(result => this.handleWechatMiniLoginResult(result, { silent: true })) .catch(() => false) .finally(() => { this._wechatMiniAutoLoginPromise = null if (this.globalData.wechatMiniAutoLoginState === 'pending') { this.globalData.wechatMiniAutoLoginState = 'idle' } }) return this._wechatMiniAutoLoginPromise }, handleWechatMiniLoginResult(result, options) { const config = options || {} const status = result && result.status ? result.status : '' if (status === 'SUCCESS') { this.setUserSession(result) this.clearPendingWechatMiniLogin() this.globalData.wechatMiniAutoLoginState = 'idle' return true } if (status === 'SELECT_SHOP') { this.setPendingWechatMiniLogin(result) this.globalData.wechatMiniAutoLoginState = 'idle' if (!config.silent && result.message) { wx.showToast({ title: result.message, icon: 'none' }) } return false } this.clearPendingWechatMiniLogin() this.globalData.wechatMiniAutoLoginState = 'idle' if (!config.silent && result && result.message) { wx.showToast({ title: result.message, icon: 'none' }) } return false }, requestWechatMiniCode() { return new Promise((resolve, reject) => { wx.login({ success: res => { if (res && res.code) { resolve(res.code) return } reject(new Error('获取微信登录凭证失败')) }, fail: reject }) }) }, isWechatMiniAutoLoginPending() { return this.globalData.wechatMiniAutoLoginState === 'pending' }, waitForWechatMiniAutoLogin() { return this._wechatMiniAutoLoginPromise || Promise.resolve(auth.isLoggedIn()) }, setPendingWechatMiniLogin(payload) { this.globalData.pendingWechatMiniLogin = payload || null }, consumePendingWechatMiniLogin() { const pending = this.globalData.pendingWechatMiniLogin this.globalData.pendingWechatMiniLogin = null return pending }, clearPendingWechatMiniLogin() { this.globalData.pendingWechatMiniLogin = null }, setUserSession(payload) { auth.setSession(payload) this.globalData.userInfo = auth.getStoredUserInfo() this.globalData.isLoggedIn = auth.isLoggedIn() this.refreshShopTheme(this.globalData.userInfo) if (this.globalData.userInfo && this.globalData.userInfo.shopId) { auth.setPreferredMiniLoginShopId(this.globalData.userInfo.shopId) } this.updateCartBadge() }, refreshUserInfo(userInfo) { auth.updateStoredUserInfo(userInfo) this.globalData.userInfo = userInfo this.globalData.isLoggedIn = auth.isLoggedIn() this.refreshShopTheme(userInfo) if (userInfo && userInfo.shopId) { auth.setPreferredMiniLoginShopId(userInfo.shopId) } }, clearUserSession() { auth.clearSession() this.globalData.userInfo = null this.globalData.isLoggedIn = false this.setShopTheme(null) this.clearCartBadge() }, setShopTheme(shop) { const resolvedTheme = theme.resolveShopTheme(shop) this.globalData.shopTheme = resolvedTheme this.syncThemeToCurrentPages() if (resolvedTheme.backgroundImageFileId) { this.resolveShopThemeBackground(shop, resolvedTheme.backgroundImageFileId) } }, async resolveShopThemeBackground(shop, fileId) { try { const backgroundImageUrl = await file.getSignedUrl(fileId) if ( !backgroundImageUrl || !this.globalData.shopTheme || this.globalData.shopTheme.backgroundImageFileId !== String(fileId) ) { return } this.globalData.shopTheme = theme.resolveShopTheme({ ...(shop || {}), themeBackgroundImageUrl: backgroundImageUrl }) this.syncThemeToCurrentPages() } catch (error) {} }, async refreshShopTheme(userInfo) { if (!userInfo || !userInfo.shopId) { this.setShopTheme(null) return } try { const shop = await shopApi.getShopById(userInfo.shopId) if (this.globalData.userInfo && String(this.globalData.userInfo.shopId) === String(userInfo.shopId)) { this.setShopTheme(shop) } } catch (error) { this.setShopTheme(null) } }, syncThemeToCurrentPages() { const pages = typeof getCurrentPages === 'function' ? getCurrentPages() : [] const data = theme.pageThemeData(this.globalData.shopTheme) pages.forEach(page => { if (page && typeof page.setData === 'function') { page.setData(data) } }) }, async refreshSessionUserInfo() { if (!auth.isLoggedIn()) { return } try { const userInfo = await userApi.getUserInfo() this.refreshUserInfo(userInfo) } catch (error) {} }, async handleIdleLogout() { if (!auth.isLoggedIn()) { return } try { await authApi.logout() } catch (error) {} this.clearUserSession() wx.showToast({ title: '长时间未操作,已退出登录', icon: 'none' }) setTimeout(() => { wx.reLaunch({ url: '/pages/auth/index' }) }, 260) }, async updateCartBadge() { if (!auth.isLoggedIn()) { this.clearCartBadge() return 0 } try { const cartList = await cartApi.getCartList() const count = Array.isArray(cartList) ? cartList.reduce((sum, item) => sum + Number(item.quantity || 0), 0) : 0 this.globalData.cartCount = count if (count > 0) { wx.setTabBarBadge({ index: 2, text: count > 99 ? '99+' : String(count) }) } else { wx.removeTabBarBadge({ index: 2 }) } return count } catch (error) { this.clearCartBadge() return 0 } }, clearCartBadge() { this.globalData.cartCount = 0 wx.removeTabBarBadge({ index: 2, fail() {} }) } })