<template>
  <div class="lowpower-containner">
    <!-- <el-button :loading="isSubscribe" @click="subscribe"> 订阅</el-button> -->
    <el-row>
      <!-- 检测步骤 -->
      <el-col :span="6" class="main-left">
        <!-- 步骤组件 模块 -->
        <check-steps :check-steps-parames="checkStepsParames" />
      </el-col>
      <el-col :span="18" class="main-right">
        <div class="main-right-container">
          <!-- MQTT报文 消息 -->
          <!-- <div @click="delClick">111</div> -->
          <el-table v-if="processData" :data="processData" stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-form label-position="left" inline class="demo-table-expand">
                  <el-form-item v-for="(item,index) in scope.row.eid_list" :key="index+item.original_message" :label="`数据${index+1}`">
                    <span>test_cate: {{ item.test_cate }}</span><br>
                    <span>test_item: {{ item.test_item }}</span><br>
                    <span>eid: {{ item.eid }}</span><br>
                    <span>original_message: {{ item.original_message }}</span>
                  </el-form-item>
                </el-form>
              </template>
            </el-table-column>
            <el-table-column prop="message" label="message" />
            <el-table-column prop="task_id" label="task_id" />
            <!-- <el-table-column fixed="right" label="操作" width="160">
              <template slot-scope="scope">
                <el-button
                  class="table-act"
                  type="text"
                  icon="el-icon-delete"
                  size="small"
                  @click="delClick(scope.row, scope.$index)"
                >删除</el-button>
              </template>
            </el-table-column> -->
            <!-- 隐藏 列 这里不用显示，但是在编辑的时候需要获取此数据 -->
            <el-table-column
              v-if="false"
              prop="deviceCheckId"
              label="序号"
            />
            <!-- 隐藏 列 -->
          </el-table>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import mqtt from 'mqtt' // 引入 mqtt 库
import CheckSteps from './CheckSteps.vue'

export default {
  name: 'MQTT',
  components: { CheckSteps },
  props: {
    deviceDetail: {
      type: Object,
      default: function() {
        return
      }
    }
  },
  data() {
    return {
      startTopic: '/V2.0.0/detection/start',
      client: null, // MQTT 客户端
      clientConnected: false,
      message: [], // 接收到的消息
      stepActionStatus: 'cancel',
      isSubscribe: false, // MQTT是否订阅
      // 步骤组件所需相关参数
      checkStepsParames: {
        checkPlans: this.deviceDetail.deviceCheckPlans
      },
      processData: [],
      itemData: [],
      messageData: []
    }
  },
  methods: {
    // 订阅MQTT消息
    subscribe() {
      this.isSubscribe = true
      // 连接 mqtt 客户端
      this.client = mqtt.connect('ws://192.168.1.236:8083/mqtt')

      // console.log('this.client=', this.client)
      // console.log('this.client.connected=', this.client.connected)
      // console.log('this.client["connected"]=', this.client['connected'])

      this.client.on('connect', () => {
        // 关闭订阅按钮读取状态
        this.isSubscribe = false
        // 设置连接状态为 true
        this.clientConnected = true
        // 发送消息
        this.publish(this.startTopic)
        // 监听消息
        this.client.subscribe([this.startTopic, '/V2.0.0/detection/process', '/V2.0.0/detection/complete/item', '/V2.0.0/detection/complete/message'])
        this.client.on('message', (topic, payload) => {
          // 接收所有消息
          // console.log(`Received message ${payload.toString()} on topic ${topic}`)

          // 更新接受到的消息到 message
          this.message.push(JSON.parse(payload.toString()))

          // 按订阅主题分别接收mqtt消息
          switch (topic) {
            // 检测开始
            case '/V2.0.0/detection/start':
              // 发生检测请求

              break
            case '/V2.0.0/detection/start/response':
              // 无线组网平台应答

              break

            // 检测过程中
            case '/V2.0.0/detection/process':
              // 无线组网平台发送的mqtt消息

              this.processData.push(JSON.parse(payload.toString()))
              break

            // 检测完成后
            case '/V2.0.0/detection/complete/item':
              // 无线组网平台发送的全部检查项结果的mqtt消息

              this.itemData.push(JSON.parse(payload.toString()))
              break
            case '/V2.0.0/detection/complete/message':
              // 无线组网平台发送的全部检查项所有的日志信息

              this.messageData.push(JSON.parse(payload.toString()))
              break

            default:
              break
          }
        })
      })
    },
    // 发送MQTT消息
    publish(publishTopic) {
      if (this.clientConnected) {
        // 生成随机task_id
        const min = 10000
        const max = 99999
        const randomNum = Math.floor(Math.random() * (max - min) + min)
        const taskId = parseInt(new Date().getTime() / 1000).toString() + randomNum.toString()

        const msg = {
          'task_id': parseInt(taskId),
          'task_name': '微功耗测试',
          'eid_list': [{
            'equip_type': 0,
            'eid': '22c608001234',
            'fre_point': 4,
            'business_cycle': 20000
          }]
        }

        this.client.publish(
          publishTopic,
          JSON.stringify(msg)
        )
      } else {
        alert('Please connect to MQTT broker first.')
      }
    },
    // 获取步骤执行状态 动态显示效果 同 controlRefresh
    UpdateDeviceStatus() {
      // console.log('refreshAll started')
    },
    delClick() {
      // console.log('this.message=', this.message)
      // console.log('this.processData=', this.processData)
      // console.log('this.itemData=', this.itemData)
      // console.log('this.messageData=', this.messageData)
    }
  }
}

</script>
