wlzboy
4 天以前 cfe0b79fbea0fb1d7a5a796e71ada7d3b7812046
app/App.vue
@@ -3,60 +3,166 @@
  import store from '@/store'
  import { getToken } from '@/utils/auth'
  import { getUnreadCount } from '@/api/message'
  import storage from '@/utils/storage'
  import { redirectToLoginByEnvironment } from '@/utils/wechat'
  export default {
    onLaunch: function() {
      this.initApp()
    data() {
      return {
        messagePollingTimer: null,
        lastToken: null // 用于检测 token 变化
      }
    },
    onLaunch: function(options) {
      console.log('App onLaunch, options:', options);
      this.lastToken = getToken()
      this.initApp(options)
      // 检查并清理存储空间
      this.checkStorage()
      // 监听用户登录事件
      uni.$on('user-login', () => {
        console.log('接收到用户登录事件,启动消息轮询')
        const token = getToken()
        if (token) {
          this.lastToken = token
          this.updateUnreadMessageBadge()
          // this.startMessagePolling()
        }
      })
      // 监听用户登出事件
      uni.$on('user-logout', () => {
        console.log('接收到用户登出事件,停止消息轮询')
        this.stopMessagePolling()
        this.lastToken = null
        // 清除消息徽标
        try {
          uni.removeTabBarBadge({ index: 3 })
        } catch (e) {
          console.error('清除消息徽标失败:', e)
        }
      })
    },
    onShow: function() {
      // 应用显示时刷新未读消息数量
      if (getToken()) {
        this.updateUnreadMessageBadge()
      const currentToken = getToken()
      // 检测 token 变化:从有到无(登出)
      if (this.lastToken && !currentToken) {
        console.log('检测到用户已登出,停止消息轮询')
        this.stopMessagePolling()
        this.lastToken = currentToken
        return
      }
      // 检测 token 变化:从无到有(登录)
      if (!this.lastToken && currentToken) {
        console.log('检测到用户已登录,启动消息轮询')
        this.lastToken = currentToken
      }
      // 应用显示时刷新未读消息数量
      // 注意:只有已登录且不在登录页面时才调用
      if (currentToken && !this.isLoginPage()) {
        this.updateUnreadMessageBadge()
        // 重新启动轮询(如果之前已停止)
        if (!this.messagePollingTimer) {
          this.startMessagePolling()
        }
      }
    },
    onHide: function() {
      // 应用隐藏时停止轮询,节省资源
      this.stopMessagePolling()
    },
    methods: {
      // 初始化应用
      initApp() {
        // 初始化应用配置
        this.initConfig()
        // 检查用户登录状态
        //#ifdef H5
        this.checkLogin()
        //#endif
        // 如果已登录,启动未读消息轮询
        if (getToken()) {
          this.updateUnreadMessageBadge()
          // 每30秒轮询一次
          this.startMessagePolling()
      initApp(options) {
        try {
          // 初始化应用配置
          this.initConfig()
          // 检查用户登录状态并自动跳转到合适的登录页面
          this.checkLoginAndRedirect(options)
        } catch (e) {
          console.error('初始化应用失败:', e)
        }
        // 注意:不在应用启动时自动启动轮询
        // 只有在用户主动登录成功后才启动(通过 user-login 事件触发)
      },
      initConfig() {
        this.globalData.config = config
      },
      checkLogin() {
        if (!getToken()) {
          this.$tab.reLaunch('/pages/login')
      // 检查登录状态并自动跳转到合适的登录页面
      checkLoginAndRedirect(options) {
        try {
          if (!getToken()) {
            console.log('用户未登录,准备跳转到登录页面')
            // 使用工具类根据环境自动跳转到合适的登录页面
            redirectToLoginByEnvironment(options, this.$tab);
          } else {
            console.log('用户已登录,无需跳转')
          }
        } catch (e) {
          console.error('检查登录状态并跳转失败:', e)
          // fallback到普通登录页面
          try {
            this.$tab.reLaunch('/pages/login');
          } catch (fallbackError) {
            console.error('fallback跳转也失败了:', fallbackError);
          }
        }
      },
      // 判断当前是否在登录页面
      isLoginPage() {
        try {
          const pages = getCurrentPages()
          if (pages.length === 0) {
            return false
          }
          const currentPage = pages[pages.length - 1]
          const route = currentPage.route || ''
          // 判断是否为登录相关页面
          return route.includes('login') || route.includes('register')
        } catch (e) {
          console.error('判断是否为登录页面失败:', e)
          return false
        }
      },
      
      // 更新未读消息徽标
      updateUnreadMessageBadge() {
        // 检查是否已登录,未登录则不请求
        if (!getToken()) {
          console.log('用户未登录,跳过获取未读消息数量')
          return
        }
        getUnreadCount().then(response => {
          const count = response.data || 0
          console.log('未读消息数量:', count)
          
          if (count > 0) {
            // 设置徽标
            uni.setTabBarBadge({
              index: 3, // 消息页面在tabBar中的索引位置(0开始)
              text: count > 99 ? '99+' : count.toString()
            })
            try {
              uni.setTabBarBadge({
                index: 3, // 消息页面在tabBar中的索引位置(0开始)
                text: count > 99 ? '99+' : count.toString()
              })
            } catch (e) {
              console.error('设置消息徽标失败:', e)
            }
          } else {
            // 移除徽标
            uni.removeTabBarBadge({
              index: 3
            })
            try {
              uni.removeTabBarBadge({
                index: 3
              })
            } catch (e) {
              console.error('移除消息徽标失败:', e)
            }
          }
        }).catch(error => {
          console.error('获取未读消息数量失败:', error)
@@ -65,22 +171,58 @@
      
      // 启动消息轮询
      startMessagePolling() {
        // 每30秒轮询一次
        this.messagePollingTimer = setInterval(() => {
          if (getToken()) {
            this.updateUnreadMessageBadge()
          } else {
            // 如果用户已登出,停止轮询
            this.stopMessagePolling()
          }
        }, 30000) // 30秒
        try {
          // 每30秒轮询一次
          this.messagePollingTimer = setInterval(() => {
            if (getToken()) {
              this.updateUnreadMessageBadge()
            } else {
              // 如果用户已登出,停止轮询
              this.stopMessagePolling()
            }
          }, 30000) // 30秒
        } catch (e) {
          console.error('启动消息轮询失败:', e)
        }
      },
      
      // 停止消息轮询
      stopMessagePolling() {
        if (this.messagePollingTimer) {
          clearInterval(this.messagePollingTimer)
          this.messagePollingTimer = null
        try {
          if (this.messagePollingTimer) {
            clearInterval(this.messagePollingTimer)
            this.messagePollingTimer = null
          }
        } catch (e) {
          console.error('停止消息轮询失败:', e)
        }
      },
      // 检查存储空间
      checkStorage() {
        try {
          // 获取存储信息
          const info = storage.getStorageInfo()
          if (info) {
            const usagePercent = (info.currentSize / info.limitSize) * 100
            console.log(`💾 存储使用情况: ${usagePercent.toFixed(2)}% (${info.currentSize}KB / ${info.limitSize}KB)`)
            // 如果使用超过 80%,自动清理
            if (usagePercent > 80) {
              console.warn('⚠️ 存储空间使用超过 80%,开始自动清理...')
              storage.checkAndClean()
              // 再次检查
              const newInfo = storage.getStorageInfo()
              if (newInfo) {
                const newUsagePercent = (newInfo.currentSize / newInfo.limitSize) * 100
                console.log(`✅ 清理后使用情况: ${newUsagePercent.toFixed(2)}%`)
              }
            }
          }
        } catch (e) {
          console.error('检查存储失败:', e)
        }
      }
    }
@@ -89,4 +231,4 @@
<style lang="scss">
  @import '@/static/scss/index.scss'
</style>
</style>