<!--传感器模块-->
<template>
  <div class="indexRightPage-sensorPage scrollbar-box">
    <img class="null-img" src="@/assets/ZDimages/basicsModules/null-data-1.png" v-if="!sensorList[0]">
    <div class="for-sensor-max-big-box scrollbar-box">
      <div class="for-sensor-big-box" :class="item.type?'for-sensor-box-yc':(item.online?'onLineColor':'offLineColor')"
           v-for="(item,index) in sensorList" :key="index">
        <div class="for-sensor-box">
          <div class="for-sensor-img-box">
            <svg-icon v-if="item.icon" class="svg-img" :icon-class="item.icon"/>
          </div>
          <div class="for-sensor-text-box">
            <el-tooltip class="item" effect="dark" :content="item.deviceName" placement="bottom">
              <p>{{item.deviceName}}</p>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" :content="item.deviceValue?item.deviceValue+item.unit:'--'" placement="bottom">
              <p>{{item.deviceValue?item.deviceValue+item.unit:'--'}}</p>
            </el-tooltip>
          </div>
        </div>
      </div>
    </div>
    <p class="bottom-time-p" v-if="lastOnlineTime">数据上报时间：{{parseTime(lastOnlineTime)}}</p>
  </div>
</template>

<script>
  import { mapState } from 'vuex'
  import mqtt from 'mqtt'
  import {
    iotSensorFindBySubId
  } from '@/api/commonality/permission'
  export default {
    name: 'sensorPage',
    computed: {
      ...mapState(['plan']) // 获取整个对象
    },
    watch: {
      plan: {
        handler(newValue, oldValue) {
          this.$set(this,'planSensorList',newValue.planSensorList);
          this.$nextTick(()=>{
            this.iotSensorFindBySubId();
          })
        },
        deep: true
      }
    },
    data(){
      return{
        //MQTT请求参数-传感器
        mtOpic:"iot/device/sensor/sub/",
        client:{},
        sensorList:[],
        lastOnlineTime:'',
        planSensorList:[],
      }
    },

    created(){

    },
    mounted(){

    },
    methods:{
      initialize(){
        this.$set(this,'planSensorList',this.$store.state.plan.planSensorList);
        this.$nextTick(()=>{
          this.iotSensorFindBySubId();
          this.offMQTT('on');
        })
      },
      //查询传感器数据
      iotSensorFindBySubId(){
        let self = this;
        iotSensorFindBySubId({subId:this.$parent.subId}).then(response => {
          response.data.forEach((item)=>{
            let num = 0;
            self.planSensorList.forEach((minItem)=>{
              if(item.deviceNo == minItem){
                num++
              }
            })
            item.type = num != 0;
            item.icon = item.icon?localStorage.getItem('fileBrowseEnvironment')+item.icon:null;
          })
          this.$set(this,'sensorList',response.data);
        })
      },
      //MQTT订阅
      sensorMQTT(){
        let self = this;
        this.client = mqtt.connect(localStorage.getItem('mqttUrl'), {
          username: localStorage.getItem('mqttUser'),
          password:localStorage.getItem('mqttPassword')
        });
        this.client.on("connect", e =>{
          this.client.subscribe(this.mtOpic+self.$parent.subId, (err) => {
            if (!err) {
              // console.log("订阅成功:" + this.mtOpic+self.$parent.subId);
            }else{
              // console.log("连接错误:" + err);
            }
          });
        });
        this.client.on("message", (topic, message) => {
          if (message){
            let data = JSON.parse(message)
            let list = JSON.parse(JSON.stringify(this.sensorList))
            list.forEach((item)=>{
              data.forEach((minItem)=>{
                if(item.deviceNo == minItem.deviceNo){
                  item.deviceValue = minItem.deviceValue;
                  item.online = minItem.online;
                }
              })
            })
            if(data[0].lastOnlineTime){
              this.$set(this,'lastOnlineTime',data[0].lastOnlineTime);
            }else{
              this.$set(this,'lastOnlineTime','');
            }
            this.$set(this,'sensorList',list);
          }
        });
      },
      //取消订阅关闭MQTT连接
      offMQTT(type){
        let self = this;
        if(self.client.unsubscribe){
          self.client.unsubscribe(self.mtOpic+self.$parent.subId, error => {
            if (error) {
              // console.log('mqtt关闭连接错误:', error)
            }
          })
          self.client.end();
          this.$set(this,'client',{});
        }
        //判断传入参数如果存在 发起一次新的连接
        if(type){
          this.sensorMQTT();
        }
      },
    },
    beforeDestroy() {
      //清除定时器
      let self = this;
      self.offMQTT();
    },
  }
</script>

<style scoped lang="scss">
  .indexRightPage-sensorPage{
    flex:1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    .null-img{
      display: block;
      margin:80px 0 0 150px;
      width:150px;
    }
    .for-sensor-max-big-box{
      flex:1;
      .for-sensor-big-box{
        display: inline-block;
        overflow: hidden;
        width: 180px;
        height: 60px;
        margin: 0 0 11px 16px;
        border-radius: 10px;
        .for-sensor-box{
          display: flex;
          .for-sensor-img-box{
            .svg-img{
              width: 26px;
              height: 26px;
              margin: 17px 11px;
              color:#fff;
            }
          }
          .for-sensor-text-box{
            flex:1;
            overflow: hidden;
            margin:9px 0;
            p{
              overflow: hidden;
              display:block;
              text-overflow:ellipsis;
              white-space:nowrap;
              margin-right:10px;
            }
            p:nth-child(1){
              font-size: 14px;
              line-height: 20px;
            }
            p:nth-child(2){
              font-size: 16px;
              line-height: 22px;
            }
          }
        }
      }
      .for-sensor-box-yc{
        color:#fff;
        background-color: #FFAEAE!important;
      }
      .offLineColor{
        color:#fff;
        background-color: #E0E0E0;
      }
      .onLineColor{
        color:#fff;
        background-color: #80D164;
      }
    }
    .bottom-time-p{
      font-size:14px;
      color:#999;
      text-align: center;
      height:40px;
      line-height:40px;
    }
  }
</style>
