<!-- 我的实验室 -->
<template>
  <view id="laboratoryInfo">
    <view class="name-max-box">
      <view class="title-box">
        <view :style="'border:1rpx solid '+itemData.fiedColor+';background:#fff;color:'+itemData.fiedColor+';'">{{itemData.levelName}}</view>
        <view>{{itemData.name}}</view>
      </view>
      <view class="address-box"><span>{{itemData.typeName}}</span>{{itemData.deptName}}</view>
      <view class="address-box-two">
        <img src="@/images/icon_14.png">
        <view>{{itemData.subAddrrStr}}</view>
      </view>
    </view>
    <view class="sensor-max-box" v-if="itemData.sensorFunctionList[0]&&!saoCodeType">
      <view class="title-max-box">
        <view class="left-view"></view>
        <view class="right-view">传感器</view>
      </view>
      <view class="text-box">
        <view class="min-box" v-for="(minItem,index2) in itemData.sensorFunctionList" :key="index2">
          <view class="min-min-box">
            <img v-show="minItem.hasWarn" src="@/images/icon_15.png">
            <view :class="{'colorA':minItem.hasWarn}">{{minItem.describe}}：{{minItem.formatVal?minItem.formatVal:'-'}}</view>
          </view>
        </view>
      </view>
    </view>
    <view class="control-max-box" v-if="!saoCodeType">
      <view class="title-max-box">
        <view class="left-view"></view>
        <view class="right-view">智能控制</view>
      </view>
      <view class="button-max-box">
        <view class="button-box" v-if="itemData.videoNum>0">
          <view>视频监控</view>
          <view @click="goVideo()">查看</view>
        </view>
        <view class="button-box">
          <view>语音播报</view>
          <view @click="goWord()">播放文字</view>
        </view>
        <view class="for-button-box" v-for="(minItem,minIndex) in itemData.labHardwareVOList" :key="minIndex" v-if="minItem.hardwareTypeEnum.enumName!='VIDEO_MONITOR' && minItem.hardwareTypeEnum.enumName!='RFID_RECOGNIZER'&& minItem.hardwareTypeEnum.enumName!='AI_TERMINAL'&& minItem.hardwareTypeEnum.enumName!='AI_DOORLOCK'&& minItem.hardwareTypeEnum.enumName!='AI_CABINETLOCK'">
          <view>{{minItem.hardwareName}}</view>
          <img v-if="minItem.state.code=='3'" src="@/images/icon_10.png" @click="hardwareButton(minItem,'close')">
          <img v-if="minItem.state.code=='4'" src="@/images/icon_11.png" @click="hardwareButton(minItem,'open')">
          <view v-if="minItem.state.code=='0'">离线</view>
          <view v-if="minItem.state.code=='2'" style="color:#0183FA;">在线</view>
        </view>
      </view>
    </view>
    <view class="info-max-box">
      <view class="title-max-box" :class="{'title-max-box-none':!infoMaxBoxType}">
        <view class="left-view"></view>
        <view class="right-view">安全信息牌</view>
        <view class="click-view" @click="infoMaxBoxClick">
          <view>{{infoMaxBoxType?'收起':'展开'}}</view>
          <img v-if="infoMaxBoxType" src="@/images/icon_06_1.png">
          <img v-else src="@/images/icon_06.png">
        </view>
      </view>
      <view  v-if="infoMaxBoxType">
        <view class="text-max-box">
          <view class="text-min-box">
            <view>责任单位：</view>
            <view>{{itemData.deptName}}</view>
          </view>
          <view class="text-min-box">
            <view>实验室负责人：</view>
            <view>{{itemData.safeInfo.subAdmin[0]?"":"未设置"}}</view>
          </view>
          <view class="text-min-box" v-for="(item,index) in itemData.safeInfo.subAdmin" :key="index">
            <view style="color:#999;">{{item.name}}</view>
            <view>{{item.phone?item.phone:'未填写'}}</view>
          </view>
          <view class="text-min-box">
            <view>安全负责人：</view>
            <view>{{itemData.safeInfo.safeUser[0]?"":"未设置"}}</view>
          </view>
           <view class="text-min-box" v-for="(item,index) in itemData.safeInfo.safeUser" :key="index">
			  <view style="color:#999;">{{item.name}}</view>
			  <view>{{item.phone?item.phone:'未填写'}}</view>
			</view>
        </view>
        <view class="safety-max-box" v-if="itemData.hazardCategory[0]||itemData.riskMeasure[0]||itemData.outfire[0]">
          <view class="max-for-box" v-if="itemData.hazardCategory[0]">
            <view class="title-box">主要危险类别</view>
            <view class="for-box" v-for="(item,index1) in itemData.hazardCategory" :key="index1">● {{item}}</view>
          </view>
          <view class="max-for-box" v-if="itemData.riskMeasure[0]">
            <view class="title-box">风险防控措施</view>
            <view class="for-box" v-for="(item,index1) in itemData.riskMeasure" :key="index1">● {{item}}</view>
          </view>
          <view class="max-for-box" v-if="itemData.outfire[0]">
            <view class="title-box">灭火要点</view>
            <view class="for-box" v-for="(item,index1) in itemData.outfire" :key="index1">● {{item}}</view>
          </view>
        </view>
        <view class="img-bottom-box" v-if="itemData.safeSigns[0]||itemData.qrCode">
          <view class="title-box">安全警示标识</view>
          <view class="for-box">
            <img class="img-ojb" src="@/images/icon_aqxxp_jzxy.png" v-if="item == 'xiyan'" v-for="(item,index) in itemData.safeSigns" :key="index">
            <img class="img-ojb" src="@/images/icon_aqxxp_jzys.png" v-if="item == 'yinshi'" v-for="(item,index) in itemData.safeSigns" :key="index">
            <img class="img-ojb" src="@/images/icon_aqxxp_dxaq.png" v-if="item == 'anquan'" v-for="(item,index) in itemData.safeSigns" :key="index">
            <img class="img-ojb" src="@/images/icon_aqxxp_gzf.png" v-if="item == 'gongzuofu'" v-for="(item,index) in itemData.safeSigns" :key="index">
            <img class="img-ojb" src="@/images/icon_aqxxp_gbmc.png" v-if="item == 'menchuang'" v-for="(item,index) in itemData.safeSigns" :key="index">
            <img class="img-ojb" src="@/images/icon_aqxxp_gbsd.png" v-if="item == 'shuidian'" v-for="(item,index) in itemData.safeSigns" :key="index">
            <img v-if="itemData.safeInfo.qrCode" class="code-img" :src="itemData.safeInfo.qrCode">
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import $mqtt from '@/utils/mqtt.min.js';
import { config } from '@/api/request/config.js'
import { mySubjectList,subject_class,listDepartments,mangerControl,getDicts,laboratoryInfo } from '@/api/index.js'
export default {
  data() {
    return {
      itemData:{},
      //MQTT请求参数-传感器
      mtopic:"lab/function/data",
      //MQTT请求参数-设备
      mtopicOne:"lab/hardware/data",
      msg:"",
      client:{},
      //安全信息牌
      infoMaxBoxType:false,
      subject:[],
      safetyWarning:[],
      hazardCategory:[],
      riskMeasure:[],
      extinguishingKeyPoints:[],
      deptId:"",
      saoCodeType:false,
    }
  },
  onLoad(option) {
    let self = this;
    if(uni.getStorageSync('saoCodeId')){
      this.saoCodeType = true;
      this.laboratoryInfo();
    }else{
      if(option.q){
        let text = decodeURIComponent(option.q)
        console.log('text',text)
        let codeId = "";
        let newList = text.split("?")[1].split("&")
        let list = newList[0].split("=")[1].split("-")
        codeId = list[0];
        uni.setStorageSync('saoCodeId',codeId)
        this.saoCodeType = true;
        this.laboratoryInfo();
      }else{
        this.deptId = JSON.parse(decodeURIComponent(option.deptId));
        this.itemData = JSON.parse(decodeURIComponent(option.item));
        self.itemData.videoNum = 0;
        self.itemData.hardwareNUM = "";
        for(let i=0;i<self.itemData.labHardwareVOList.length;i++){
          if(self.itemData.labHardwareVOList[i].hardwareTypeEnum.enumName=='VIDEO_MONITOR'){
            self.itemData.hardwareNUM = self.itemData.hardwareNUM+self.itemData.labHardwareVOList[i].hardwareNUM+',';
            self.itemData.videoNum++
          }
        }
        this.itemData.safeUserName = this.itemData.safeInfo.safeUserName
        this.itemData.safePhone = this.itemData.safeInfo.safePhone
        if(this.itemData.safeInfo.hazardCategory){
          this.itemData.hazardCategory = this.itemData.safeInfo.hazardCategory
        }
        if(this.itemData.safeInfo.riskMeasure){
          this.itemData.riskMeasure = this.itemData.safeInfo.riskMeasure
        }
        if(this.itemData.safeInfo.safeSigns){
          this.itemData.safeSigns = this.itemData.safeInfo.safeSigns
        }
        if(this.itemData.safeInfo.outfire){
          this.itemData.outfire = this.itemData.safeInfo.outfire
        }
        if(this.itemData.safeInfo.safeUserNameAdminPhone){
          let list = [];
          let newList = [];
          list = this.itemData.safeInfo.safeUserNameAdminPhone.split(",");
          for(let i=0;i<list.length;i++){
            list[i] = list[i].split("@");
            let obj = {
              name:list[i][0],
              phone:list[i][1]
            }
            newList.push(obj);
          }
          this.itemData.safeInfo.safeUser = newList;
        }
        if(this.itemData.safeInfo.adminNameAndPhone){
          let list = [];
          let newList = [];
          list = this.itemData.safeInfo.adminNameAndPhone.split(",");
          for(let i=0;i<list.length;i++){
            list[i] = list[i].split("@");
            let obj = {
              name:list[i][0],
              phone:list[i][1]
            }
            newList.push(obj);
          }
          this.itemData.safeInfo.subAdmin = newList;
        }
        this.saoCodeType = false;
      }
    }

  },
  onShow(){
    if(!this.saoCodeType){
      // //监听传感器信息
      getApp().watch(this.getMqttSensorData,'mqttSensorData')
      // //监听设备信息
      getApp().watch(this.getMqttDeviceData,'mqttDeviceData')
    }
  },
  methods: {
    //查询详情
    async laboratoryInfo(){
      let self = this;
      let id = uni.getStorageSync('saoCodeId');
      const {data} = await laboratoryInfo(id);
      if(data.code == 200){
        uni.removeStorageSync('saoCodeId')
        this.itemData = data.data[0];
        self.itemData.videoNum = 0;
        self.itemData.hardwareNUM = "";
        this.itemData.safeUserName = this.itemData.safeInfo.safeUserName
        this.itemData.safePhone = this.itemData.safeInfo.safePhone
        if(this.itemData.safeInfo.hazardCategory){
          this.itemData.hazardCategory = this.itemData.safeInfo.hazardCategory
        }
        if(this.itemData.safeInfo.riskMeasure){
          this.itemData.riskMeasure = this.itemData.safeInfo.riskMeasure
        }
        if(this.itemData.safeInfo.safeSigns){
          this.itemData.safeSigns = this.itemData.safeInfo.safeSigns
        }
        if(this.itemData.safeInfo.outfire){
          this.itemData.outfire = this.itemData.safeInfo.outfire
        }
        if(this.itemData.safeInfo.safeUserNameAdminPhone){
          let list = [];
          let newList = [];
          list = this.itemData.safeInfo.safeUserNameAdminPhone.split(",");
          for(let i=0;i<list.length;i++){
            list[i] = list[i].split("@");
            let obj = {
              name:list[i][0],
              phone:list[i][1]
            }
            newList.push(obj);
          }
          this.itemData.safeInfo.safeUser = newList;
        }
        if(this.itemData.safeInfo.adminNameAndPhone){
          let list = [];
          let newList = [];
          list = this.itemData.safeInfo.adminNameAndPhone.split(",");
          for(let i=0;i<list.length;i++){
            list[i] = list[i].split("@");
            let obj = {
              name:list[i][0],
              phone:list[i][1]
            }
            newList.push(obj);
          }
          this.itemData.safeInfo.subAdmin = newList;
        }
        this.infoMaxBoxType = true;
      }
    },
    //监听传感器信息
    getMqttSensorData(val){
      let self = this;
      if(val.subId){
        if(self.itemData.id == val.subId){
          self.$set(self.itemData,'sensorFunctionList',val.functionStatuses);
        }
      }
    },
    //监听设备信息
    getMqttDeviceData(val){
      let self = this;
      // console.log('页面获取的-设备信息',val)
      for(let i=0;i<val.length;i++){
        for(let k=0;k<self.itemData.labHardwareVOList.length;k++){
          if(val[i].num == self.itemData.labHardwareVOList[k].id){
            if(val[i].hardwareOperate == 'CLOSE'){
              self.itemData.labHardwareVOList[k].state.code = 4;
            }else if(val[i].hardwareOperate == 'OPEN'){
              self.itemData.labHardwareVOList[k].state.code = 3;
            }else if(val[i].hardwareOperate == 'OFFLINE'){
              self.itemData.labHardwareVOList[k].state.code = 0;
            }else if(val[i].hardwareOperate == 'ONLINE'){
              self.itemData.labHardwareVOList[k].state.code = 2;
            }
          }
        }
      }
    },
    infoMaxBoxClick(){
      this.infoMaxBoxType = !this.infoMaxBoxType;
    },
    async getSafetyWarning(){
      const {data} = await getDicts('sys_safety_warning');
      if(data.code == 200){
        this.safetyWarning = data.data;
      }
    },
    async getHazardCategory(){
      const {data} = await getDicts('sys_hazard_category');
      if(data.code == 200){
        this.hazardCategory = data.data;
      }
    },
    async getRiskMeasure(){
      const {data} = await getDicts('sys_risk_measure');
      if(data.code == 200){
        this.riskMeasure = data.data;
      }
    },
    async getExtinguishingKeyPoints(){
      const {data} = await getDicts('sys_extinguishing_key_points');
      if(data.code == 200){
        this.extinguishingKeyPoints = data.data;
      }
    },
    //MQTT订阅-传感器
    subscriptionMQTT(){
      let self = this;
      const mqttOptions = {
        keepalive: 30,
        clean: false,//保留会话
        connectTimeout: 5000, // 超时时间
        reconnectPeriod:5000, // 重连间隔
        clientId: 'lab/function/data',
        username: config.username,
        password: config.password,
      }

      const connectUrl = config.mqtt_url;
      this.client = $mqtt.connect('wxs://' + connectUrl, mqttOptions);
      this.client.on('connect', () => {
        // 这是为了给自己发条消息，其它无作用
        this.client.subscribe(this.mtopic, (err) => {
          if (!err) {
            console.log("订阅传感器成功",this.mtopic)
          }
        })
        this.client.subscribe(this.mtopicOne, (err) => {
          if (!err) {
            console.log("订阅设备成功",this.mtopicOne)
          }
        })
      });
      // 自动重连
      this.client.on('reconnect', (msg) => {
        console.log('reconnect', msg)
      });
      // 错误
      this.client.on('error', () => {
        console.log('error')
      });
      // 断开
      this.client.on('end', () => {
        console.log('end')
      });
      // 掉线
      this.client.on('offline', (msg) => {
        console.log('offline',msg)
      });
      // 收到消息
      this.client.on('message', (topic, message) => {
        let data = JSON.parse(message)
        console.log('topic',topic)
        console.log('data',data)
        if(topic == this.mtopic){
          if(data.data.subId){
            if(self.itemData.id == data.data.subId){
              self.$set(self.itemData,'sensorFunctionList',data.data.functionStatuses);
            }
          }
        }else if(topic == this.mtopicOne){
          for(let i=0;i<data.data.length;i++){
            for(let k=0;k<self.itemData.labHardwareVOList.length;k++){
              if(data.data[i].num == self.itemData.labHardwareVOList[k].id){
                if(data.data[i].hardwareOperate == 'CLOSE'){
                  self.itemData.labHardwareVOList[k].state.code = 4;
                }else if(data.data[i].hardwareOperate == 'OPEN'){
                  self.itemData.labHardwareVOList[k].state.code = 3;
                }else if(data.data[i].hardwareOperate == 'OFFLINE'){
                  self.itemData.labHardwareVOList[k].state.code = 0;
                }else if(data.data[i].hardwareOperate == 'ONLINE'){
                  self.itemData.labHardwareVOList[k].state.code = 2;
                }
              }
            }
          }
        }
      })
      // 全局监听是否有关闭mqtt的消息的事件
      uni.$on('closeMqtt',() => {
        this.client.end(true); // 主动断开连接
      })
    },
    //取消订阅关闭MQTT连接
    offMQTT(){
      this.client.unsubscribe(this.mtopic, error => {
        if (error) {
          console.log('Unsubscribe error', error)
        }
      })
      this.client.end();
      this.client = {};
    },
    //设备开关按钮
    hardwareButton(minItem,command){
      let self = this;
      let text = '';
      if(command == 'close'){
        text = '关闭';
      }else if(command == 'open'){
        text = '开启';
      }
      uni.showModal({
        content: '确认要'+text+'吗?',
        cancelColor:"#999",
        confirmColor:"#0183FA",
        success: function (res) {
          if (res.confirm) {
            self.mangerControl(minItem,command);
            console.log('用户点击确定');
          } else if (res.cancel) {
            console.log('用户点击取消');
          }
        }
      });
    },
    //设备开关
    async mangerControl(minItem,command){
      let obj = {
        id:minItem.id,
        command:command,
      };
      const {data} = await mangerControl(obj);
      if(data.code == 200){
        if(command == 'open'){
          minItem.type = 3;
        }else if(command == 'close'){
          minItem.type = 4;
        }
        uni.showToast({
          title: '操作成功',
          icon:"none",
          mask:true,
          duration: 2000
        });
      }
    },
    goVideo(){
		this.itemData.floorId = this.itemData.subAddrr.floorId;
      uni.navigateTo({
        url:'/pages_manage/workbench/laboratory/monitor?item='+encodeURIComponent(JSON.stringify(this.itemData))+'&deptId='+this.deptId
      })
    },
    goWord(){
      uni.navigateTo({
        url:'/pages_manage/workbench/laboratory/word?item='+encodeURIComponent(JSON.stringify(this.itemData))
      })
    },
  },
  onHide(){
    // //删除传感器监听
    getApp().deleteSensorWatch();
    // //删除设备监听
    getApp().deleteDeviceWatch();
    console.log("onHide",this.mtopic);
  },
  beforeDestroy(){
    // //删除传感器监听
    getApp().deleteSensorWatch();
    // //删除设备监听
    getApp().deleteDeviceWatch();
    console.log("beforeDestroy",this.mtopic);
  }
}
</script>

<style lang="stylus" scoped>
#laboratoryInfo{
  height:100%;
  display flex
  flex-direction column
  .name-max-box{
    background #fff
    .title-box{
      margin:20rpx 20rpx 0;
      display flex
      view:nth-child(1){
        height:40rpx;
        line-height:40rpx;
        font-size:20rpx;
        border-radius:10rpx;
        padding:0 20rpx;
        color:#fff;
        margin-right:20rpx;
      }
      view:nth-child(2){
        line-height:42rpx;
        font-size:30rpx;
        color:#0183FA;
        max-width:600rpx;
        flex:1;
      }
      img{
        width:12rpx;
        height:20rpx;
        margin-top:11rpx;
      }
      .colorA{
        background:#aa2315;
      }
      .colorB{
        background:#ff9b09;
      }
      .colorC{
        background:#3ea3e9;
      }
      .colorD{
        background:#3ea34c;
      }

    }
    .address-box{
      margin:20rpx 20rpx;
      font-size:26rpx;
      color:#999999;
      span{
        margin-right:60rpx;
      }
    }
    .address-box-two{
      display flex
      margin:0 20rpx 20rpx 20rpx;
      img{
        width:28rpx;
        height:30rpx;
        margin-right:18rpx;
      }
      view{
        line-height:30rpx;
        font-size:24rpx;
        color:#999999;
      }
    }
  }
  .title-max-box-none{
    border:none!important;
  }
  .title-max-box{
    display flex
    height:80rpx;
    border-bottom:1rpx solid #E0E0E0;
    .left-view{
      width: 4rpx;
      height: 34rpx;
      margin:25rpx 24rpx 0 20rpx;
      background:#0D97EB;
    }
    .right-view{
      line-height:80rpx;
      font-size: 30rpx;
      color: #333333;
      flex:1;
    }
    .click-view{
      display flex
      padding:0 20rpx;
      view{
        line-height:80rpx;
        font-size: 24rpx;
        color: #666666;
      }
      img{
        width:20rpx;
        height:10rpx;
        margin:35rpx 0 0 20rpx;
      }
    }
  }
  .sensor-max-box{
    background #fff
    margin-top:20rpx;
    .text-box{
      /*border-top:1rpx dashed #e0e0e0;*/
      /*border-top:1rpx solid #E0E0E0;*/
      padding:0 20rpx;
      /*
      overflow-x:scroll;
      overflow-y:hidden;
      white-space: nowrap;
      */
      .min-box{
        display inline-block
        /*padding:0 30rpx 0 10rpx;*/
        width:355rpx;
        .min-min-box{
          display: flex
          img{
            width:30rpx;
            height:27rpx;
            margin-top:24rpx;
            margin-right:10rpx;
          }
          view{
            line-height:74rpx;
            text-align center
            font-size:28rpx;
            color:#333;
          }
          .colorA{
            color:#EE3A3A;
          }
        }
      }
    }
  }
  .control-max-box{
    background #fff
    margin-top:20rpx;
    .button-max-box{
      .button-box:last-child{
        border:none!important;
      }
      .button-box{
        display flex
        border-bottom:1rpx solid #e0e0e0;
        margin:0 20rpx;
        view:nth-child(1){
          flex:1;
          line-height:90rpx;
          color:#333333;
          font-size:28rpx;
        }
        view:nth-child(2){
          width:120rpx;
          line-height:42rpx;
          border:4rpx solid #0183FA;
          border-radius:30rpx;
          color: #0183FA;
          font-size: 24rpx;
          text-align center;
          margin:20rpx 0 20rpx 0;
        }
      }
      .for-button-box:last-child{
        border:none!important;
      }
      .for-button-box{
        display flex
        border-bottom:1rpx solid #e0e0e0;
        margin:0 20rpx;
        view{
          flex:1;
          line-height:90rpx;
          color:#333333;
          font-size:28rpx;
        }
        img{
          height:50rpx;
          width:100rpx;
          margin:20rpx 0 20rpx 0;
        }
        view:nth-child(2){
          text-align right
          color:#999;
        }
      }
    }
  }
  .info-max-box{
    background #fff
    margin-top:20rpx;
    .top-name-max-box{
      background #fff
      overflow hidden
      .name-box{
        margin:27rpx 20rpx 0;
        display:flex;
        view:nth-child(1){
          background:#f95f5f;
          color:#fff;
          border-radius:6rpx;
          font-size:20rpx;
          padding:0 10rpx;
          height:42rpx;
          line-height:42rpx;
        }
        view:nth-child(2){
          color:#333;
          margin-left:20rpx;
          font-size:28rpx;
          height:30rpx;
          line-height:42rpx;
          font-weight:700;
        }
      }
      .address-box{
        margin:22rpx 20rpx;
        font-size:26rpx;
      }
    }
    .text-max-box{
      background #fff
      padding:8rpx 20rpx;
      border-bottom:1rpx solid #e0e0e0;
      .text-min-box{
        display:flex;
        view{
          line-height:66rpx;
          height:66rpx;
          font-size:28rpx;
        }
        view:nth-child(1){
          width:220rpx;
          color:#333;
        }
        view:nth-child(2){
          flex:1;
          color:#999;
          text-align:right;
        }
      }
    }
    .safety-max-box{
      background #fff
      padding:8rpx 20rpx;
      .max-for-box{
        .title-box{
          line-height:76rpx;
          font-size:30rpx;
          color:#333;
        }
        .for-box{
          line-height:48rpx;
          font-size:28rpx;
          color:#999;
        }
      }
    }
    .img-bottom-box{
      margin-top:20rpx;
      background #fff
      padding:8rpx 20rpx 20rpx;
      .title-box{
        line-height:76rpx;
        font-size:28rpx;
        color:#333;
      }
      .for-box{
        line-height:48rpx;
        font-size:26rpx;
        color:#999;
        .img-ojb{
          display inline-block
          width:86rpx;
          height:114rpx;
          margin-left:30rpx;
        }
        .code-img{
          width:200rpx;
          height:200rpx;
          margin:20rpx auto 40rpx;
        }
      }
    }
  }
}
</style>
