<template>
  <div>
    <el-form>
      <el-form-item label="无人机id">
        <el-input v-model="deviceHardId"></el-input>
      </el-form-item>
      <el-form-item label="操作">
        <el-button @click="subscribe">订阅</el-button>
        <el-button @click="unsubscribe">取消订阅</el-button>
        <el-button @click="publish({type: orders.继续航线任务})">通过原始type发送指令</el-button>
        <el-button @click="order({order: '继续航线任务'})">通过关键字发送指令</el-button>
      </el-form-item>
      <el-form-item label="支持的指令">
        {{ orders }}
      </el-form-item>
    </el-form>
    <div>
      {{ text }}
    </div>
  </div>
</template>

<script>
export default {
  name: 'MQTT',
  data(){
    return {
      deviceHardId: ''
    }
  },
  computed: {
    text(){
      return this.$store.state.MMCMQTT.dataSet;
    },
    orders(){
      return this.$store.state.MMCMQTT.orders;
    },
    topic(){
      return `PX4/RECEIVE/${this.deviceHardId}`;
    }
  },
  async created(){
    try{
      await this.$store.dispatch('MMCMQTT/init', {  
        url: 'mqtts://jianzai.mmcuav.cn/mqtt'
      })
    }catch(e){
      console.log('mqtt失败', e)
    }
    console.log('mqtt连接成功');
  },
  beforeDestroy(){
    this.$store.dispatch('MMCMQTT/end')
  },
  methods: {
    subscribe(){
      this.$store.dispatch('MMCMQTT/subscribe', {
        topic: this.topic,
        callback(){
          console.log('订阅成功')
        }
      })  
    },
    unsubscribe(){
      this.$store.dispatch('MMCMQTT/unsubscribe', {
        topic: this.topic,
        callback(){
          console.log('取消订阅')
        }
      })  
    },
    publish({ type }){
      this.$store.dispatch('MMCMQTT/publish', {
        topic: this.topic,
        data: {
          type
        },
        callback(){
          alert('发送成功')
        }
      })
    },
    order( { order } ){
      this.$store.dispatch('MMCMQTT/order', {
        topic: this.topic,
        order,
        callback(){
          alert('发送成功')
        }
      })
    }
  }
}
</script>