<template>
  <view class="content">
    <view class="header">
      <u-search placeholder="请输入设备名称" :clearabled="true" @clear="searchDevice" @custom="searchDevice" v-model="search.deviceName" @search="searchDevice"></u-search>
    </view>
    <view class="text-area">
      <u-grid
          :border="true"
          col="3"
      >
        <u-grid-item @click="goDeviceDetail(listItem)"
            v-for="(listItem,listIndex) in deviceList"
            :key="listIndex"
        >
          <u--image  :showLoading="true" src="/static/images/device/device.png" width="50px" height="50px"></u--image>

          <text class="grid-text" style="text-align: center;font-size: 24rpx">{{ listItem.deviceName }}
          </text>
          <text>
            {{listItem.serialNumber}}

          </text>
          <view style="margin:20rpx 0px">
            <u-tag v-if="listItem.status === 4" text="离线"  size="mini" type="info"></u-tag>
            <u-tag v-if="listItem.status === 3" text="在线"  size="mini" type="success"></u-tag>
            <u-tag v-if="listItem.status === 2" text="禁用"  size="mini" type="error"></u-tag>
            <u-tag v-if="listItem.status === 1" text="未激活"  size="mini" type="error"></u-tag>
          </view>

        </u-grid-item>
      </u-grid>

    </view>
    <u-picker @cancel="show=false" :show="show" :columns="columns" @confirm="chooseGroup" keyName="label"></u-picker>
  </view>
</template>

<script>
import { listDeviceGroup,listDevice } from '@/api/device/device.js'
export default {
  data(){
      return {
        value:"",
        show:false,
        groupName:"",
        columns: [
        ],
        deviceList:[],
        page:1,
        search:{
          deviceName:""
        }

      }
  },
  onLoad: function() {
    this.connectMqtt();
  },
  destroyed() {
    // 取消订阅主题
    this.mqttUnSubscribe(this.deviceList);
  },
  methods:{
    goDeviceDetail(item){
      uni.navigateTo({
        url: '/pages/device/detail?id='+item.deviceId
      });
    },
    searchDevice(){
      console.log(this.search.deviceName)
        this.mqttUnSubscribe(this.deviceList);
        this.listDevice();
    },
    listDevice(){
      let self = this;
      listDevice(this.page,this.search.deviceName).then(res=>{
            let rows = res.rows;
            self.deviceList = rows;
            self.mqttSubscribe(self.deviceList);
      })
    },
    listDeviceGroup(){
      let self = this;
      let id = this.$store.state.user.id;
      listDeviceGroup(id).then(res=>{
        self.columns = [];
        let groups = [];
        let rows = res.rows;
        for (let i = 0; i < rows.length; i++) {
          let row = rows[i];
          let id = row.groupId;
          let name = row.groupName;
          groups.push({
            label:name,
            id:id
          })
        }
        self.columns.push(groups) ;
      });

    },
    chooseGroup(e){
      let data = e.value[0];
      console.log(data.id+","+data.label);
      this.groupName = data.label;
      this.show = false
    },
    /* 连接Mqtt消息服务器 */
    async connectMqtt() {
      if (this.$mqttTool.client == null) {
        await this.$mqttTool.connect();
      }
      this.mqttCallback();
      this.listDevice();
    },
    /* Mqtt回调处理  */
    mqttCallback() {
      this.$mqttTool.client.on('message', (topic, message, buffer) => {
        let topics = topic.split('/');
        let productId = topics[1];
        let deviceNum = topics[2];
        message = JSON.parse(message.toString());
        if (topics[3] == 'status') {
          console.log('接收到【设备状态】主题：', topic);
          console.log('接收到【设备状态】内容：', message);
          // 更新列表中设备的状态
          for (let i = 0; i < this.deviceList.length; i++) {
            if (this.deviceList[i].serialNumber == deviceNum) {
              this.deviceList[i].status = message.status;
              this.deviceList[i].isShadow = message.isShadow;
              this.deviceList[i].rssi = message.rssi;
              return;
            }
          }
        }
        if (topics[3] == "monitor") {
          console.log('接收到【设备状态】主题：', topic);
          console.log('接收到【设备状态】内容：', message);
          // 实时监测
          this.chartLoading = false;
          for (let k = 0; k < message.length; k++) {
            let value = message[k].value;
            let id = message[k].id;
            let remark = message[k].remark;
            // 数据加载到图表
            for (let i = 0; i < this.dataList.length; i++) {
              if (id == this.dataList[i].id) {
                if (this.dataList[i].length > 50) {
                  this.dataList[i].shift();
                }
                this.dataList[i].data.push([this.getTime(), value]);
                // 更新图表
                this.chart[i].setOption({
                  series: [{
                    data: this.dataList[i].data
                  }]
                });
                break;
              }
            }
          }
        }
        if (topics[3] == 'property' || topics[3] == 'function') {
          console.log('接收到【物模型】主题：', topic);
          console.log('接收到【物模型】内容：', message);
          // 更新列表中设备的属性
          for (let i = 0; i < this.deviceList.length; i++) {
            if (this.deviceList[i].serialNumber == deviceNum) {
              for (let j = 0; j < message.length; j++) {
                let isComplete = false;
                // 布尔类型
                for (let k = 0; k < this.deviceList[i].boolList.length && !isComplete; k++) {
                  if (this.deviceList[i].boolList[k].id == message[j].id) {
                    this.deviceList[i].boolList[k].shadow = message[j].value;
                    isComplete = true;
                    break;
                  }
                }
                // 枚举类型
                for (let k = 0; k < this.deviceList[i].enumList.length && !isComplete; k++) {
                  if (this.deviceList[i].enumList[k].id == message[j].id) {
                    this.deviceList[i].enumList[k].shadow = message[j].value;
                    isComplete = true;
                    break;
                  }
                }
                // 字符串类型
                for (let k = 0; k < this.deviceList[i].stringList.length && !isComplete; k++) {
                  if (this.deviceList[i].stringList[k].id == message[j].id) {
                    this.deviceList[i].stringList[k].shadow = message[j].value;
                    isComplete = true;
                    break;
                  }
                }
                // 数组类型
                for (let k = 0; k < this.deviceList[i].arrayList.length && !isComplete; k++) {
                  if (this.deviceList[i].arrayList[k].id == message[j].id) {
                    this.deviceList[i].arrayList[k].shadow = message[j].value;
                    isComplete = true;
                    break;
                  }
                }
                // 整数类型
                for (let k = 0; k < this.deviceList[i].integerList.length && !isComplete; k++) {
                  if (this.deviceList[i].integerList[k].id == message[j].id) {
                    this.deviceList[i].integerList[k].shadow = message[j].value;
                    isComplete = true;
                    break;
                  }
                }
                // 小数类型
                for (let k = 0; k < this.deviceList[i].decimalList.length && !isComplete; k++) {
                  if (this.deviceList[i].decimalList[k].id == message[j].id) {
                    this.deviceList[i].decimalList[k].shadow = message[j].value;
                    isComplete = true;
                    break;
                  }
                }
                // 监测数据
                for (let k = 0; k < this.deviceList[i].readOnlyList.length && !isComplete; k++) {
                  if (this.deviceList[i].readOnlyList[k].id == message[j].id) {
                    this.deviceList[i].readOnlyList[k].shadow = message[j].value;
                    isComplete = true;
                    break;
                  }
                }
              }
              return;
            }
          }
        }
      });
    },
    /* 订阅消息 */
    mqttSubscribe(list) {
      // 订阅当前页面设备状态和实时监测
      let topics = [];
      for (let i = 0; i < list.length; i++) {
        let topicStatus = '/' + list[i].productId + '/' + list[i].serialNumber + '/status/post';
        let topicMonitor = "/" + list[i].productId + "/" + list[i].serialNumber + "/monitor/post";
        let topicProperty = '/' + list[i].productId + '/' + list[i].serialNumber + '/property/post';
        let topicFunction = '/' + list[i].productId + '/' + list[i].serialNumber + '/function/post';
        topics.push(topicStatus);
        topics.push(topicMonitor);
        topics.push(topicProperty);
        topics.push(topicFunction);
      }
      this.$mqttTool.subscribe(topics);
    },
    mqttUnSubscribe(list){
      let topics = [];
      for (let i = 0; i < list.length; i++) {
        let topicStatus = '/' + list[i].productId + '/' + list[i].serialNumber + '/status/post';
        let topicMonitor = "/" + list[i].productId + "/" + list[i].serialNumber + "/monitor/post";
        let topicProperty = '/' + list[i].productId + '/' + list[i].serialNumber + '/property/post';
        let topicFunction = '/' + list[i].productId + '/' + list[i].serialNumber + '/function/post';
        topics.push(topicStatus);
        topics.push(topicMonitor);
        topics.push(topicProperty);
        topics.push(topicFunction);
      }
      console.log('取消订阅', topics);
      this.$mqttTool.unsubscribe(topics);
    }

  }
}
</script>

<style>
.header{
  height: 100rpx;
  width: 100%;
  background: white;
  padding:0px 20rpx

}
.content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.logo {
  height: 200rpx;
  width: 200rpx;
  margin-top: 200rpx;
  margin-left: auto;
  margin-right: auto;
  margin-bottom: 50rpx;
}

.text-area {
  margin:10px;
  padding-bottom: 10px;
  justify-content: center;
  width: 100%;
}
.grid-text {

  font-size: 14px;
  color: #909399;
  padding: 10rpx 0 20rpx 0rpx;
  /* #ifndef APP-PLUS */
  box-sizing: border-box;
  /* #endif */
}
.title {
  font-size: 36rpx;
  color: #8f8f94;
}
</style>
