<!--硬件模块-->
<template>
  <div class="indexRightPage-hardwarePage scrollbar-box">
    <img class="null-img" src="@/assets/ZDimages/basicsModules/null-data-1.png" v-if="!hardwareList[0]">
    <div class="for-hardware-max-big-box scrollbar-box">
      <div class="for-hardware-big-box onLineColor"
           v-if="item.hardwareTypeKey == 'airConditioner'"
           v-for="(item,index) in hardwareList" :key="index">
        <div class="for-hardware-box">
          <div class="for-hardware-text-box" >
            <el-tooltip class="item" effect="dark" :content="item.hardwareName" placement="bottom">
              <p>{{item.hardwareName}}</p>
            </el-tooltip>
          </div>
          <div class="for-hardware-switch-box">
            <div class="for-hardware-text-title">
              <p :class="item.switchType==1?'colorOpen':'colorOff'">{{item.switchType == 1?'开启':(item.switchType == 0?'关闭':'')}}</p>
              <p :class="item.switchType==1?'':'colorText'" v-for="(minItem,minIndex) in infraredControllerData.functionList"
                 :key="minItem.value" v-if="minItem.value == item.functionType">{{minItem.label}}</p>
              <p :class="item.switchType==1?'':'colorText'" v-for="(minItem,minIndex) in infraredControllerData.refrigerationList"
                 :key="minItem.value" v-if="item.functionType == 1&&minItem.value == item.orderType">{{minItem.label}}</p>
              <p :class="item.switchType==1?'':'colorText'" v-for="(minItem,minIndex) in infraredControllerData.heatingList"
                 :key="minItem.value" v-if="item.functionType == 2&&minItem.value == item.orderType">{{minItem.label}}</p>
            </div>
            <div class="for-hardware-button">
              <p @click="dialogOpen(item)">操作</p>
            </div>
          </div>
        </div>
      </div>
      <div class="for-hardware-big-box onLineColor"
           v-if="item.hardwareTypeKey != 'airConditioner'"
           v-for="(item,index) in hardwareList" :key="index">
        <div class="for-hardware-box">
          <div class="for-hardware-text-box" >
            <el-tooltip class="item" effect="dark" :content="item.hardwareName" placement="bottom">
              <p>{{item.hardwareName}}</p>
            </el-tooltip>
          </div>
          <div class="for-hardware-switch-box">
            <div class="for-hardware-switch-title">
              <p v-if="item.operatingState && item.reservedThree">{{item.reservedThree}}</p>
            </div>
            <div class="for-hardware-switch">
              <el-switch
                class="switch"
                @click.native="changeIsNeedCaptcha(item)"
                v-model="item.operatingState"
                :active-value="true"
                :inactive-value="false"
                active-text="开启"
                inactive-text="关闭"
                disabled>
              </el-switch>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!--红外控制器-->
    <el-dialog class="indexRightPage-hardwarePage-dialog" :title='infraredControllerTitle' width="460px" append-to-body
               :visible.sync="infraredControllerType" v-if="infraredControllerType" @close="dialogOff()"
               :close-on-click-modal="false" :close-on-press-escape="false">
      <div class="infraredController-max-big-box">
        <div class="infraredController-switchType-box">
          <p class="switchType-name-p">{{infraredControllerForm.name}}</p>
          <p class="switchType-type-p"
             @click="switchTypeButton"
             :class="infraredControllerForm.switchType == 1 ? '': 'switchType-type-off-p'">{{infraredControllerForm.switchType == 1 ? '开启':'关闭'}}</p>
        </div>
        <div style="overflow: hidden;height:130px;">
          <div class="infraredController-functionType-box" v-if="infraredControllerForm.switchType == 1">
            <p :class="infraredControllerForm.functionType == item.value?'check-button':''"
               @click="functionButton(item.value)"
               v-for="(item,index) in infraredControllerData.functionList"
               :key="index">{{item.label}}</p>
          </div>
          <div class="infraredController-orderType-box" v-if="infraredControllerForm.switchType == 1 && (infraredControllerForm.functionType == 1 || infraredControllerForm.functionType == 2)">
            <p class="order-minus" @click="minusTextButton()">-</p>
            <p class="order-text" v-for="(item,index) in infraredControllerData.refrigerationList" :key="index" v-if="infraredControllerForm.functionType==1&&infraredControllerForm.orderType == item.value">{{item.label}}</p>
            <p class="order-text" v-for="(item,index) in infraredControllerData.heatingList" :key="index" v-if="infraredControllerForm.functionType==2&&infraredControllerForm.orderType == item.value">{{item.label}}</p>
            <p class="order-add" @click="addTextButton()">+</p>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer dialog-footer-box">
        <p class="dialog-footer-button-null"></p>
        <p class="dialog-footer-button-primary" @click="dialogSubmit">确定</p>
        <p class="dialog-footer-button-null"></p>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { controlsRestrictVerify } from '@/utils/index'
  import mqtt from 'mqtt'
  import {
    iotHardwareFindByType,
    iotHardwareOperatingHardware
  } from '@/api/commonality/permission'
  export default {
    name: 'hardwarePage',
    data(){
      return{
        //MQTT请求参数-硬件
        mtOpic:"iot/hardware/all/sub/",
        client:{},
        hardwareList:[],
        //红外控制器相关
        infraredControllerType:false,
        infraredControllerTitle:"",
        infraredControllerForm:{
          name:null,//设备名称
          switchType:null,//0.关 1.开
          functionType:null, //1.制冷 2.制热 3.通风
          orderType:null, //温度指令
          hardwareNo:null, //设备编号
        },
        infraredControllerData:{
          functionList:[
            {label:'制冷',value:'1'},
            {label:'制热',value:'2'},
            {label:'通风',value:'3'},
          ],
          //制冷
          refrigerationList:[
            {label:"18°C",value:18},
            {label:"19°C",value:19},
            {label:"20°C",value:20},
            {label:"21°C",value:21},
            {label:"22°C",value:22},
            {label:"23°C",value:23},
            {label:"24°C",value:24},
            {label:"25°C",value:25},
            {label:"26°C",value:26},
            {label:"27°C",value:27},
            {label:"28°C",value:28},
          ],
          //制热
          heatingList:[
            {label:"22°C",value:22},
            {label:"23°C",value:23},
            {label:"24°C",value:24},
            {label:"25°C",value:25},
            {label:"26°C",value:26},
            {label:"27°C",value:27},
            {label:"28°C",value:28},
            {label:"29°C",value:29},
            {label:"30°C",value:30},
          ],
        }
      }
    },
    created(){

    },
    mounted(){

    },
    methods:{
      initialize(){
        this.iotHardwareFindByType();
        this.offMQTT('on');
      },
      //红外控制器操作相关
      //弹层关闭
      dialogOff(){
        this.$set(this,'infraredControllerType',false);
      },
      //弹层开启
      dialogOpen(item){
        if(!controlsRestrictVerify('subHardwareControl')){
          this.msgError('没有相关操作权限,请联系管理员')
          return
        }
        this.$set(this,'infraredControllerTitle','空调控制');
        this.$set(this,'infraredControllerForm',{
          name:item.hardwareName,
          switchType:parseInt(item.switchType),
          functionType:item.switchType == 0 ? 1 : parseInt(item.functionType),
          orderType:item.switchType == 1 && item.functionType !=3 ? parseInt(item.orderType):18,
          hardwareNo:item.hardwareNo,
        });
        this.$set(this,'infraredControllerType',true);
      },
      dialogSubmit(){
        let text = '';
        if(this.infraredControllerForm.switchType == 1){
          if(this.infraredControllerForm.functionType == 1){
            text = '3-' + this.infraredControllerForm.orderType;
          }else if(this.infraredControllerForm.functionType == 2){
            text = '4-' + this.infraredControllerForm.orderType;
          }else if(this.infraredControllerForm.functionType == 3){
            text = '2';
          }
        }else if(this.infraredControllerForm.switchType == 0){
          text = '0';
        }
        let switchData = {
          hardwareNo:this.infraredControllerForm.hardwareNo,
          command:text
        };
        iotHardwareOperatingHardware(switchData).then(response => {
          if(response.code==200){
            this.msgSuccess("操作成功")
            this.$set(this,'infraredControllerType',false);
          }
        });
      },
      //开关切换
      switchTypeButton(){
        if(!this.infraredControllerForm.switchType){
          if (this.infraredControllerForm.functionType == 1){
            if(this.infraredControllerForm.orderType<18 || this.infraredControllerForm.orderType>28){
              this.$set(this.infraredControllerForm,'orderType',18);
            }
          } else if(this.infraredControllerForm.functionType == 2){
            if(this.infraredControllerForm.orderType<22 || this.infraredControllerForm.orderType>30){
              this.$set(this.infraredControllerForm,'orderType',22);
            }
          }else if(this.infraredControllerForm.functionType == 3){
            this.$set(this.infraredControllerForm,'orderType',18);
          }else{
            this.$set(this.infraredControllerForm,'functionType',1);
            this.$set(this.infraredControllerForm,'orderType',18);
          }
        }
        this.$set(this.infraredControllerForm,'switchType',!this.infraredControllerForm.switchType);
      },
      //状态切换
      functionButton(value){
        if(this.infraredControllerForm.functionType != value){
          if (value == 1){
            if(this.infraredControllerForm.orderType<18 || this.infraredControllerForm.orderType>28){
              this.$set(this.infraredControllerForm,'orderType',18);
            }
          } else if(value == 2){
            if(this.infraredControllerForm.orderType<22 || this.infraredControllerForm.orderType>30){
              this.$set(this.infraredControllerForm,'orderType',22);
            }
          }
          this.$set(this.infraredControllerForm,'functionType',value);
        }
      },
      //指令切换
      minusTextButton(){
        if (this.infraredControllerForm.functionType == 1){
          if(this.infraredControllerForm.orderType>18){
            this.infraredControllerForm.orderType--
          }
        } else if(this.infraredControllerForm.functionType == 2){
          if(this.infraredControllerForm.orderType>22){
            this.infraredControllerForm.orderType--
          }
        }
      },
      addTextButton(){
        if (this.infraredControllerForm.functionType == 1){
          if(this.infraredControllerForm.orderType<28){
            this.infraredControllerForm.orderType++
          }
        } else if(this.infraredControllerForm.functionType == 2){
          if(this.infraredControllerForm.orderType<30){
            this.infraredControllerForm.orderType++
          }
        }
      },
      //查询硬件数据
      iotHardwareFindByType(){
        iotHardwareFindByType({subjectId:this.$parent.subId}).then(response => {
          response.data.forEach((item)=>{
            if(item.hardwareTypeKey == 'airConditioner'){
              if(item.reservedThree == 0){
                item.switchType = 0;
              }else if(item.reservedThree == 2){
                item.switchType = 1;
                item.functionType = 3;
              }else if(item.reservedThree.indexOf('-') != -1){
                let list = item.reservedThree.split('-');
                item.switchType = 1;
                item.functionType = list[0]==3?1:(list[0]==4?2:'');
                item.orderType = list[1]?list[1]:'';
              }else{
                item.switchType = '';
                item.functionType = '';
                item.orderType = '';
              }
            }
          })
          this.$set(this,'hardwareList',response.data);
        })
      },
      // 开启关闭验证
      async changeIsNeedCaptcha (row) {
        let self = this;
        if(!controlsRestrictVerify('subHardwareControl')){
          this.msgError('没有相关操作权限,请联系管理员')
          return
        }
        let text = row.operatingState?'关闭':'开启';
        this.$confirm(`是否`+text+`此设备`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(async () => {
          self.switchChange(row)
        }).catch(() => {

        })
      },
      //开关按钮
      switchChange(row){
        let switchData = {
          hardwareNo:row.hardwareNo,
          command:row.operatingState?'0':'1'
        };
        iotHardwareOperatingHardware(switchData).then(response => {
          if(response.code==200){
            this.msgSuccess("操作成功")
          }
        });
      },
      //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)
            // console.log('硬件-mqtt',data)
            let list = JSON.parse(JSON.stringify(this.hardwareList))
            list.forEach((item)=>{
              if(item.hardwareNo == data.hardwareNo){
                if(item.hardwareTypeKey == 'airConditioner'){
                  if(data.command == 0){
                    item.switchType = 0;
                    item.functionType = '';
                    item.orderType = '';
                  }else if(data.command == 2){
                    item.switchType = 1;
                    item.functionType = 3;
                    item.orderType = '';
                  }else if(data.command.indexOf('-') != -1){
                    let list = data.command.split('-');
                    item.switchType = 1;
                    item.functionType = list[0]==3?1:(list[0]==4?2:'');
                    item.orderType = list[1]?list[1]:'';
                  }else{
                    item.switchType = '';
                    item.functionType = '';
                    item.orderType = '';
                  }
                }else{
                  item.operatingState = data.operatingState;
                  item.online = data.online;
                }
              }
            })
            this.$set(this,'hardwareList',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-hardwarePage{
    flex:1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    .null-img{
      display: block;
      margin:80px 0 0 150px;
      width:150px;
    }
    .for-hardware-max-big-box{
      flex:1;
      .for-hardware-big-box{
        display: inline-block;
        overflow: hidden;
        width: 180px;
        height: 70px;
        padding:10px 14px;
        margin: 0 0 11px 16px;
        border-radius: 10px;
        .for-hardware-box{
          .for-hardware-text-box{
            display: flex;
            flex:1;
            p{
              overflow: hidden;
              font-size: 14px;
              line-height: 24px;
            }
            p:nth-child(1){
              flex:1;
              display:block;
              overflow:hidden;
              text-overflow:ellipsis;
              white-space:nowrap;
              margin-right:10px;
            }
            p:nth-child(2){
            }
          }
          .for-hardware-switch-box{
            flex:1;
            display: flex;
            margin-top: 7px;
            overflow: hidden;
            .for-hardware-switch-title{
              flex:1;
              p{
                width: 70px;
                height: 20px;
                border-radius: 10px;
                opacity: 1;
                border: 1px solid #0183FA;
                font-size: 12px;
                font-weight: 400;
                color: #0183FA;
                line-height: 17px;
                text-align: center;
              }
            }
            .for-hardware-text-title{
              flex:1;
              display: flex;
              p{
                font-size:12px;
                height:20px;
                line-height:20px;
              }
              p:nth-child(1){
                width:34px;
                text-align: center;
                border-radius:4px;
                margin-right:6px;
              }
              p:nth-child(2){
                text-align: center;
              }
              p:nth-child(3){
                text-align: center;
              }
              .colorOpen{
                background-color: #0183FA;
                color:#fff;
              }
              .colorOff{
                background-color: #999;
                color:#fff;
              }
              .colorText{
                color:#999;
              }
            }
            .for-hardware-button{
              background-color: #0183FA;
              color:#fff;
              font-size:12px;
              width:50px;
              line-height:20px;
              text-align: center;
              border-radius:20px;
              cursor: pointer;
            }
          }
        }
      }
      .offLineColor{
        color:#333;
        background-color: #E0E0E0;
      }
      .onLineColor{
        color:#333;
        background-color: #E5F2FF;
      }
    }
  }
</style>
<style lang="scss">
  .indexRightPage-hardwarePage{
    .el-switch{
      display: block;
      width:50px!important;
      height:20px!important;
    }
    .switch .el-switch__label {
      position: absolute;
      display: none;
      color: #fff !important;
    }
    .switch .el-switch__label.is-active {
      display: block;
    }
    .switch.el-switch .el-switch__core,
    .el-switch .el-switch__label {
      width: 50px !important;
      height:20px!important;
      line-height:20px!important;
      -webkit-border-radius: 20px!important;
      -moz-border-radius: 20px!important;
      border-radius: 20px!important;
      margin: 0;
      position: absolute;
      top: 0;
    }
    .switch .el-switch__label--left {
      z-index: 1;
    }
    .switch .el-switch__label--left span{
      margin-left:19px;
      font-size: 12px;
      color:#fff;
    }
    .switch .el-switch__label--right {
      z-index: 1;
    }
    .switch .el-switch__label--right span{
      margin-left:6px;
      font-size: 12px;
      color:#fff;
    }
    .el-switch__core{
      background-color: #999;
    }
    .el-switch__core:after{
      height:14px!important;
      width:14px!important;
      top:2px!important;
      left:2px;
    }
    .el-switch.is-checked .el-switch__core{
      background-color: #1890ff;
    }
    .el-switch.is-checked .el-switch__core::after{
      margin-left: -16px!important;
    }
  }
  .indexRightPage-hardwarePage-dialog{
    .infraredController-max-big-box{
      font-size:16px;
      .infraredController-switchType-box{
        display: flex;
        p{
          line-height:30px;
        }
        .switchType-name-p{
          font-size:18px;
          flex:1;
          display:block;
          overflow:hidden;
          text-overflow:ellipsis;
          white-space:nowrap;
        }
        .switchType-type-p{
          cursor: pointer;
          width:80px;
          text-align: center;
          border-radius:6px;
          background-color: #fff;
          border:1px solid #0183FB;
          color:#0183FB;
        }
        .switchType-type-off-p{
          background-color: #fff!important;
          border:1px solid #999!important;
          color:#999!important;
        }
      }
      .infraredController-functionType-box{
        margin-top:20px;
        display: flex;
        p{
          border-radius:6px;
          background-color: #fff;
          border:1px solid #999;
          color:#333;
          line-height:40px;
          width:130px;
          text-align: center;
          margin-left:14px;
          cursor: pointer;
        }
        p:nth-child(1){
          margin-left:0!important;
        }
        .check-button{
          background-color: #0183FB!important;
          border:1px solid #0183FB!important;
          color:#fff!important;
        }
      }
      .infraredController-orderType-box{
        margin-top:20px;
        display: flex;
        p{
          text-align: center;
          line-height:40px;
          width:60px;
        }
        .order-minus{
          cursor: pointer;
          border:1px solid #999;
          border-top-left-radius: 6px;
          border-bottom-left-radius: 6px;
        }
        .order-text{
          width:300px;
          border-top:1px solid #999;
          border-bottom:1px solid #999;
        }
        .order-add{
          cursor: pointer;
          border:1px solid #999;
          border-top-right-radius: 6px;
          border-bottom-right-radius: 6px;
        }
      }
    }
  }
</style>
