<template>
  <div class="subject">
    <div class="subject-page" v-if="pageType == 1">
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
        <el-form-item label="学院" prop="deptId" label-width="60px">
          <el-select v-model="queryParams.deptId" placeholder="请选择学院" clearable size="small">
            <el-option
              v-for="dict in deptOptions"
              :key="dict.deptId"
              :label="dict.deptName"
              :value="dict.deptId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="实验室名称" prop="name" label-width="100px">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入实验室名称"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item style="float: right;">
          <el-col :span="1.5" style="margin-bottom:20px;">
            <p class="add-button-one-120"
               @click="clickPage(2)"
               v-hasPermi="['laboratory:subject:add']"
            ><i class="el-icon-plus"></i>新增实验室</p>
          </el-col>
        </el-form-item>
        <el-form-item style="margin-right: 20px;">
          <p class="inquire-button-one" style="margin-left:20px;" @click="handleQuery">查询</p>
          <p class="reset-button-one" style="margin-left:20px;" @click="resetQuery">重置</p>
        </el-form-item>
      </el-form>
      <div class="subject-page-min">
        <div class="left-subject-list" >
          <el-table ref="multipleTable" border :data="subjectList" highlight-current-row @current-change="handleCurrentChange" style="cursor: pointer;">
            <el-table-column label="排序" align="left" prop="id" width="80">
              <template slot-scope="scope">
                <el-input maxlength="4" type="text" oninput ="value=value.replace(/[^0-9.]/g,'')" v-model="scope.row.diyOrder" @focus="liveSort(scope.row)" @blur="editSort(scope.row)"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="实验室名称" align="left" prop="name" width="230" show-overflow-tooltip/>
            <el-table-column label="位置" align="left" prop="name" width="160" show-overflow-tooltip>
              <template slot-scope="scope">
                {{scope.row.buildName}}{{scope.row.floorName}}{{scope.row.room}}
              </template>
            </el-table-column>
            <!--<el-table-column label="类型" align="left" prop="moldName" width="100" show-overflow-tooltip/>-->
            <el-table-column label="安全分类" align="left" prop="typeName" width="100" show-overflow-tooltip/>
            <el-table-column label="安全分级" align="left" prop="levelName" width="80" show-overflow-tooltip>
              <template slot-scope="scope">
                <span :style="'color:'+scope.row.fiedColor+';'">{{scope.row.levelName}}</span>
              </template>
            </el-table-column>
            <el-table-column label="重大危险源辨识指标" align="left" prop="riskIndicator" width="150" show-overflow-tooltip/>
            <el-table-column label="学院" align="left" prop="deptName" width="150" show-overflow-tooltip/>
            <el-table-column label="实验室责任人" align="left" prop="adminName" width="120" show-overflow-tooltip/>
            <el-table-column label="安全责任人" align="left" prop="safeUserName" width="200" show-overflow-tooltip/>
            <el-table-column label="操作" align="left" width="160">
              <template slot-scope="scope">
                <div style="display: flex;height:30px;">
                  <p class="table-min-button" style="margin-right:10px;" v-hasPermi="['laboratory:subject:query']" @click="clickPage(7,scope.row)">详情</p>
                  <el-dropdown trigger="click" size="mini" @command="(command) => handleCommand(command, scope.row)">
                    <p class="table-min-button">更多<i class="el-icon-d-arrow-right"></i></p>
                    <el-dropdown-menu slot="dropdown" style="margin:0!important;">
                      <el-dropdown-item style="height:36px;line-height:36px;width:90px;text-align: center" command="1" v-hasPermiAnd="['laboratory:subject:query','laboratory:subject:edit']">关联配置</el-dropdown-item>
                      <el-dropdown-item style="height:36px;line-height:36px;width:90px;text-align: center" command="2">物联配置</el-dropdown-item>
                      <el-dropdown-item style="height:36px;line-height:36px;width:90px;text-align: center" command="3" v-hasPermi="['laboratory:subjectmaterial:add']">准入配置</el-dropdown-item>
                      <el-dropdown-item style="height:36px;line-height:36px;width:90px;text-align: center" command="4" v-hasPermiAnd="['laboratory:subject:query','laboratory:subject:edit']">编辑</el-dropdown-item>
                      <!--<el-dropdown-item style="height:36px;line-height:36px;width:90px;text-align: center" command="5"-->
                      <!--v-hasPermi="['laboratory:subject:remove']">删除</el-dropdown-item>-->
                    </el-dropdown-menu>
                  </el-dropdown>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </div>
        <div class="right-subject-box scrollbar-box" :class="rightButtonType == 4?'overflow-box':''" v-if="checkedSubject.id">
          <div class="top-button-box">
            <div :class="rightButtonType == 1 ? 'buttonColorA' : 'buttonColorB'" @click="rightButtonClick(1)">传感器监测</div>
            <div :class="rightButtonType == 2 ? 'buttonColorA' : 'buttonColorB'" @click="rightButtonClick(2)">物联控制</div>
            <div :class="rightButtonType == 3 ? 'buttonColorA' : 'buttonColorB'" @click="rightButtonClick(3)">视频监控</div>
            <div :class="rightButtonType == 4 ? 'buttonColorA' : 'buttonColorB'" @click="rightButtonClick(4)">智能声光报警器</div>
          </div>
          <!--传感器-->
          <div class="bottom-max-box" :class="rightButtonType == 4?'overflow-box':''">
            <div class="bottom-sensor-box" v-if="rightButtonType == 1">
              <p class="top-title">当前位置：{{checkedSubject.subAddrr.buildName}}{{checkedSubject.subAddrr.floorName}}</p>
              <div class="sensor-for-max-box" v-if="checkedSubject.sensorFunctionStatusList[0]">
                <div class="sensor-for-big-box"
                     :class="item.type == 1 ? 'sensor-color-a' : (item.type == 2 ? 'sensor-color-b' : 'sensor-color-c')"
                     v-for="(item,index) in checkedSubject.sensorFunctionStatusList" :key="index">
                  <div class="sensor-for-min-box">
                    <img src="@/assets/ZDimages/subject/icon_bj_wd.png" v-if="item.funNum == 'wendu'">
                    <img src="@/assets/ZDimages/subject/icon_bj_sd.png" v-if="item.funNum == 'shidu'">
                    <img src="@/assets/ZDimages/subject/icon_bj_eyht.png" v-if="item.funNum == 'co'">
                    <img src="@/assets/ZDimages/subject/icon_bj_jwnd.png" v-if="item.funNum == 'jiawan'">
                    <img src="@/assets/ZDimages/subject/icon_sy_yqnd.png" v-if="item.funNum == 'o2'">
                    <img src="@/assets/ZDimages/subject/icon_bj_yg.png" v-if="item.funNum == 'yanwu'">
                    <img src="@/assets/ZDimages/subject/icon_sy_dqy.png" v-if="item.funNum == 'daqiya'">
                    <img src="@/assets/ZDimages/subject/icon_syspz_voc.png" v-if="item.funNum == 'voc'">
                    <img src="@/assets/ZDimages/subject/icon_syspz_tvoc.png" v-if="item.funNum == 'tvoc'">
                    <img src="@/assets/ZDimages/subject/icon_sy_mcnd.png" v-if="item.funNum == 'so2'">
                    <img src="@/assets/ZDimages/subject/icon_bj_yyhd.png" v-if="item.funNum == 'no1'">
                    <img src="@/assets/ZDimages/subject/icon_bj_dqy.png" v-if="item.funNum == 'fenchen'">
                    <img src="@/assets/ZDimages/subject/icon_bj_qq.png" v-if="item.funNum == 'H2'">
                    <img src="@/assets/ZDimages/subject/guangqi.png" v-if="item.funNum == 'guangqi'">
                    <img src="@/assets/ZDimages/subject/lvqi.png" v-if="item.funNum == 'lvqi'">
                    <div>
                      <el-tooltip class="item" effect="dark" :content="item.describe" placement="bottom">
                        <p>{{item.describe|ellipsis}}</p>
                      </el-tooltip>
                      <p>{{item.formatVal}}</p>
                    </div>
                  </div>
                </div>
              </div>
              <img class="null-data-img" src="@/assets/ZDimages/null-data.png" v-if="!checkedSubject.sensorFunctionStatusList[0]">
              <p class="null-text-p" v-if="!checkedSubject.sensorFunctionStatusList[0]">暂无环境监测信息，请在更多操作-物联设备配置中进行添加</p>
              <p class="bottom-text" v-if="checkedSubject.sensorFunctionStatusList[0]">数据上报时间：{{checkedSubject.sensorFunctionStatusList[0].sendDate}}</p>
            </div>
            <div class="bottom-switch-box" v-if="rightButtonType == 2">
              <p class="top-title">当前位置：{{checkedSubject.subAddrr.buildName}}{{checkedSubject.subAddrr.floorName}}</p>
              <div class="switch-for-max-box" v-show="checkedSubject.labHardwareVOList" v-hasPermi="['laboratory:subcontrol:set']">
                <div class="switch-for-big-box" v-for="(item,index) in checkedSubject.labHardwareVOList" :key="index">
                  <div class="switch-for-min-box" v-if="item.hardwareTypeEnum.enumName == 'SWITCH'">
                    <p class="switch-for-min-title">电源控制</p>
                    <el-switch
                      v-if="item.state.code == 3||item.state.code == 4"
                      class="switch"
                      @click.native="changeIsNeedCaptcha(item)"
                      v-model="item.state.code"
                      :active-value="3"
                      :inactive-value="4"
                      active-text="开"
                      inactive-text="关"
                      disabled>
                    </el-switch>
                    <p class="switch-null-p" v-else>{{item.state.name}}</p>
                  </div>
                  <div class="switch-for-min-box" v-if="item.hardwareTypeEnum.enumName == 'AI_VENTILATION'">
                    <p class="switch-for-min-title">智能通风</p>
                    <el-switch
                      v-if="item.state.code == 3||item.state.code == 4"
                      class="switch"
                      @click.native="changeIsNeedCaptcha(item)"
                      v-model="item.state.code"
                      :active-value="3"
                      :inactive-value="4"
                      active-text="开"
                      inactive-text="关"
                      disabled>
                    </el-switch>
                    <p class="switch-null-p" v-else>{{item.state.name}}</p>
                  </div>
                  <div class="switch-for-min-box" v-if="item.hardwareTypeEnum.enumName == 'ONE_MACHINE'">
                    <p class="switch-for-min-title">广播系统</p>
                    <p class="switch-for-min-button" @click="handleAdd(item.subId)">播放文字</p>
                  </div>
                </div>
              </div>
              <img class="null-data-img" src="@/assets/ZDimages/null-data.png" v-show="!checkedSubject.labHardwareVOList">
              <p class="null-text-p" v-show="!checkedSubject.labHardwareVOList">暂无物联控制信息，请在更多操作-物联设备配置中进行添加</p>
            </div>
            <div class="bottom-video-box" v-if="rightButtonType == 3">
              <p class="top-title">当前位置：{{checkedSubject.subAddrr.buildName}}{{checkedSubject.subAddrr.floorName}}</p>
              <div class="video-for-max-box" v-if="checkedSubject.videoData[0]">
                <div class="switch-for-big-box" v-for="(item,index) in checkedSubject.videoData" :key="index">
                  <video :id="item.divId" ref="videoRef" autoplay controls  muted width="490px" height="262px"></video>
                  <p class="el-icon-full-screen position-p" @click="videoFullScreen(index)"></p>
                </div>
              </div>
              <img class="null-data-img" src="@/assets/ZDimages/null-data.png" v-if="!checkedSubject.videoData[0]">
              <p class="null-text-p" v-if="!checkedSubject.videoData[0]">暂无视频监控信息，请在更多操作-物联设备配置中进行添加</p>
            </div>
            <div class="bottom-alarm-box" v-if="rightButtonType == 4">
              <div class="alarm-max-box">
                <img src="@/assets/ZDimages/medicUniversity-3_1/img_syslb_znsgbjzx.png" class="alarm-img">
                <div class="alarm-big-box" v-if="hardwareData[0]">
                  <p>报警器编号：{{hardwareData[0].hardwareNum}}</p>
                  <p :class="hardwareData[0].status==3||hardwareData[0].status==4?'colorTypeA':'colorTypeB'">{{hardwareData[0].status==3||hardwareData[0].status==4?'在线':'离线'}}</p>
                </div>
                <div class="alarm-big-box" v-if="!hardwareData[0]">
                  <p>未绑定报警器</p>
                </div>
                <div class="alarm-position-box" v-if="hardwareData[0]">
                  <el-switch
                    v-if="hardwareData[0].status == 3||hardwareData[0].status == 4"
                    @click.native="changeIsNeedCaptchaAlarm(hardwareData[0])"
                    class="switch captcha-img"
                    :active-value="3"
                    :inactive-value="4"
                    active-color="#FF9900"
                    inactive-color="#999"
                    v-model="hardwareData[0].status"
                    active-text="报警中"
                    inactive-text="未报警"
                    disabled
                  ></el-switch>
                </div>
              </div>
              <div class="alarm-title-box">
                <p>报警记录</p>
                <p v-hasPermi="['chemical:hxpAlarmRecord:list']" @click="goAlarmRecord">更多>></p>
              </div>
              <el-table  border :data="tableList" ref="multipleTable">
                <el-table-column label="报警时间" align="center" prop="alarmTime"/>
                <el-table-column label="报警时长" align="center" prop="alarmDuration" width="110"/>
                <el-table-column label="处理状态" align="center" prop="operate" width="100"/>
                <el-table-column label="处理人" align="center" prop="handlingUserName" width="90"/>
              </el-table>
              <pagination
                v-show="totalTwo>0"
                :total="totalTwo"
                :page.sync="queryParamsTwo.pageNum"
                :limit.sync="queryParamsTwo.pageSize"
                @pagination="getHxpAlarmRecordNoAuthList"
              />
            </div>
          </div>
        </div>
      </div>
    </div>
    <add-subject v-if="pageType == 2" :subjectData="subjectData"></add-subject>
    <device-list v-if="pageType == 3" :subjectData="subjectData"></device-list>
    <admission-configuration v-if="pageType == 4" :subjectData="subjectData"></admission-configuration>
    <association-configuration v-if="pageType == 5" :subjectData="subjectData"></association-configuration>
    <info-page v-if="pageType == 6" :newData="newData"></info-page>
    <!--播放文字窗口-->
    <el-dialog title="广播系统" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="播放文字" prop="txt">
          <el-input v-model="form.txt" placeholder="请输入播放文字" />
        </el-form-item>
        <el-form-item label="播报方式" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio :label="1">文字</el-radio>
            <el-radio :label="2">音频</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitFormOne">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import mqtt from 'mqtt'
import flvjs from 'flv.js'
import { hardWareControl,alarmControl } from "@/api/laboratory/hardware";
import { authListSubject,subjectInfo,updateSubject,mangerVoice,startUrl } from "@/api/laboratory/subject";
import { filterDept } from "@/api/medicUniversity-3_1/index";
import addSubject from "./addSubject.vue";
import deviceList from "./deviceList.vue";
import admissionConfiguration from "./admissionConfiguration.vue";
import associationConfiguration from "./associationConfiguration.vue";
import infoPage from "./infoPage.vue";
import { getHxpAlarmRecordNoAuthList,getEnablelist } from "@/api/medicUniversity-3_1/index";
export default {
  filters:{
    ellipsis(value){
      if (!value) return '';
      if (value.length > 6) {
        return value.slice(0,6) + '...'
      }
      return value
    }
  },
  name: "subject",
  components: {
    addSubject,
    deviceList,
    admissionConfiguration,
    associationConfiguration,
    infoPage
  },
  data(){
    return{
      pageType:1,
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize:20,
        name: null,
        floorId: null,
        room: null,
        deptId: null,
        deptName: null,
        adminId: null,
        isDel: null,
        userId: null,
        diyOrder: null
      },
      // 实验室表格数据
      subjectList: [],
      //学院列表
      deptOptions:[],
      //当前选中实验室
      checkedSubject:{},
      //当前选中右侧按钮
      rightButtonType:1,
      //编辑实验室数据
      subjectData:{},
      // 临时保存排序
      sort:"",
      //播放文字的实验室id
      subId:"",
      open:false,
      form:{},
      rules:{
        txt:[
          {required: true, message: '请输入播放文字', trigger: 'blur'},
          { required: true, message: "请输入播放文字", validator: this.spaceJudgment, trigger: "blur" }
        ],
        type:[
          {required: true, message: '请选择播报方式', trigger: 'blur'}
        ],
      },
      newData:{

      },
      //MQTT请求参数-传感器
      mtopic:"lab/function/data",
      //MQTT请求参数-硬件
      mtopicOne:"lab/hardware/data",
      msg:"",
      client:{},
      videoList:[],
      //警报数据
      totalTwo:0,
      tableList:[],
      queryParamsTwo:{
        pageNum:1,
        pageSize:20,
      },
      hardwareData:[],
      //mqtt实验室id
      mqttIdList:[],
    }
  },
  created() {
  },
  mounted(){
    this.getDeptList();
    // this.subscriptionMQTT();
    this.getList();
  },
  methods:{
    goAlarmRecord(){
      this.$router.push({
        path: `/chemicalLibrary/alarmRecord`,
      })
    },
    //报警器开启关闭方法
    changeIsNeedCaptchaAlarm(row){
      let self = this;
      console.log(row.status)
      if(row.status!=3 && row.status!=4){
        return
      }
      let text = row.status==3?'关闭':(row.status==4?'开启':'')
      this.$confirm(`是否`+text+`此设备`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async () => {
        self.alarmControl(row)
      }).catch(() => {

      })
    },
    //开关按钮
    alarmControl(row){
      let switchData = {
        id:row.id,
        switchVal:row.status==3?'close':(row.status==4?'open':'')
      };
      alarmControl(switchData).then(response => {
        if(response.code==200){
          row.status = row.status==3?4:(row.status==4?3:'')
        }
      });
    },
    //获取实验室绑定报警器设备数据
    getEnablelist(){
      let obj = {
        subjectId:this.subId,
        type:"AI_ALARM"
      }
      getEnablelist(obj).then(response => {
        this.hardwareData = response.rows;
      });
    },
    //获取实验室报警列表数据
    getHxpAlarmRecordNoAuthList(){
      this.queryParamsTwo.subId = this.subId;
      getHxpAlarmRecordNoAuthList(this.queryParamsTwo).then(response => {
        this.totalTwo = response.total;
        this.tableList = response.rows;
      });
    },
    //播放文字
    handleAdd(id) {
      this.open = true;
      this.subId = id;
    },
    // 取消按钮
    cancel() {
      this.form = {};
      this.open = false;
    },
    /*播放文字*/
    submitFormOne(){
      this.$refs["form"].validate(valid => {
        if (valid) {
          let id = this.subId;
          mangerVoice(this.form,id).then(response => {
            this.msgSuccess("播放成功");
            this.open = false;
            this.getList();
          });
        }
      });
    },
    // 页面切换
    clickPage(type,row){
      if(this.pageType != type){
        if(type == 1){
          //列表页面
          this.pageType = type;
          this.getList();
          this.$set(this,'subjectData',{})
        }else if(type == 2){
          //新增页面
          this.pageType = type;
        }else if(type == 3){
          //编辑页面
          //this.pageType = 2;
          this.editFun(row);
          //this.$set(this,'subjectData',row)
        }else if(type == 4){
          this.pageType = 3;
          this.$set(this,'subjectData',row)
        }else if(type == 5){
          this.pageType = 4;
          this.$set(this,'subjectData',row)
        }else if(type == 6){
          this.pageType = 5;
          this.$set(this,'subjectData',row)
        }else if(type == 7){
          this.subjectInfoTwo(row);
          // this.$set(this,'subjectData',row)
        }
      }
    },
    //实验室编辑
    editFun(row){
      let self = this;
      let type = 0; //硬件 //0全部
      subjectInfo(row.id,type).then(response => {
        console.log(response.data)
        this.$set(this,'subjectData',response.data)
        this.pageType = 2;
      })
    },
    //获取实验室详情
    subjectInfoTwo(row){
      let self = this;
      let type = 0; //硬件 //0全部
      subjectInfo(row.id,type).then(response => {
        // console.log("获取实验室详情",response.data)
        this.$set(this,'newData',response.data);
        if(response.data.safeUserName){
          this.$set(this.newData,'safeUserName',response.data.safeUserName.split(','));
        }
        if(response.data.safeUserPhone){
          this.$set(this.newData,'safeUserPhone',response.data.safeUserPhone.split(','));
        }
        if(response.data.safeSigns){
          this.$set(this.newData,'safeSigns',response.data.safeSigns.split(','));
        }
        if(response.data.hazardCategory){
          this.$set(this.newData,'hazardCategory',response.data.hazardCategory.split(','));
        }
        if(response.data.outfire){
          this.$set(this.newData,'outfire',response.data.outfire.split(','));
        }
        if(response.data.riskMeasure){
          this.$set(this.newData,'riskMeasure',response.data.riskMeasure.split(','));
        }
        let list = [];
        let listTwo = [];
        if (response.data.labHardwareVOList){
          for(let i=0;i<response.data.labHardwareVOList.length;i++){
            if(response.data.labHardwareVOList[i].hardwareTypeEnum.enumName == 'VIDEO_MONITOR'){
              list.push(response.data.labHardwareVOList[i].hardwareNUM);
            }
            if(response.data.labHardwareVOList[i].hardwareTypeEnum.enumName == 'SWITCH' || response.data.labHardwareVOList[i].hardwareTypeEnum.enumName == 'AI_VENTILATION' || response.data.labHardwareVOList[i].hardwareTypeEnum.enumName == 'ONE_MACHINE'){
              listTwo.push(response.data.labHardwareVOList[i])
            }
          }
        }
        this.$set(this.newData,'labHardwareVOListTwo',listTwo);
        if(list[0]){
          let obj = {
            count:"100",
            deviceIds:list.join(),
            page:"1",
          };
          let urlText = window.location.href;
          if(urlText.indexOf(localStorage.getItem('ipIdentify')) != -1){
            startUrl(obj).then(res => {
              if(res.code == 200){
                if(!res.data[0]){
                  this.msgError("视频配置异常请联系管理员")
                  this.newData.videoData = [];
                  this.pageType = 6;
                }else{
                  let videoList = [];
                  for(let i=0;i<res.data.length;i++){
                    let obj = {
                      name:response.data.name + response.data.subAddrr.room,
                      videoType:"flv",
                      divId:'divId'+i,
                      url:res.data[i].result.body.data.ws_flv,
                    }
                    videoList.push(obj)
                  }
                  this.$set(this.newData,'videoData',videoList);
                  this.pageType = 6;
                }
              }
            });
          }else{
            startUrl(obj).then(res => {
              if(res.code == 200){
                if(!res.data[0]){
                  this.msgError("视频配置异常请联系管理员")
                  this.newData.videoData = [];
                  this.pageType = 6;
                }else{
                  let videoList = [];
                  for(let i=0;i<res.data.length;i++){
                    let text = localStorage.getItem('cameraUrl');
                    let url = res.data[i].result.body.data.ws_flv;
                    url = url.split("rtp/");
                    let newUrl = text+'rtp/'+url[1];
                    let obj = {
                      name:response.data.name + response.data.subAddrr.room,
                      videoType:"flv",
                      divId:'divId'+i,
                      url:newUrl,
                    }
                    videoList.push(obj)
                  }
                  this.$set(this.newData,'videoData',videoList);
                  this.pageType = 6;
                }
              }
            });
          }
        }else{
          this.$set(this.newData,'videoData',[]);
          this.pageType = 6;
        }
      })
    },
    // 开启关闭验证
    async changeIsNeedCaptcha (row) {
      let self = this;
      console.log(row)
      if(row.state.code!=3 && row.state.code!=4){
        return
      }
      let text = row.state.code==3?'关闭':(row.state.code==4?'开启':'')
      this.$confirm(`是否`+text+`此设备`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async () => {
        self.switchChange(row)
      }).catch(() => {

      })
    },
    //开关按钮
    switchChange(row){
      let switchData = {
        id:row.id,
        switchVal:row.state.code==3?'close':(row.state.code==4?'open':'')
      };
      hardWareControl(switchData).then(response => {
        console.log(response);
        if(response.code==200){
          row.state.code = row.state.code==3?4:(row.state.code==4?3:'')
          this.msgSuccess("操作成功")
        }
      });
    },
    //切换实验室展示数据
    rightButtonClick(type){
      let self = this;
      if(this.rightButtonType != type){
        this.rightButtonType = type;
        this.videoOff();
        if(type == 3){
          let self = this;
          let list = [];
          if(self.checkedSubject.labHardwareVOList){
            for(let i=0;i<self.checkedSubject.labHardwareVOList.length;i++){
              if(self.checkedSubject.labHardwareVOList[i].hardwareTypeEnum.enumName == 'VIDEO_MONITOR'){
                list.push(self.checkedSubject.labHardwareVOList[i].hardwareNUM);
              }
            }
            if(list[0]){
              let obj = {
                count:"100",
                deviceIds:list+'',
                page:"1",
              };
              let urlText = window.location.href;
              if(urlText.indexOf(localStorage.getItem('ipIdentify')) != -1){
                startUrl(obj).then(res => {
                  if(res.code == 200){
                    if(!res.data[0]){
                      this.msgError("视频配置异常请联系管理员")
                      return
                    }
                    let videoList = [];
                    for(let i=0;i<res.data.length;i++){
                      let obj = {
                        name:self.checkedSubject.name + self.checkedSubject.subAddrr.room,
                        videoType:"flv",
                        divId:'divId'+i,
                        url:res.data[i].result.body.data.ws_flv,
                      }
                      videoList.push(obj)
                    }
                    this.$set(this.checkedSubject,'videoData',videoList);
                    if(this.rightButtonType == 3){
                      setTimeout(function(){
                        self.videoFunction();
                      },1000);
                    }
                  }
                });
              }else{
                startUrl(obj).then(res => {
                  if(res.code == 200){
                    if(!res.data[0]){
                      this.msgError("视频配置异常请联系管理员")
                      return
                    }
                    let videoList = [];
                    for(let i=0;i<res.data.length;i++){
                      let text = localStorage.getItem('cameraUrl');
                      let url = res.data[i].result.body.data.ws_flv;
                      url = url.split("rtp/");
                      let newUrl = text+'rtp/'+url[1];
                      let obj = {
                        name:self.checkedSubject.name + self.checkedSubject.subAddrr.room,
                        videoType:"flv",
                        divId:'divId'+i,
                        url:newUrl,
                      }
                      videoList.push(obj)
                    }
                    this.$set(this.checkedSubject,'videoData',videoList);
                    if(this.rightButtonType == 3){
                      setTimeout(function(){
                        self.videoFunction();
                      },1000);
                    }
                  }
                });
              }
            }else{
              this.$set(this.checkedSubject,'videoData',[]);
            }
          }else{
            this.$set(this.checkedSubject,'videoData',[]);
          }
        }
      }
    },
    //选中实验室
    handleCurrentChange(val){
      let self = this;
      if(val.id != this.checkedSubject.id){
        this.videoOff();
        this.offMQTT();
        this.subjectInfo(val.id);
        this.subId = val.id;
        this.$set(this,'queryParamsTwo',{
          pageNum:1,
          pageSize:20,
        });
        this.getEnablelist();
        this.getHxpAlarmRecordNoAuthList();
        this.subscriptionMQTT();
      }
    },
    //获取实验室详情
    subjectInfo(id){
      let type = 1; //硬件 //0全部
      subjectInfo(id,type).then(response => {
        this.$set(this,'checkedSubject',response.data);
        this.$set(this.checkedSubject,'videoData',[]);
        this.rightButtonType = 1;
      })
    },
    //编辑按钮
    handleCommand(command, row){
      switch (command) {
        case "1":
          console.log('关联配置');
          this.clickPage(6,row);
          break;
        case "2":
          console.log('物联配置');
          this.clickPage(4,row);
          break;
        case "3":
          console.log('准入配置');
          this.clickPage(5,row);
          break;
        case "4":
          console.log('编辑');
          this.clickPage(3,row);
          break;
        case "5":
          console.log('删除');
          break;
        default:
          break;
      }
    },
    //保存当前排序
    liveSort(row){
      console.log("row",row);
      let obj = {
        sort:row.diyOrder
      }
      this.sort = JSON.parse(JSON.stringify(obj));
    },
    //编辑排序
    editSort(row){
      let self = this;
      if(row.diyOrder != this.sort.sort){
        self.$confirm('是否确认修改排序?', "", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          let obj = {
            id:row.id,
            diyOrder:row.diyOrder,
          };
          updateSubject(obj).then(response => {
            self.msgSuccess("修改成功");
            self.getList();
          });
        }).then(() => {}).catch(() => {
          let obj = JSON.parse(JSON.stringify(self.sort));
          row.diyOrder = obj.sort
        });
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$set(this,'queryParams',{
        pageNum: 1,
        pageSize:20,
        deptId:"",
        name: '',
      });

      // this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 查询实验室列表 */
    getList() {
      this.loading = true;
      // this.offMQTT();
      authListSubject(this.queryParams).then(response => {
        this.subjectList = response.rows;
        this.total = response.total;
        this.loading = false;
        if(response.rows[0]){
          this.$refs.multipleTable.setCurrentRow(response.rows[0]);
          this.subjectInfo(response.rows[0].id);
        }
        let idList = [];
        for(let i=0;i<response.rows.length;i++){
          idList.push(response.rows[i].id)
        }
        this.$set(this,'mqttIdList',idList);
        // this.subscriptionMQTT();
      });
    },
    /** 查询学院列表 */
    getDeptList() {
      filterDept().then(response => {
        this.$set(this, 'deptOptions', response.data)
      });
    },
    //MQTT订阅
    subscriptionMQTT(){
      let self = this;
      this.client = mqtt.connect(localStorage.getItem('mqttUrl'), {
        username: localStorage.getItem('mqttUser'),
        password: localStorage.getItem('mqttPassword')
      });
      this.client.on("connect", e =>{
        console.log("连接成功");
        this.client.subscribe(this.mtopic+self.subId, (err) => {
          if (!err) {
            console.log("订阅成功:" + this.mtopic+self.subId);
          }
        });
        this.client.subscribe(this.mtopicOne+self.subId, (err) => {
          if (!err) {
            console.log("订阅成功:" + this.mtopicOne+self.subId);
          }
        });
        // for(let i = 0; i< self.mqttIdList.length;i++){
        //   this.client.subscribe(this.mtopic+self.mqttIdList[i], (err) => {
        //     if (!err) {
        //       console.log("订阅成功:" + this.mtopic+self.mqttIdList[i]);
        //     }
        //   });
        //   this.client.subscribe(this.mtopicOne+self.mqttIdList[i], (err) => {
        //     if (!err) {
        //       console.log("订阅成功:" + this.mtopicOne+self.mqttIdList[i]);
        //     }
        //   });
        // }
      });
      this.client.on("message", (topic, message) => {
        // console.log('message',message)
        if (message){
          let data = JSON.parse(message)
          // console.log("MQTT----message",data)
          if(data.data.subId){
            //传感器
            // console.log("传感器",data.data.subId,'---------',data);
            if(self.checkedSubject.id){
              if(data.data.subId&&data.data.subId == self.checkedSubject.id){
                self.$set(self.checkedSubject,'sensorFunctionStatusList',data.data.functionStatuses);
                self.$set(self.checkedSubject.sensorFunctionStatusList[0],'sendDate',data.sendDate);
              }
            }
            if(self.newData.id){
              if(data.data.subId&&data.data.subId == self.newData.id){
                self.$set(self.newData,'sensorFunctionStatusList',data.data.functionStatuses);
                self.$set(self.newData.sensorFunctionStatusList[0],'sendDate',data.sendDate);
              }
            }
          }else{
            //硬件
            // console.log("硬件",data);
            for (let i = 0; i < data.data.length; i++) {
              if (self.checkedSubject.labHardwareVOList) {
                for (let k = 0; k < self.checkedSubject.labHardwareVOList.length; k++) {
                  if (self.checkedSubject.labHardwareVOList[k].id == data.data[i].num) {
                    if (data.data[i].hardwareOperate == 'CLOSE') {
                      self.checkedSubject.labHardwareVOList[k].state.code = 4;
                    } else if (data.data[i].hardwareOperate == 'OPEN') {
                      self.checkedSubject.labHardwareVOList[k].state.code = 3;
                    } else if (data.data[i].hardwareOperate == 'OFFLINE') {
                      self.checkedSubject.labHardwareVOList[k].state.code = 0;
                    }
                  }
                }
              }
              if(self.newData.labHardwareVOList){
                for(let k=0;k<self.newData.labHardwareVOList.length;k++){
                  if(self.newData.labHardwareVOList[k].id == data.data[i].num){
                    if(data.data[i].hardwareOperate == 'CLOSE'){
                      self.newData.labHardwareVOList[k].state.code = 4;
                    }else if(data.data[i].hardwareOperate == 'OPEN'){
                      self.newData.labHardwareVOList[k].state.code = 3;
                    }else if(data.data[i].hardwareOperate == 'OFFLINE'){
                      self.newData.labHardwareVOList[k].state.code = 0;
                    }
                  }
                }
              }
            }
          }
        }
      });
    },
    //取消订阅关闭MQTT连接
    offMQTT(){
      let self = this;
      if (self.mqttIdList[0]){
        // for(let i=0;i<self.mqttIdList.length;i++){
        //   self.client.unsubscribe(self.mtopic+self.mqttIdList[i], error => {
        //     if (error) {
        //       console.log('Unsubscribe error', error)
        //     }
        //   })
        //   self.client.unsubscribe(self.mtopicOne+self.mqttIdList[i], error => {
        //     if (error) {
        //       console.log('Unsubscribe error', error)
        //     }
        //   })
        // }
        self.client.unsubscribe(self.mtopic+self.subId, error => {
          if (error) {
            console.log('Unsubscribe error', error)
          }
        })
        self.client.unsubscribe(self.mtopicOne+self.subId, error => {
          if (error) {
            console.log('Unsubscribe error', error)
          }
        })
        self.client.end();
        self.client = {};
      }
    },
    //视频方法
    videoFunction(){
      let self = this;
      // self.videoList = [];
      for(let i=0;i<self.checkedSubject.videoData.length;i++){
        let obj = {
          player :{},
          flvPlayer:{}
        };
        obj.player = document.getElementById(self.checkedSubject.videoData[i].divId);
        // if (flvjs.isSupported()) {
        obj.flvPlayer = flvjs.createPlayer(
          {
            // isLive: true, //=> 是否为直播流
            // hasAudio: false, //=> 是否开启声音
            type: self.checkedSubject.videoData[i].videoType, //媒体类型 flv 或 mp4
            url: self.checkedSubject.videoData[i].url //视频流地址
          },
          {
            enableStashBuffer: true,//启用 IO 存储缓冲区。 如果您需要实时流播放（最小延迟），请设置为 false，但如果存在网络抖动，则可能会停止。
            stashInitialSize: 128,//IO 存储缓冲区初始大小。 默认值为 384KB。 指示合适的大小可以改善视频加载/搜索时间。
            isLive: true,//是否是直播
            lazyLoadRecoverDuration: 30,//指示以秒为单位的lazyLoad 恢复时间边界。
            autoCleanupSourceBuffer: true,//进行自动清理
            autoCleanupMaxBackwardDuration: 3 * 60,//3 * 60 当向后缓冲持续时间超过这个值（以秒为单位）时，对 SourceBuffer 进行自动清理
            autoCleanupMinBackwardDuration: 2 * 60,//2 * 60 指示在执行自动清理时为后向缓冲区保留的持续时间（以秒为单位）。
          }
        );
        self.videoList.push(obj);
        // }
        console.log("i",i)
      }

      for(let i=0;i<self.videoList.length;i++){
        self.videoList[i].flvPlayer.attachMediaElement(self.videoList[i].player);
        self.videoList[i].flvPlayer.load(); //加载
        self.videoList[i].flvPlayer.play(); //加载
      }
    },
    //视屏全屏方法
    videoFullScreen(index){
      this.$refs.videoRef[index].webkitRequestFullScreen();
    },
    //断开视频流
    videoOff(){
      let self = this;
      if(self.videoList[0]){
        for(let i=0;i<self.videoList.length;i++){
          self.videoList[i].flvPlayer.pause();
          self.videoList[i].flvPlayer.unload();
          self.videoList[i].flvPlayer.detachMediaElement();
          self.videoList[i].flvPlayer.destroy();
          self.videoList[i].flvPlayer = null;
        }
        self.videoList = [];
      }
    },
  },
  beforeDestroy() {
    //清除定时器
    let self = this;
    self.videoOff();
    self.offMQTT();
    console.log("beforeDestroy");
  },
}
</script>

<style scoped lang="scss">
.subject{
  flex:1;
  display: flex!important;
  flex-direction: column;
  overflow: hidden;
  *{
    margin:0;
  }
  .subject-page{
    flex:1;
    display: flex;
    flex-direction: column;
    padding:20px;
    overflow: hidden;
    border-radius:10px;
    margin:5px 20px 20px 10px;
    box-shadow: 0 0 8px 1px rgba(0, 0, 0, 0.1);
    .subject-page-min{
      flex:1;
      display: flex;
      overflow: hidden;
    }
    .left-subject-list{
      flex:1;
      display: flex;
      flex-direction: column;
      margin-right:20px;
      overflow: hidden ;
    }
    .overflow-box{
      overflow: hidden;
    }
    .right-subject-box{
      width:514px;
      display: flex;
      flex-direction: column;
      .top-button-box{
        display: flex;
        div{
          padding:0 10px;
          height:40px;
          line-height:40px;
          font-size:16px;
          text-align: center;
          border-top-right-radius: 10px;
          border-top-left-radius: 10px;
          margin-right:1px;
          cursor: pointer;
          font-weight: 500;
        }
        .buttonColorA{
          color:#FFFFFF;
          background:#0045AF ;
        }
        .buttonColorB{
          color:#999999;
          background:#E0E0E0 ;
        }
      }
      .bottom-max-box{
        font-weight:500;
        flex:1;
        display: flex;
        flex-direction: column;
        .bottom-sensor-box{
          background: #fff;
          width:510px;
          border: 1px solid #E0E0E0;
          border-radius: 0 10px 10px 10px;
          .top-title{
            line-height:18px;
            font-size:16px;
            margin:23px 10px;
          }
          .null-text-p{
            text-align: center;
            font-size:16px;
            color:#999;
            line-height:50px;
            margin:0 30px;
          }
          .sensor-for-max-box{
            .sensor-for-big-box{
              display: inline-block;
              width:158px;
              height:60px;
              margin:0 0 11px 8px;
              border-radius: 10px;
              .sensor-for-min-box{
                display: flex;
                img{
                  width:26px;
                  height:26px;
                  margin:17px 11px;
                }
                div{
                  margin:9px 0;
                  p{
                    color:#fff;
                  }
                  p:nth-child(1){
                    font-size:14px;
                    line-height:20px;
                  }
                  p:nth-child(2){
                    font-size:16px;
                    line-height:22px;
                  }
                }
              }
            }
            .sensor-color-a{
              background: #FF7272;
              color:#fff;
            }
            .sensor-color-b{
              background: #E0E0E0;
              color:#999999;
            }
            .sensor-color-c{
              background: #80D164;
              color:#fff;

            }
          }
          .bottom-text{
            line-height:18px;
            font-size:14px;
            color:#999999;
            margin:40px 10px 15px;
          }
        }
        .bottom-switch-box{
          background: #fff;
          width:510px;
          border: 1px solid #E0E0E0;
          border-radius: 0 10px 10px 10px;
          .top-title{
            line-height:18px;
            font-size:16px;
            margin:23px 10px;
          }
          .null-text-p{
            text-align: center;
            font-size:16px;
            color:#999;
            line-height:50px;
            margin:0 30px;
          }
          .switch-for-max-box{
            .switch-for-big-box{
              display: inline-block;
              .switch-for-min-box{
                width:210px;
                height:60px;
                border:1px solid #E0E0E0;
                border-radius: 10px;
                margin:0 0 20px 30px;
                display: flex;
                .switch-for-min-title{
                  font-size:16px;
                  line-height:58px;
                  width:113px;
                  margin-left:12px;
                  display:block;
                  overflow:hidden;
                  text-overflow:ellipsis;
                  white-space:nowrap;
                }
                .switch{
                  margin-top:14px;
                }
                .switch-null-p{
                  font-size:16px;
                  line-height:58px;
                  color:#999;
                }
                .switch-for-min-button{
                  width:70px;
                  height:30px;
                  line-height:30px;
                  font-size:14px;
                  color:#0045AF;
                  border-radius:6px;
                  border: 1px solid #0045AF;
                  margin-top:14px;
                  text-align: center;
                  cursor: pointer;
                }
              }
            }
          }
        }
        .bottom-video-box{
          background: #fff;
          width:510px;
          border: 1px solid #E0E0E0;
          border-radius: 0 10px 10px 10px;
          .top-title{
            line-height:18px;
            font-size:16px;
            margin:23px 10px;
          }
          .null-text-p{
            text-align: center;
            font-size:16px;
            color:#999;
            line-height:50px;
            margin:0 30px;
          }
          .video-for-max-box{
            .switch-for-big-box{
              width:490px;
              height:262px;
              margin:0 auto 14px;
              position: relative;
              .position-p{
                width:42px;
                height:42px;
                text-align: center;
                line-height:42px;
                font-size:18px;
                position: absolute;
                top:0;
                right:0;
                color:#fff;
                cursor: pointer;
              }
            }
          }
        }
        .bottom-alarm-box{
          flex:1;
          display: flex;
          flex-direction: column;
          background: #fff;
          width:510px;
          overflow-x: hidden;
          .alarm-max-box{
            width:510px;
            height:150px;
            display: flex;
            position:relative;
            border: 1px solid #E0E0E0;
            border-radius: 0 10px 10px 10px;
            .alarm-img{
              width:110px;
              height:110px;
              margin:20px;
            }
            .alarm-big-box{
              p:nth-child(1){
                font-size:14px;
                margin:40px 0 25px 0;
              }
              p:nth-child(2){
                width: 60px;
                font-size:12px;
                font-weight:700;
                line-height:24px;
                border-radius: 12px;
                text-align: center;
              }
              .colorTypeA{
                background: rgba(1,131,250,0.2);
                color:#0183FA;
              }
              .colorTypeB{
                background: #ECECEC;
                color:#A2A2A2;
              }
            }
            .alarm-position-box{
              position:absolute;
              bottom:20px;
              right:15px;
              width: 75px;
              height: 30px;
            }
          }
          .alarm-title-box{
            display: flex;
            p{
              line-height:60px;
              font-size:14px;
            }
            p:nth-child(1){
              flex:1;
            }
            p:nth-child(2){
              cursor: pointer;
            }
          }
        }
        .null-data-img{
          width:137px;
          height:137px;
          display: block;
          margin:10px auto;
        }
      }
    }
  }
}
</style>
<style lang="scss">
.alarm-position-box{
  .switch .el-switch__label {
    position: absolute;
    display: none;
    color: #fff !important;
  }
  .switch .el-switch__label--right {
    z-index: 1;
  }
  .switch .el-switch__label--right span{
    margin-right: 9px;
  }
  .switch .el-switch__label--left {
    z-index: 1;
  }
  .switch .el-switch__label--left span{
    margin-left: 9px;
  }
  .switch .el-switch__label.is-active {
    display: block;
  }
  .switch.el-switch .el-switch__core,
  .el-switch .el-switch__label {
    width: 80px !important;
    height:30px!important;
    line-height:30px!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 span{
    margin-left:30px!important;
  }
  .switch .el-switch__label--right span{
    margin-left:8px!important;
  }
  .el-switch__core:after{
    height:24px!important;
    width:24px!important;
    top:2px!important;
  }
  .el-switch.is-checked .el-switch__core::after{
    margin-left: -25px!important;
  }
  .el-switch{
    margin:10px auto 0;
    display: block;
    width:80px!important;
    height:4px!important;
  }
}
</style>
