<script>
import config from './config'
import { getToken } from '@/utils/auth'
import mqttUtil from '@/utils/mqtt'
import {startMqttOnlinePing, stopMqttOnlinePing} from "./utils/mqtt";
import {batchSubscribe} from "./api/system/mqtt";
import store from "store";
import {listAgri} from "./api/system/assets/agri";

export default {
  subscribeList:[],
  globalData: {
    config: {},
    mqtt: {
      hasLogin: false,
      token: '',
      subscribeList: []
    }
  },
  onLaunch: function() {

    // 仅开发环境生效
    // #ifdef H5
    if (process.env.NODE_ENV === 'development') {

      // 监听热重载事件（HBuilderX特有）
      document.addEventListener('uni-app:reload', () => {
        console.log('开发环境代码热更新') ;
        mqttUtil.disconnectMqtt(); // 断开旧MQTT连接
      });
    }
    // 监听H5页面刷新/关闭事件
    window.addEventListener('beforeunload', () => {
      mqttUtil.disconnectMqtt()
      console.log('H5刷新，强制断开MQTT连接')
    })
    // #endif
    // #ifdef mp-weixin
    this.checkMiniProgramUpdate();
    // #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()
      }

      // 防止 mqtt client 还没连上：可以等 connected 后再 start（见下面提示）
      startMqttOnlinePing( 20000);
    }
  },
  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()
      stopMqttOnlinePing();
    }
  },
  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
      }
      var clientId = mqttUtil.getMqttState().clientId;
      this.getSubscribeImei(clientId).then(res=>{
        console.info("subscribeList",res)
        const subscribeList = res;
        this.globalData.mqtt.subscribeList = subscribeList || []
        batchSubscribe({clientId: clientId}).then((result) => {
          if (result.code === 200) {
            console.info(`设备列表订阅成功：${subscribeList}`)
          }
        })

        // ========== 新增：登录成功时同步到localStorage ==========
        uni.setStorageSync('mqtt_subscribe_list', subscribeList || [])

        if (subscribeList.length > 0) {
          mqttUtil.updateSubscribeList(subscribeList)
          console.log('恢复MQTT订阅列表：', subscribeList)
          // ========== 新增：恢复订阅后同步到localStorage ==========
          uni.setStorageSync('mqtt_subscribe_list', subscribeList)
        }
      })
    },
    loginSuccess(token) {
      this.globalData.mqtt.hasLogin = true
      this.globalData.mqtt.token = token

      this.reconnectMqtt()
      console.log('登录成功，MQTT已初始化')
    },
    logout() {
      mqttUtil.disconnectMqtt()
      this.globalData.mqtt = {
        hasLogin: false,
        token: '',
        subscribeList: []
      }
      // ========== 新增：登出时清空localStorage的订阅列表 ==========
      uni.removeStorageSync('mqtt_subscribe_list')
      console.log('登出成功，MQTT已断开')
    },

    getSubscribeImei(clientId) {
      return listAgri().then(response => {
        const subscribeList = [];
          if (response.code === 200) {
            response.rows.forEach(item =>
                subscribeList.push(`frontend/${clientId}/dtu/${item.imei}/+`)
            );
            if (store.getters && store.getters.name === 'admin') {
              subscribeList.push(`frontend/${clientId}/dtu/862538065276061/+`)
            }
          }
          return subscribeList;
      })
    },
    // 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'
          })
        }
      })
    },


    // 小程序版本更新检测+MQTT清理
    checkMiniProgramUpdate() {
      // 第二步：再判断API是否存在（兜底，避免低版本微信不支持）
      if (!uni.canIUse('getUpdateManager')) {
        console.log('当前微信版本过低，不支持版本更新检测');
        return;
      }
      if (!uni.canIUse('getUpdateManager')) return;

      const updateManager = uni.getUpdateManager();
      // 检测到有新版本
      updateManager.onCheckForUpdate((res) => {
        if (res.hasUpdate) {
          console.log('检测到小程序新版本，准备清理MQTT');
        }
      });

      // 新版本下载完成，准备重启前：先清理MQTT
      updateManager.onUpdateReady(() => {
        // 第一步：取消MQTT订阅+断开连接
        mqttUtil.disconnectMqtt()

        // 第二步：提示用户重启
        uni.showModal({
          title: '版本更新',
          content: '新版本已准备好，重启后即可体验',
          success: (res) => {
            if (res.confirm) {
              // 重启小程序加载新版本
              updateManager.applyUpdate();
            }
          }
        });
      });

      // 新版本下载失败，兜底清理
      updateManager.onUpdateFailed(() => {
        mqttUtil.disconnectMqtt()
        uni.showToast({
          title: '更新失败，已重置连接',
          icon: 'none'
        });
      });
    }
  }
}
</script>

<style lang="scss">
// 加上图鸟会全变白
//@import './tuniao-ui/index.scss';
//@import './tuniao-ui/iconfont.css';
@import '@/static/scss/index.scss';
//@import "colorui/main.css";
//@import "colorui/icon.css";
</style>
