<template>
  <view class="content">
    <view class="header" style="padding:0 20rpx">
      <u-search placeholder="请输入设备名称" :showAction="false" :clearabled="true" @clear="searchDevice" @custom="searchDevice" v-model="search.deviceName" @search="searchDevice"></u-search>
    </view>
    <view class="text-area">
    <view v-for="(item,listIndex) in deviceList" @click="goDeviceDetail(item)">
      <uni-card>
        <template v-slot:cover>
          <view style="position: relative;display: flex;flex-direction: row;height: 100rpx">
            <view style="width: 60rpx;height: 40rpx;position: absolute;top: 32rpx;">
              <u-image :showLoading="true" src="/static/images/device/device.png" width="80rpx" height="80rpx" ></u-image>
            </view>
            <view style="position: absolute;top: 32rpx;left: 100rpx;display: flex;flex-direction: column;color: #545454;">
              <view style="font-size: 24rpx;font-weight:600;margin-bottom:16rpx">
                {{ item.deviceName }}
              </view>
              <view style="font-size: 20rpx;">
                {{item.serialNumber}}

              </view>

            </view>
            <view style="position: absolute;right:20rpx;top:24rpx;display: flex;flex-direction: column;">
              <view v-if="item.status == 3">
                <u-image :showLoading="true" src="/static/images/device/online.png" width="60rpx" height="60rpx" ></u-image>
                <view style="color:#48C373;font-size: 20rpx;text-align: center">在线</view>
              </view>

              <view v-if="item.status == 4">
                <u-image :showLoading="true" src="/static/images/device/outline.png" width="60rpx" height="60rpx" ></u-image>
                <view style="color:#CECDCD;font-size: 20rpx;text-align: center">离线</view>
              </view>

              <view v-if="item.status == 2">
                <u-image :showLoading="true" src="/static/images/device/outline.png" width="60rpx" height="60rpx" ></u-image>
                <view style="color:#CECDCD;font-size: 20rpx;text-align: center">禁用</view>
              </view>

              <view v-if="item.status == 1">
                <u-image :showLoading="true" src="/static/images/device/outline.png" width="60rpx" height="60rpx" ></u-image>
                <view style="color:#CECDCD;font-size: 20rpx;text-align: center">未激活</view>
              </view>
            </view>
          </view>
        </template>
      </uni-card>
    </view>
    </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:""
        },
        deptId:0,

      }
  },
  onLoad: function(opt) {
    this.deptId = opt.deptId;
    this.connectMqtt();
  },
  destroyed() {
    // 取消订阅主题
    this.mqttUnSubscribe(this.deviceList);
    clearInterval(this.checkTimer);
  },
  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,this.deptId).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();
      this.startCheck();
    },
    /* 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);
    },
    startCheck(){
      let self = this;
      this.checkTimer = setInterval(function (){
        self.sendHeart();
      },20000);
    },
    checkActive(){
      let self = this;
      setTimeout(function (){
        if(self.publishMsg){
          self.resetConn()
        }
      },3000);
    },
    sendHeart(){
      console.log("发送心跳")
      let device = this.deviceInfo;
      let self = this;
      let topic = "/property-offline/post";
      self.publishMsg = true;
      self.checkActive();
      this.$mqttTool.publish(topic, "ok", "heart").then(res => {
        self.publishMsg = false;
      }).catch(res => {
        self.publishMsg = false;
      });
    },
    resetConn(){
      console.log("检测异常，重连")
      this.$mqttTool.end();
      this.$mqttTool.client = null;
      this.connectMqtt();
      this.getDetail();
    }

  }
}
</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>
