import mqtt from 'mqtt'

export const mqttMixins = {
  data() {
    return {
      client: null,
      topic: 'data-collect-topic',
      message: null,
      warnRecordMsg: null,
    }
  },
  mounted() {
    this.initMqtt()
  },
  methods: {
    initMqtt () {
      const options = {
        //mqtt客户端的id
        clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8),
        host: '182.207.99.106',
        port: 1883,
        protocol: 'tcp',
        connectTimeout: 4000,
        username: 'admin',
        password: 'jingang@mqtt',
        clean: true
      }
      this.client = mqtt.connect(options)
      this.client.on('connect', () => {
        this.$notify({
          title: '成功',
          message: 'MQTT连接成功',
          duration: 2000,
          type: 'success'
        })
        console.log('连接成功....')
        this.client.subscribe(this.topic, { qos: 1 }, error => {
          if (!error) {
            console.log('消息订阅成功')
          } else {
            console.log('消息订阅失败')
          }
        })
        this.client.subscribe('warn-record', { qos: 1 }, error => {
          if (!error) {
            console.log('消息订阅成功')
          } else {
            console.log('消息订阅失败')
          }
        })
      })
      this.client.on('message', (topic, message) => this.receiveMessages(topic, message))
      this.client.on('end', () => {
        console.log('MQTT断开连接!')
      })
      this.client.on('offline', () => {
        console.log('MQTT OFFLINE !')
        this.$notify({
          title: '错误',
          message: 'MQTT连接失败',
          duration: 2000,
          type: 'error'
        })
      })
      //如果连接错误，打印错误
      this.client.on('error', err => {
        console.log('err=>', err)
        this.client.end()
        this.$notify({
          title: '错误',
          message: 'MQTT连接失败',
          duration: 2000,
          type: 'error'
        })
      })
    },
    receiveMessages(topic, message) {
      // console.log('收到来自', topic, '的消息---->>', message.toString())
      // console.log('收到来自', topic, '的消息---->>', JSON.parse(message.toString()))
      if (topic === 'data-collect-topic') {
        this.message = JSON.parse(message.toString())
      } else if (topic === 'warn-record') {
        this.warnRecordMsg = JSON.parse(message.toString())
        console.log('收到来自', topic, '的消息---->>', message.toString())
      }
    },
    mqttPublish () {
      const topic = 'topic/response' //和后台约定好的主题
      this.client.publish(topic, JSON.stringify(this.message))
    },
  },
  beforeDestroy () {
    if (this.client) {
      this.client.end()
    }
  },
}
