import mqtt from 'mqtt'

//let HOST = '192.168.3.51'

const apiInfo = uni.getStorageSync('apiInfo')

let HOST = apiInfo.hostname

if (process.env.NODE_ENV == 'development') {
  HOST = '124.71.68.31'
}
const ENDPOINT = '/mqtt'
const connection = {
  protocol: 'ws',
  host: HOST,
  port: 81,
  endpoint: ENDPOINT,
  // for more options, please refer to https://github.com/mqttjs/MQTT.js#mqttclientstreambuilder-options
  clean: true,
  connectTimeout: 30 * 1000, // ms
  reconnectPeriod: 4000, // ms
  clientId: 'emqx_vue_' + Math.random().toString(16).substring(2, 8)
}
let Mymqtt = {
  data () {
    return {
      mqttClient: null
    }
  },
  beforeDestroy () {
    if (this.mqttClient) {
      this.mqttClient.end()
    }
  },
  methods: {
    mqttInit () {
      const { protocol, host, endpoint, port, ...options } = connection

      const connectUrl = `${protocol}://${host}:${port}${endpoint}`

      this.mqttClient = mqtt.connect(connectUrl, options)

      if (this.mqttClient.on) {
        this.mqttClient.on('connect', () => {
          console.log('连接成功')
          // 订阅
          this.doSubscribe(this.TOPIC)
        })
        this.mqttClient.on('reconnect', () => {
          console.log('重连')
        })
        this.mqttClient.on('error', error => {
          console.log('Connection failed', error)
        })
        this.mqttClient.on('message', (topic, message) => {
          console.log('ff', topic, JSON.parse(message))
        })

        this.mqttClient.on('message', (topic, message) => {
          let data = JSON.parse(message).items
          this.initMqttData(data)
        })
      }
    },
    // 订阅
    doSubscribe (subscription) {
      let { topic, qos } = subscription
      this.mqttClient.subscribe(topic, { qos }, (error, res) => {
        if (error) {
          console.log('Subscribe to topics error', error)
          return
        }
        console.log(`订阅:${topic}成功`, res)
      })
    }
  }
}
export default Mymqtt
