import { mqtt_url, mqtt_options, mqtt_topics } from '@/settings'
import * as mqtt from 'mqtt/dist/mqtt.min'
import { generateClientId } from '@/utils'
export default {
  destroyed() {
    if (this.client.connected) {
      try {
        this.client.end(false, () => {
          console.log('Successfully disconnected!')
        })
      } catch (error) {
        console.log('Disconnect failed', error.toString())
      }
    }
  },
  methods: {
    initMqtt(
      params = {
        topicName: '',
        mqttResponse: () => {}
      }
    ) {
      const clientId = generateClientId()
      const mqttOptions = mqtt_options
      mqttOptions.clientId = clientId

      const client = mqtt.connect(mqtt_url, mqttOptions)
      client.on('connect', function() {
        console.log('Connected')
        client.subscribe(mqtt_topics, function(err) {
          console.log(err)
          if (!err) {
            client.publish('topic/1', 'Hello mqtt')
          } else {
            client.publish('topic/1', 'Hello mqtt err')
          }
        })
      })
      client.on('message', function(_topic, message) {
        if (Array.isArray(params.topicName)) {
          if (params.topicName.includes(_topic) && params.mqttResponse && message) {
            params.mqttResponse(JSON.parse(message.toString()))
          }
        } else {
          if (params.topicName === _topic && params.mqttResponse && message) {
            params.mqttResponse(JSON.parse(message.toString()))
          }
        }
      })
      client.on('reconnect', (error) => {
        console.log('正在重连:', error)
      })
      client.on('error', (error) => {
        console.log('连接失败:', error)
      })
      client.on('close', function() {
        console.log('Disconnected')
      })
      client.on('offline', function() {
        console.log('offline')
      })
      this.client = client
    }
  }
}
