<template>
  <view>
    <!-- MQTT 客户端组件 -->
    <slot :connect="connect" :disconnect="disconnect" :publish="publish" :subscribe="subscribe" :unsubscribe="unsubscribe" :status="status" :topics="topics">
      <!-- 默认插槽内容，用户可自定义 -->
    </slot>
  </view>
</template>

<script>
import MQTTClient from '../js_sdk/index.js'

export default {
  name: 'mqtt-client',
  props: {
    options: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      mqtt: null,
      status: 'disconnected',
      topics: []
    }
  },
  created() {
    this.mqtt = new MQTTClient(this.options)
    
    this.mqtt.on('statusChange', (status) => {
      this.status = status
      this.$emit('status-change', status)
    })
    
    this.mqtt.on('message', (msg) => {
      this.$emit('message', msg)
    })
    
    this.mqtt.on('connect', () => {
      this.$emit('connect')
    })
    
    this.mqtt.on('disconnect', (res) => {
      this.$emit('disconnect', res)
    })
    
    this.mqtt.on('error', (error) => {
      this.$emit('error', error)
    })
  },
  beforeDestroy() {
    if (this.mqtt) {
      this.mqtt.disconnect()
    }
  },
  methods: {
    connect() {
      if (this.mqtt) {
        this.mqtt.connect()
      }
    },
    disconnect() {
      if (this.mqtt) {
        this.mqtt.disconnect()
      }
    },
    publish(topic, message, qos = 0) {
      if (this.mqtt) {
        this.mqtt.publish(topic, message, qos)
      }
    },
    subscribe(topic, qos = 0) {
      if (this.mqtt) {
        this.mqtt.subscribe(topic, qos)
        if (!this.topics.includes(topic)) {
          this.topics.push(topic)
        }
      }
    },
    unsubscribe(topic) {
      if (this.mqtt) {
        this.mqtt.unsubscribe(topic)
        const index = this.topics.indexOf(topic)
        if (index > -1) {
          this.topics.splice(index, 1)
        }
      }
    }
  }
}
</script>

<style>
</style>
