// MQTT连接测试工具
import { createMqtt, getConnectionStatus, closeMqtt } from './sendMqtt.js'

class MqttTest {
  constructor() {
    this.testResults = []
  }

  // 运行MQTT连接测试
  async runTest() {
    console.log('🧪 开始MQTT连接测试...')
    
    try {
      // 测试1: 创建连接
      console.log('📋 测试1: 创建MQTT连接')
      createMqtt()
      
      // 等待连接建立
      await this.waitForConnection(10000) // 等待10秒
      
      // 测试2: 检查连接状态
      console.log('📋 测试2: 检查连接状态')
      const isConnected = getConnectionStatus()
      console.log('连接状态:', isConnected)
      
      // 测试3: 监听数据
      console.log('📋 测试3: 设置数据监听')
      uni.$on('mqttData', (data) => {
        console.log('✅ 收到测试数据:', data)
        this.testResults.push({
          type: 'data_received',
          data: data,
          timestamp: new Date().toISOString()
        })
      })
      
      // 等待数据
      console.log('⏳ 等待MQTT数据...')
      await this.waitForData(30000) // 等待30秒
      
      // 输出测试结果
      this.printTestResults()
      
    } catch (error) {
      console.error('❌ MQTT测试失败:', error)
    }
  }

  // 等待连接建立
  waitForConnection(timeout = 10000) {
    return new Promise((resolve, reject) => {
      const startTime = Date.now()
      const checkInterval = setInterval(() => {
        const isConnected = getConnectionStatus()
        if (isConnected) {
          clearInterval(checkInterval)
          console.log('✅ MQTT连接建立成功')
          resolve(true)
        } else if (Date.now() - startTime > timeout) {
          clearInterval(checkInterval)
          console.log('⏰ MQTT连接超时')
          reject(new Error('连接超时'))
        }
      }, 1000)
    })
  }

  // 等待数据接收
  waitForData(timeout = 30000) {
    return new Promise((resolve) => {
      const startTime = Date.now()
      const checkInterval = setInterval(() => {
        if (this.testResults.length > 0 || Date.now() - startTime > timeout) {
          clearInterval(checkInterval)
          resolve()
        }
      }, 1000)
    })
  }

  // 打印测试结果
  printTestResults() {
    console.log('📊 MQTT测试结果:')
    console.log('连接状态:', getConnectionStatus())
    console.log('收到数据次数:', this.testResults.length)
    
    if (this.testResults.length > 0) {
      console.log('最新数据:', this.testResults[this.testResults.length - 1])
    }
  }

  // 清理测试
  cleanup() {
    uni.$off('mqttData')
    closeMqtt()
    console.log('🧹 MQTT测试清理完成')
  }
}

// 导出测试实例
export default new MqttTest()