<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() {
    this.initApp()
    mqttUtil.disconnectMqtt()
  },
  onShow() {
    console.log('小程序切前台/首次显示')
    const token = getToken() || this.globalData.mqtt.token
    if (token) {
      console.info("token存在，mqtt重新连接中。。")
      this.reconnectMqtt()
    }
  },
  onHide() {
    console.log('小程序切后台')
    const mqttState = mqttUtil.getMqttState()
    if (mqttState.isConnected) {
      this.globalData.mqtt.subscribeList = mqttState.subscribeList
      mqttUtil.disconnectMqtt()
    }
  },
  onUnload() {
    console.log('小程序销毁')
    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)
      }
    },
    loginSuccess(token, subscribeList) {
      this.globalData.mqtt.hasLogin = true
      this.globalData.mqtt.token = token
      this.globalData.mqtt.subscribeList = subscribeList || []
      this.reconnectMqtt()
      console.log('登录成功，MQTT已初始化')
    },
    logout() {
      mqttUtil.disconnectMqtt()
      this.globalData.mqtt = {
        hasLogin: false,
        token: '',
        subscribeList: []
      }
      console.log('登出成功，MQTT已断开')
    }
  }
}
</script>

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