<script>
import config from './config'
import { getToken } from '@/utils/auth'
import mqttUtil from '@/utils/mqtt'

export default {
  globalData: {
    config: {},
    mqtt: {
      hasLogin: false,
      token: '',
      subscribeList: []
    }
  },
  onLaunch: function() {
    // #ifdef H5
    // 监听H5页面刷新/关闭事件
    window.addEventListener('beforeunload', () => {
      mqttUtil.disconnectMqtt()
      console.log('H5刷新，强制断开MQTT连接')
    })
    // #endif
    this.initApp()
    mqttUtil.disconnectMqtt()

    // ========== 新增：H5刷新后，从localStorage恢复订阅列表 ==========
    const savedSubscribeList = uni.getStorageSync('mqtt_subscribe_list')
    if (savedSubscribeList && savedSubscribeList.length > 0) {
      this.globalData.mqtt.subscribeList = savedSubscribeList
    }
    // ========== 新增：被踢下线断开mqtt ==========


    // 2. 监听token过期事件（全局事件）
    uni.$on('tokenExpired', () => {
      console.info("被动token校验")
      this.handleTokenExpired()
    })
  },
  onShow() {
    // 重新进入后执行
    console.log('小程序切前台/首次显示')
    const token = getToken() || this.globalData.mqtt.token
    if (token) {

      // 兜底检查：如果globalData里没有列表，但缓存里有，补充恢复
      if (this.globalData.mqtt.subscribeList.length === 0) {
        const savedSubscribeList = uni.getStorageSync('mqtt_subscribe_list')
        if (savedSubscribeList && savedSubscribeList.length > 0) {
          this.globalData.mqtt.subscribeList = savedSubscribeList
        }
      }
      console.info("clientaasa: ",mqttUtil.getMqttState().client)
      if (mqttUtil.getMqttState().client==null) {
        console.info("token存在，mqtt重新连接中。。")
        this.reconnectMqtt()
      }
    }
  },
  onHide() {
    console.log('小程序切后台')
    const mqttState = mqttUtil.getMqttState()
    if (mqttState.isConnected) {
      this.globalData.mqtt.subscribeList = mqttState.subscribeList
      // ========== 新增：切后台时同步到localStorage ==========
      uni.setStorageSync('mqtt_subscribe_list', this.globalData.mqtt.subscribeList)
      mqttUtil.disconnectMqtt()
    }
  },
  methods: {
    // 初始化应用
    initApp() {
      // 初始化应用配置
      this.initConfig()
      // 检查用户登录状态
      //#ifdef H5
      this.checkLogin()
      //#endif
      const token = getToken()
      if (token) {
        this.globalData.mqtt.hasLogin = true
        this.globalData.mqtt.token = token
      }
    },
    initConfig() {
      this.globalData.config = config
    },
    checkLogin() {
      if (!getToken()) {
        this.$tab.reLaunch('/pages/login')
      }
    },
    reconnectMqtt() {
      const initSuccess = mqttUtil.initMqttConfig()
      if (!initSuccess) {
        console.error('MQTT配置初始化失败')
        return
      }

      const connectSuccess = mqttUtil.connectMqtt()
      if (!connectSuccess) {
        console.error('MQTT连接失败')
        return
      }

      const subscribeList = this.globalData.mqtt.subscribeList
      if (subscribeList.length > 0) {
        mqttUtil.updateSubscribeList(subscribeList)
        console.log('恢复MQTT订阅列表：', subscribeList)
        // ========== 新增：恢复订阅后同步到localStorage ==========
        uni.setStorageSync('mqtt_subscribe_list', subscribeList)
      }
    },
    loginSuccess(token, subscribeList) {
      this.globalData.mqtt.hasLogin = true
      this.globalData.mqtt.token = token
      this.globalData.mqtt.subscribeList = subscribeList || []
      // ========== 新增：登录成功时同步到localStorage ==========
      uni.setStorageSync('mqtt_subscribe_list', subscribeList || [])
      this.reconnectMqtt()
      console.log('登录成功，MQTT已初始化')
    },
    logout() {
      mqttUtil.disconnectMqtt()
      this.globalData.mqtt = {
        hasLogin: false,
        token: '',
        subscribeList: []
      }
      // ========== 新增：登出时清空localStorage的订阅列表 ==========
      uni.removeStorageSync('mqtt_subscribe_list')
      console.log('登出成功，MQTT已断开')
    },



    // token过期处理逻辑（核心）
    handleTokenExpired() {

      console.info("被踢下线")
      // 1. 断开MQTT连接
      mqttUtil.disconnectMqtt()

      // 2. 清除token和用户信息
      this.globalData.mqtt = {
        hasLogin: false,
        token: '',
        subscribeList: []
      }

      // 3. 提示用户并跳转登录页
      uni.showModal({
        title: '提示',
        content: '登录已过期，请重新登录',
        showCancel: false,
        success: () => {
          // 跳转登录页（关闭所有页面，避免返回）
          uni.reLaunch({
            url: '/pages/login'
          })
        }
      })
    }
  }
}
</script>

<style lang="scss">
@import '@/static/scss/index.scss'
</style>