import mqtt from 'mqtt'
import store from '@/store'

export default {
  client: null, // mqtt连接 对象
  url: store.state.settings.mqttHost, // mqtt服务器地址
  options: { // mqtt服务器 参数配置
    port: store.state.settings.mqttPort,
    connectTimeout: 3000,
    clientId: store.state.user.shop_id,
    clean: true,
    keepalive: 60,
    username: store.state.settings.mqttUserName,
    password: store.state.settings.mqttPassword
  },
  mqttConf,
  mqttDestroy,
  doSubscribe,
  publishFun
}

/**
 * @Description: mqtt对象初始化
 */
function mqttConf () {
  if (!this.client || (this.client && !this.client.connected)) {
    // 如果 client 不存在，或存在但未连接，重新连接
    this.client = mqtt.connect(this.url, this.options)

    this.client.on('error', () => {
      store.dispatch('fetchLog', { content: '指令服务器异常中断' })
    })
    this.client.on('reconnect', () => {
      store.dispatch('fetchLog', { content: '重新连接指令服务器' })
    })
    this.client.on('offline', () => {
      store.dispatch('fetchLog', { content: '指令服务器异常中断' })
      store.state.app.mqttState = false
    })
  }
}
/**
 * @description: 获取主题消息
 * @param {string} topic 主题名称
 * @param {fun} callBack 回调 传一个对象{topic订阅的主题,msg接收到主题的数据} 在父级给获取
 */
function doSubscribe (topic, callBack) {
  // 订阅主题
  this.client.on('connect', () => {
    if (store.state.app.mqttState === false) {
      store.dispatch('fetchLog', { content: '成功连接指令服务器' })
    }
    store.state.app.mqttState = true // 标记mqtt链接成功 在线
    // 订阅一个主题
    this.client.subscribe(topic, { qos: 2 })
  })
  // 获取订阅主题的消息
  this.client.on('message', (topic, message) => {
    callBack({ topic: topic, msg: message.toString() })
  })
}
/**
  * @description: 向指定topic发送消息
  * @param {*} topic 发送信息到的主题 不包括前缀
  * @param {*} msg 要发送的信息
  */
function publishFun (topic, msg) {
  // topic要保持一致
  this.client.publish(topic, msg, {
    qos: 2
  })
}
/**
 * @Description: 销毁mqtt对象
 */
function mqttDestroy () {
  if (this.client) {
    this.client.end() // 离开页面的时候  关闭mqtt连接
    this.client = null
  }
}
