<!--硬件管理/电源控制-->
<template>
  <div class="powerControl">
    <el-table v-loading="loading" border :data="hardwareList" @selection-change="handleSelectionChange">
      <el-table-column label="名称" align="left" prop="name" />
      <el-table-column label="学院" align="left" prop="deptName" />
      <el-table-column label="实验室" align="left" prop="subjectName" />
      <el-table-column label="继电器编号" align="left" prop="relayCode" />
      <el-table-column label="状态" align="left" >
        <template slot-scope="scope">
          <p :class="scope.row.status==4?'table-type-color-ash':(scope.row.status==3?'table-type-color-green':(scope.row.status==0?'table-type-color-red':''))">{{scope.row.status==4?'关闭':(scope.row.status==3?'开启':(scope.row.status==0?'离线':(!scope.row.status?'未知':'')))}}</p>
        </template>
      </el-table-column>
      <el-table-column label="开关" align="left" >
        <template slot-scope="scope">
          <!--@change="(event)=>switchChange(event,scope.row.id)"-->
          <el-switch
            v-if="scope.row.status == 3||scope.row.status == 4"
            class="switch"
            @click.native="changeIsNeedCaptcha(scope.row)"
            v-model="scope.row.status"
            :active-value="3"
            :inactive-value="4"
            active-text="开"
            inactive-text="关"
            disabled
          >
          </el-switch>
          <p v-else :class="scope.row.status==0?'table-type-color-red':''">{{scope.row.status==0?'离线':'未知'}}</p>
        </template>
      </el-table-column>
      <!--<el-table-column label="开关" align="left" >-->
        <!--<template slot-scope="scope">-->
          <!--<el-switch-->
            <!--class="switch"-->
            <!--@change="switchChange(scope.row.deptId)"-->
            <!--v-model="scope.row.deptId"-->
            <!--:active-value="1"-->
            <!--:inactive-value="0"-->
            <!--active-text="开"-->
            <!--inactive-text="关"-->
          <!--&gt;-->
          <!--</el-switch>-->
        <!--</template>-->
      <!--</el-table-column>-->
      <el-table-column label="操作" align="left" class-name="small-padding fixed-width" width="120" v-if="tableButtonType">
        <template slot-scope="scope">
          <div class="button-box">
            <el-dropdown @command="moreClick">
              <p class="table-min-button">更多>></p>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item style="border-bottom:1px solid #E0E0E0;margin:0 10px;" :command="{row:scope.row,command:1}"
                                  v-hasPermiAnd="['laboratory:hardware:query','laboratory:hardware:edit']">修改设备</el-dropdown-item>
                <el-dropdown-item style="margin:0 10px;" :command="{row:scope.row,command:2}"
                                  v-hasPermi="['laboratory:hardware:remove']">删除设备</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <pagination :page-sizes="[20, 30, 40, 50]"
      v-show="total>0"
      :total="total"
      layout="total, prev, pager, next, sizes, jumper"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改硬件对话框 -->
    <el-drawer
      class="videoSurveillance-drawer"
      :visible.sync="drawer"
      direction="rtl"
      ref="drawer"
      :with-header="false"
      :show-close="false"
      :before-close="handleClose">
      <div class="videoSurveillance-drawer-max-box">
        <div class="videoSurveillance-drawer-content">
          <el-form ref="form" :model="form"  :rules="rules" label-width="80px">
            <el-form-item label="硬件名称"  prop="name">
              <el-input
                v-model="form.name"
                placeholder="请输入硬件名称"
                clearable
                size="small"
                maxLength="8"
              />
            </el-form-item>
            <el-form-item label="硬件类型" v-if="pageType==''" prop="type">
              <el-select v-model="form.type" placeholder="请选择硬件类型">
                <el-option label="请选择硬件类型" value="" />
                <el-option v-for="hardType in hardTypeOptions"
                           :key="hardType.enumName"
                           :label="hardType.name"
                           :value="hardType.enumName">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="实验室" prop="subjectId">
              <el-select v-model="form.subjectId" placeholder="请选择实验室">
                <el-option v-for="lab in labListOptions"
                           :key="lab.id"
                           :label="lab.name"
                           :value="lab.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="继电器类型" label-width="1rem">
              <el-radio-group v-model="form.hardwareType" @change="radioChange">
                <el-radio :label="item.value" :key="item.value" v-for="(item,index) in hardwardTypeList">{{item.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="绑定继电器" prop="relayCode" v-if="form.hardwareType==1">
              <el-select v-model="form.relayCode" placeholder="请选择继电器" clearable @change="loadRelayNum" @clear="loadClear">
                <el-option v-for="relay in relayList"
                           :key="relay.code"
                           :label="relay.code"
                           :value="relay.code">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="继电器编号"  prop="relayCode" v-if="form.hardwareType==2">
              <el-input
                v-model="form.relayCode"
                placeholder="请输入继电器编号"
                clearable
                size="small"
                maxlength="20"
              />
            </el-form-item>
            <el-form-item label="继电器位置" prop="bit" >
              <el-select v-model="form.bit" placeholder="请选择继电器位置" clearable >
                <el-option v-for="lab in relayNumList"
                           :key="lab.name"
                           :label="lab.name"
                           :value="lab.name">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="是否灭火主机" prop="isPcfire">
              <el-radio-group v-model="form.isPcfire">
                <el-radio :label="0">否</el-radio>
                <el-radio :label="1">是</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="配置名称"  prop="relayCode" v-if="form.hardwareType==2">
              <el-input
                v-model="form.configName"
                placeholder="请输入配置名称"
                clearable
                size="small"
                maxLength="15"
              />
            </el-form-item>
            <el-form-item label="配置状态"  prop="relayCode" v-if="form.hardwareType==2">
              <el-input
                v-model="form.configStatus"
                placeholder="请输入配置状态"
                clearable
                size="small"
                maxLength="8"
              />
            </el-form-item>
          </el-form>
        </div>
        <div class="videoSurveillance-bottom-button-box">
          <p></p>
          <p @click="offDrawer">取消</p>
          <p @click="submitForm">提交</p>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
  import mqtt from 'mqtt'
  import { subjectDictList } from "@/api/laboratory/group";
  import { listDepartments } from "@/api/system/dept";
  import { listHardware, getHardware, delHardware, addHardware, updateHardware,queryHardwareType,getHardwareDetail,getSubjectLayout,hardWareControl  } from "@/api/laboratory/hardware";

  import { treeselect } from "@/api/system/dept";
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import { listRelay } from "@/api/laboratory/relay";

  export default {
    props:{
      pageType:{},
      queryParams:{}
    },
    components: { Treeselect },
    name: "powerControl",
    data() {
      return {
        tableButtonType:this.hasPermiDom(['laboratory:hardware:query','laboratory:hardware:edit','laboratory:hardware:remove']),
        index:'',
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 硬件表格数据
        hardwareList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 部门树选项
        deptOptions: [],
        subjectOptions: undefined,
        isUpdate:false,
        // 表单参数
        form: {
          hardwareType:1,
        },
        // 表单校验
        rules: {
            name: [
              { required: true, message: "请输入硬件名称", trigger: "blur" },
              { required: true, message: "请输入硬件名称", validator: this.spaceJudgment, trigger: "blur" }
            ],
            type: [
                { required: true, message: "请选择硬件类型", trigger: "blur" }
            ],
            subjectId:[
                { required: true, message: "请选择实验室", trigger: "blur" },
            ]
        },
        hardTypeOptions:{},
        labListOptions:{},
        //  关联实验室弹窗开关
        drawer:false,
        drawerData:{
          name:"甲烷检测实验室",
          text:"描述内容描述内容描述内容描述内容描述内容描述内容描述内容描述内容描述内容描述内容",
          img:"",
        },
        mapData:{
          widthData:"60",
          heightData:"123",
          list:[
            {
              id: "",
              top:0,
              left:0
            }
          ]
        },
        mapList:[],
        // 继电器
        relayList: [],
        relayNumList:[
          {name:1},
          {name:2},
          {name:3},
          {name:4},
          {name:5},
          {name:6},
          {name:7},
          {name:8},
          {name:9},
          {name:10},
          {name:11},
          {name:12}
        ],
        hardwardTypeList:[
          {value:1,label:"老继电器"},
          {value:2,label:"新继电器"}
        ],
        mtopic:"lab/hardware/data",
        //mqtt发送id数组
        mqttIdList:[],
      };
    },
    created() {
      this.getList();
      this.getDeptList();
    },
    methods: {
      radioChange(){
        let self = this;
        self.relayNumList=[];
        let num = 12;
        if(this.form.hardwareType==2){
          let list = [];
          for(let i=0;i<num;i++){
            let obj = {
              name:i+1
            }
            list.push(obj);
          }
          self.relayNumList = list;
        }
      },
      // 开启关闭验证
      async changeIsNeedCaptcha (row) {
        let self = this;
        if(row.isPcfire!=1){
          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.switchChange(row)
          }).catch(() => {

          })
        }

      },
      //开关按钮
      switchChange(row){
        let switchData = {
          id:row.id,
          switchVal:row.status==3?'close':(row.status==4?'open':'')
        };
        hardWareControl(switchData).then(response => {
          console.log(response.data);
          if(response.code==200){
            row.status = row.status==3?4:(row.status==4?3:'')
          }
        });
      },
      //删除
      delBox(item){
        console.log(item)
      },
      moveClick(index){
        this.moveIndex = index
        console.log(",index",index)
      },
      //锚点拖动
      move(e){
        let odiv = e.target;        //获取目标元素
        //算出鼠标相对元素的位置
        let disX = e.clientX - odiv.offsetLeft;
        let disY = e.clientY - odiv.offsetTop;
        document.onmousemove = (e)=>{       //鼠标按下并移动的事件
          //用鼠标的位置减去鼠标相对元素的位置，得到元素的位置
          let left = e.clientX - disX;
          let top = e.clientY - disY;
          //绑定元素位置到positionX和positionY上面
          //移动当前元素
          if(left>0&&left<(this.mapData.widthData*3-60)){
            odiv.style.left = left + 'px';
            this.mapData.list[this.moveIndex].left = left;
            this.mapData.list[this.moveIndex].minLeft = parseInt(left/6);
          }
          if(top>0&&top<(this.mapData.heightData*3-60)){
            odiv.style.top = top + 'px';
            this.mapData.list[this.moveIndex].top = top;
            this.mapData.list[this.moveIndex].minTop = parseInt(top/6);
          }
        };
        document.onmouseup = (e) => {
          document.onmousemove = null;
          document.onmouseup = null;
        };
      },
      getHardTypeList(){
          queryHardwareType().then(response => {
            if(response.code==200){
                this.hardTypeOptions=response.data;
            }
            console.log(this.hardTypeOptions)
        });
      },
      //关联实验室弹窗
      drawerBoxOnTwo(){
        this.drawerTwo = true;
      },
      //关联实验室弹窗
      drawerBoxOn(){
        this.drawer = true;
      },
      //关闭弹窗
      offDrawer(){
        this.$refs.drawer.closeDrawer();
      },
      //弹窗关闭前回调
      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
      },
      //更多选项
      moreClick(item){
        if(item.command == 1){
          this.handleUpdate(item.row)
        }else if(item.command == 2){
          this.handleDelete(item.row)
        }
      },
      getLabList(){
          subjectDictList().then(response => {
              console.log(response)
              if(response.code==200){
                  this.labListOptions=response.data;
              }
              console.log(this.labListOptions)
          });
      },
      /** 查询硬件列表 */
      getList() {
        this.offMQTT();
        this.loading = true;
        this.queryParams.type = this.pageType;
        listHardware(this.queryParams).then(response => {
          this.hardwareList = response.rows;
          this.total = response.total;
          this.loading = false;
          //处理实验室id
          let list = [];
          for(let i=0;i<response.rows.length;i++){
            let num = 0;
            for(let o=0;o<list.length;o++){
              if(response.rows[i].subjectId == list){
                num++
              }
            }
            if(num == 0){
              list.push(response.rows[i].subjectId)
            }
          }
          this.$set(this,'mqttIdList',list);
          this.subscriptionMQTT();
        });
      },
      //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("连接成功");
          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.on("message", (topic, message) => {
          if (message){
            let data = JSON.parse(message)
            // this.getStatistics();
            for(let i=0;i<data.data.length;i++){
              for(let o=0;o<self.hardwareList.length;o++){
                if(data.data[i].num == self.hardwareList[o].id){
                  if (data.data[i].hardwareOperate == 'CLOSE') {
                    self.$set(self.hardwareList[o],'status',4);
                  } else if (data.data[i].hardwareOperate == 'OPEN') {
                    self.$set(self.hardwareList[o],'status',3);
                  } else if (data.data[i].hardwareOperate == 'OFFLINE') {
                    self.$set(self.hardwareList[o],'status',0);
                  }
                }
              }
            }
          }
        });
      },
      // 查询继电器列表
      getRelayList(){
        listRelay({"type": 1}).then(response => {
          this.relayList = response.data;
          if(this.form.relayCode){
            let self = this
            let num = ""
            for(let i=0;i<self.relayList.length;i++){
              if(self.relayList[i].code == this.form.relayCode){
                num = self.relayList[i].routeNum
              }
            }
            let list = [];
            for(let i=0;i<num;i++){
              let obj = {
                name:i+1
              }
              list.push(obj);
            }
            this.relayNumList = list;
          }
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      //清空按钮
      loadClear(){
        this.form.bit = '';
      },
      loadRelayNum(e){
        let self = this;
        let num = ""
        for(let i=0;i<self.relayList.length;i++){
          if(self.relayList[i].code == e){
            num = self.relayList[i].routeNum
          }
        }
        let list = [];
        for(let i=0;i<num;i++){
          let obj = {
            name:i+1
          }
          list.push(obj);
        }
        this.relayNumList = list;
      },
      loadHardware(){
        let self = this;
        this.mapList = [];
        let newId = this.mapData.list[0].id;
        // this.mapData.list = [];
        let queryParam = {};
        if(this.form.id){
          queryParam.id = this.form.id;
        }else{
          queryParam.id = -1;
        }
        queryParam.subjectId = this.form.subjectId;
        getHardwareDetail(queryParam).then(response => {
          let subHardList = response.data.subjectHardPosiList;
          for(var i=0;i<subHardList.length;i++){
            if(response.data.subjectHardPosiList[i].id!=newId){
              this.mapList.push({"name":response.data.subjectHardPosiList[i].hardName,"y":(response.data.subjectHardPosiList[i].horizontalAxis/3).toFixed(0),"x":(response.data.subjectHardPosiList[i].verticalAxis/3).toFixed(0)});
            }
          }
          this.$forceUpdate()
        });

        getSubjectLayout(this.form.subjectId).then(response => {
          if(response.data){
            this.mapData.widthData = response.data.layWidth;
            this.mapData.heightData = response.data.layHeight;
          }else{
            this.mapData.widthData = 60;
            this.mapData.heightData = 123;
          }
          this.$forceUpdate()
        });

        let obj = JSON.parse(JSON.stringify(this.mapData.list[0]));
        obj.x = 0;
        obj.y = 0;
        obj.top = 0;
        obj.left = 0;
        this.mapData.list.splice(0,1);
        setTimeout(function(){
          self.mapData.list.push(obj);
        },50);
        this.$forceUpdate()
      },
      /** 查询实验室字典列表 */
      getSubjectDictList (deptId) {
        this.subjectOptions = null;
        this.loading = true;
        // this.queryParams.deptId = deptId;
        let params = {};
        params.deptId = deptId;
        this.queryParams.subjectId = "";
        subjectDictList(params).then(response => {
          this.subjectOptions = response.data;
          this.loading = false;
        });
      },
      /** 查询学院列表 */
      getDeptList() {
        listDepartments().then(response => {
          this.$set(this, 'deptOptions', response.data)
        });
      },
      // 筛选节点
      filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },
      // 节点单击事件
      handleNodeClick(data) {
        this.queryParams.deptId = data;
        // console.log("data",data);
        this.getSubjectDictList(data);
        // this.getList();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          name: null,
          factory: null,
          type: null,
          macAdd: null,
          subjectId: null,
          deptId: null,
          deptName: null,
          operate: 0,
          createTime: null,
          userId: null,
          createBy: null,
          updateTime: null,
          updateBy: null,
          remark: null,
          isPcfire: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        // this.reset();
        // this.open = true;
        // this.title = "添加硬件";
        // this.getHardTypeList();
        // this.getLabList();
        // this.form.type=this.pageType;
        this.reset();
        this.mapList = []
        this.mapData.list = [{
          id: "",
          top:0,
          left:0
        }];
        this.isUpdate=true;
        this.form.hardwareType=1;
        this.form.isPcfire=0;
        this.form.type=this.pageType;
        this.drawer = true;
        this.title = "添加硬件";
        this.getHardTypeList();
        this.getLabList();
        this.getRelayList();
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        this.mapList = [];
        this.mapData.list = [];
        this.isUpdate=true;
        this.form.type=this.pageType;
        this.getHardTypeList();
        this.getLabList();
        const id = row.id || this.ids
        let queryParam = {};
        queryParam.id = id;
        queryParam.subjectId = row.subjectId;
        getHardwareDetail(queryParam).then(response => {
          this.form = response.data;
          this.$forceUpdate;
          this.getRelayList()
          this.title = "修改硬件";
          this.drawer = true;
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.form.hardwarePosition={
          horizontalAxis:'',
          verticalAxis:''
        }
        this.form.type=this.pageType;
        // this.form.hardwarePosition.horizontalAxis=this.mapData.list[0].top;
        // this.form.hardwarePosition.verticalAxis=this.mapData.list[0].left;
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateHardware(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.drawer = false;
                this.getList();
              });
            } else {
              addHardware(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.drawer = false;
                this.getList();
              });
            }

          }
        });
        // this.$refs["form"].validate(valid => {
        //   if (valid) {
        //     if (this.form.id != null) {
        //       updateHardware(this.form).then(response => {
        //         this.msgSuccess("修改成功");
        //         this.open = false;
        //         this.getList();
        //       });
        //     } else {
        //       console.log("this.form",this.form)
        //       addHardware(this.form).then(response => {
        //         this.msgSuccess("新增成功");
        //         this.open = false;
        //         this.getList();
        //       });
        //     }
        //   }
        // });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$confirm('是否确认删除硬件?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delHardware(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('laboratory/hardware/export', {
          ...this.queryParams
        }, `laboratory_hardware.xlsx`)
      },
      //取消订阅关闭MQTT连接
      offMQTT(){
        let self = this;
        if (self.mqttIdList[0]) {
          for (let i = 0; i < self.mqttIdList.length; i++) {
            self.client.unsubscribe(this.mtopic + self.mqttIdList[i], error => {
              if (error) {
                console.log('Unsubscribe error', error)
              }
            })
          }
          self.client.end();
          self.client = {};
        }
      },
    },
    beforeDestroy() {
      //清除定时器
      let self = this;
      self.offMQTT();
      console.log("beforeDestroy");
    },
  };
</script>

<style scoped lang="scss">
  .powerControl{
    flex: 1;
    display: flex!important;
    flex-direction: column;
    padding:20px!important;
    overflow: hidden;
    .form-box{
    }
    .button-box{
      width:90px;
      display: flex;
    }
  }
</style>
