<template>
  <div class="home">
    <headComponent></headComponent>
    <notice v-if="noticeShowType" :noticeProps="noticeProps"></notice>
    <div class="home-page" v-if="!noticeShowType">
      <div class="home-left-box">
        <left-top></left-top>
        <left-bottom></left-bottom>
      </div>
      <div class="home-center-box">
        <center-top></center-top>
        <center-center></center-center>
        <div style="display: flex;">
          <center-bottom-left></center-bottom-left>
          <center-bottom-right></center-bottom-right>
        </div>
      </div>
      <div class="home-right-box">
        <right></right>
      </div>
    </div>
    <baseComponent></baseComponent>
    <alarmComponent v-if="alarmType" :alarmData="alarmData"></alarmComponent>
  </div>
</template>
<script>
  import mqtt from 'mqtt'
  import {
    laboratoryBigViewSelectTriggerInfo,
    iotSensorFindBySubId,
    iotCameraFindByCondition
  } from "@/api/index";
  import { dashboardsResearchUsage,dashboardsNotice } from "@/api/yiLi";
  import { getFloorMaps } from '@/utils/mapList'
  //head组件
  import headComponent from './components/headComponent.vue'
  import baseComponent from './components/baseComponent.vue'
  import leftTop from './components/left-top.vue'
  import leftBottom from './components/left-bottom.vue'
  import centerTop from './components/center-top.vue'
  import centerCenter from './components/center-center.vue'
  import centerBottomLeft from './components/center-bottom-left.vue'
  import centerBottomRight from './components/center-bottom-right.vue'
  import right from './components/right.vue'
  import notice from './components/notice.vue'
  //报警弹窗
  import alarmComponent from './components/subcomponent/alarmComponent.vue'

  export default {
    name: 'home',
    components: {
      headComponent,
      baseComponent,
      leftTop,
      leftBottom,
      centerTop,
      centerCenter,
      centerBottomLeft,
      centerBottomRight,
      right,
      notice,
      alarmComponent
    },
    data () {
      return {
        //预案MQTT
        planOpic:'lab/risk/plan/change',
        planClient:{},
        roomList:[],
        alarmType:false,
        alarmData:null,
        //预案查询定时器
        alarmTimer:null,
        //预案查询定时
        alarmSwitchTime:60000,
        //通知查询定时器
        noticeTimer:null,
        //通知查询定时
        noticeSwitchTime:600000,
        noticeShowType:false,
        //通知数据
        noticeProps:{},
      }
    },
    created(){

    },
    mounted(){
      this.offPlanMQTT('on');
      this.laboratoryBigViewSelectTriggerInfo();
      //开启预案定时查询
      this.alarmTimerFunction();
      //开启定时通知查询
      this.getDataTimerFunction();
    },
    methods:{
      getDataTimerFunction(){
        clearInterval(this.noticeTimer)
        this.dashboardsNotice();
        this.noticeTimer = window.setInterval(() => {
          if(this.noticeShowType){
            this.$set(this,'noticeShowType',false);
          }else{
            this.dashboardsNotice();
          }
        }, this.noticeSwitchTime);
      },
      //定时获取通知
      dashboardsNotice(){
        dashboardsNotice().then(res => {
          if(res.data){
            this.$set(this,'noticeProps',res.data[0]);
            this.$set(this,'noticeShowType',true);
          }
        })
      },
      /*************** 获取报警相关 ***************/
      laboratoryBigViewSelectTriggerInfo(){
        laboratoryBigViewSelectTriggerInfo().then(res => {
          let alarmRoom = getFloorMaps(res.data);
          if(alarmRoom[0]){
            this.dashboardsResearchUsage(alarmRoom);
          }else{
            this.$set(this,'alarmType',false);
            this.$set(this,'alarmData',null);
          }
        })
      },
      //获取房间数据
      dashboardsResearchUsage(list){
        dashboardsResearchUsage('roomNames='+list[0].roomNumName).then(res => {
          let obj = list[0];
          obj.list = JSON.parse(JSON.stringify(list));
          if(res.data[0]){
            obj = {...obj,...res.data[0]};
            obj.status = obj.runningStateName == '维修' ? '3':(obj.stateName == '租用'?'2':'1')
            if(obj.userName){
              if(obj.userName('-') != -1) {
                obj.userName = obj.userName.split('-')[0]
              }
            }
            if(obj.headName){
              if(obj.headName('-') != -1) {
                obj.headName = obj.headName.split('-')[0]
              }
            }
            //假数据
            // obj.monitorVisable = true;
            // obj.subId = '1955554621449019392';
            this.iotSensorFindBySubId(obj);
          }
        });
      },
      //查询传感器
      iotSensorFindBySubId(obj){
        let self = this;
        iotSensorFindBySubId({subId:obj.subId}).then(response => {
          obj.sensor = [];
          for(let i=0;i<obj.alarmData.triggerUploadData.length;i++){
            for(let o=0;o<response.data.length;o++){
              if(obj.alarmData.triggerUploadData[i].deviceNo == response.data[o].deviceNo){
                response.data[i].icon = response.data[i].icon?localStorage.getItem('fileBrowseEnvironment')+response.data[i].icon:null;
                // response.data[i].icon = 'http://192.168.1.8/statics/2025/08/25/9eec5108-2702-4ed0-942a-aced71fd1f57.svg';
                obj.sensor.push(response.data[i])
              }
            }
          }
          obj.videoList = [];
          //查询实验室监控
          if(obj.monitorVisable){
            let videoObj = {
              page:'1',
              pageSize:'10',
              buildId:'',
              floorId:'',
              passageway:'',
              subIds:[obj.subId],
              protocol:window.location.href.indexOf('https') !== -1?'wss':'ws',
              streamType:1,
              source:1,
            };
            iotCameraFindByCondition(videoObj).then(response => {
              for(let i=0;i<response.data.records.length;i++){
                obj.videoList.push(
                  {
                    fullShow:true,
                    width: 708, //(宽度:非必传-默认600)
                    height: 450, //(高度:非必传-默认338)
                    url: response.data.records[i].streamUrl,
                    cameraIndexCode: response.data.records[i].deviceNo,
                  }
                )
              }
              self.$set(self,'alarmType',true);
              self.$set(self,'alarmData',obj);
            });
          }else{
            self.$set(self,'alarmType',true);
            self.$set(self,'alarmData',obj);
          }
        });
      },
      //预案查询定时器
      alarmTimerFunction(){
        const self = this;
        self.alarmTimer = window.setInterval(() => {
          checkAlarmUpdates();
        }, this.alarmSwitchTime);
        async function checkAlarmUpdates() {
          self.laboratoryBigViewSelectTriggerInfo();
        }
      },
      //预案-MQTT连接
      offPlanMQTT(type){
        let self = this;
        if(self.planClient.unsubscribe){
          self.planClient.unsubscribe(self.planOpic, error => {
            if (error) {
              // console.log('mqtt关闭连接错误:', error)
            }
          })
          self.planClient.end();
          this.$set(this,'planClient',{});
        }
        //判断传入参数如果存在 发起一次新的连接
        if(type){
          this.planMQTT();
        }
      },
      //预案-MQTT订阅
      planMQTT(){
        let self = this;
        this.planClient = mqtt.connect(localStorage.getItem('mqttUrl'), {
          username: localStorage.getItem('mqttUser'),
          password:localStorage.getItem('mqttPassword')
        });
        this.planClient.on("connect", e =>{
          this.planClient.subscribe(self.planOpic, (err) => {
            if (!err) {
              console.log("预案-订阅成功:" + self.planOpic);
            }else{
              // console.log("预案-连接错误:" + err);
            }
          });
        });
        this.planClient.on("message", (topic, message) => {
          if (message){
            console.log('MQTTmessage',message);
            //获取预案数据
            this.laboratoryBigViewSelectTriggerInfo();
          }
        });
      },
    },
    beforeDestroy() {
      clearInterval(this.alarmTimer);
      clearInterval(this.noticeTimer)
      //清除MQTT
      this.offPlanMQTT();
    },
    destroyed() {
      clearInterval(this.alarmTimer);
      clearInterval(this.noticeTimer)
      //清除MQTT
      this.offPlanMQTT();
    }
  }
</script>
<style scoped lang="scss">
  .home{
    /*width: 3072px;*/
    /*height: 1660px;*/
    /*分辨率调整*/
    width: 3840px;
    height: 2160px;
    flex:1;
    display: flex;
    flex-direction: column;
    position: relative;
    background-color: #020B15;
    background-image: url("../assets/ZDimages/dbg@1x.png");
    background-size: 100% 100%;
    .home-page{
      flex:1;
      overflow: hidden;
      display: flex;
      .home-left-box{
        display: flex;
        flex-direction: column;
        overflow: hidden;
        width: 950px;
        margin:0 0 0 46px;
        /*background-color: #8a6d3b;*/
      }
      .home-center-box{
        display: flex;
        flex-direction: column;
        overflow: hidden;
        width: 1757px;
        margin:0 46px;
        padding-top:18px;
        /*background-color: #13ce66;*/
      }
      .home-right-box{
        display: flex;
        flex-direction: column;
        overflow: hidden;
        width: 950px;
        margin:0 46px 0 0;
        /*background-color: #2f54eb;*/
      }
    }
  }
</style>
