<!--硬件管理/视频监控-->
<template>
  <div class="videoSurveillance">
    <!--<el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px" class="form-box">-->

      <!--<el-form-item label="学院" prop="deptId">-->
        <!--<el-select v-model="queryParams.deptId" placeholder="请选择学院" clearable @change="handleNodeClick">-->
          <!--<el-option-->
            <!--v-for="dict in deptOptions"-->
            <!--:key="dict.deptId"-->
            <!--:label="dict.deptName"-->
            <!--:value="dict.deptId"-->
          <!--&gt;</el-option>-->
        <!--</el-select>-->
      <!--</el-form-item>-->

      <!--<el-form-item label="实验室" prop="subjectId">-->
        <!--<el-select v-model="queryParams.subjectId" clearable placeholder="请选择实验室">-->
          <!--<el-option-->
            <!--v-for="item in subjectOptions"-->
            <!--:key="item.id"-->
            <!--:label="item.name"-->
            <!--:value="item.id">-->
          <!--</el-option>-->
        <!--</el-select>-->
      <!--</el-form-item>-->

      <!--<el-form-item label="状态" prop="operate">-->
        <!--<el-select v-model="queryParams.operate" placeholder="请选择状态" clearable size="small">-->
          <!--<el-option label="在线" value="ONLINE" />-->
          <!--<el-option label="离线" value="OFFLINE" />-->
          <!--<el-option label="开启" value="OPEN" />-->
          <!--<el-option label="关闭" value="CLOSE" />-->
        <!--</el-select>-->
      <!--</el-form-item>-->
      <!--<el-form-item style="float: right;">-->
        <!--<el-col :span="1.5">-->
          <!--<p class="add-button-one-120"-->
             <!--@click="handleAdd"-->
             <!--v-hasPermi="['laboratory:hardware:add']"-->
          <!--&gt;<i class="el-icon-plus"></i>新增硬件</p>-->
        <!--</el-col>-->
      <!--</el-form-item>-->
      <!--<el-form-item>-->
        <!--<p class="inquire-button-one" @click="handleQuery">查询</p>-->
        <!--<p class="reset-button-one" @click="resetQuery">重置</p>-->
      <!--</el-form-item>-->
    <!--</el-form>-->
    <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="hardwareNum" />
      <el-table-column label="状态" align="left" >
        <template slot-scope="scope">
          <!-- <p :class="'table-type-color-red'">{{'离线'}}</p> -->
          <p :class="scope.row.status==0?'table-type-color-ash':(scope.row.status==2?'table-type-color-green':(!scope.row.status?'table-type-color-red':''))">{{scope.row.status==0?'离线':(scope.row.status==2?'在线':(!scope.row.status?'离线':''))}}</p>
        </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">
            <!--<p class="table-min-button"-->
               <!--@click="handleView(scope.row)"-->
               <!--style="margin-right:20px;"-->
               <!--v-hasPermi="['laboratory:hardware:query']"-->
            <!--&gt;查看</p>-->
            <el-dropdown @command="moreClick" v-hasPermi="['laboratory:hardware:query','laboratory:hardware:edit','laboratory:hardware:remove']">
              <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
                :disabled="disabledType"
                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 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="hardwareNum">
              <el-input
                :disabled="disabledType"
                v-model="form.hardwareNum"
                placeholder="请输入设备编号"
                clearable
                maxlength="30"
                size="small"
              />
            </el-form-item>
            <el-form-item label="实验室" prop="subjectId">
              <el-select v-model="form.subjectId" placeholder="请选择实验室" :disabled="disabledType">
                <el-tooltip class="item" effect="dark" :content="lab.name" placement="top" v-for="lab in labListOptions">
                  <el-option style="max-width: 200px"
                             :key="lab.id"
                             :label="lab.name"
                             :value="lab.id">
                  </el-option>
                </el-tooltip>
              </el-select>
            </el-form-item>
            <el-form-item label="硬件IP" prop="ipAddress">
              <el-input
                :disabled="disabledType"
                v-model="form.ipAddress"
                placeholder="请输入硬件IP"
                clearable
                size="small"
                maxLength="20"
              />
            </el-form-item>

            <!--<el-form-item label="硬件位置" prop="position">-->
              <!--<div class="map-box" :style="'width:'+mapData.widthData*3+'px;height:'+mapData.heightData*3+'px;'">-->
                <!--<div v-for="(item,index1) in mapData.list" v-if="isUpdate"-->
                     <!--:style="'top:'+item.y*3+'px;left:'+item.x*3+'px;'"-->
                     <!--@mouseenter="moveClick(index1)"-->
                     <!--@mousedown="move">-->
                  <!--{{form.name?form.name:'未命名'}}-->
                <!--</div>-->
                <!--<p class="map-p" v-for="(item) in mapList"  :style="'top:'+item.y*3+'px;left:'+item.x*3+'px;'">{{item.name}}</p>-->
              <!--</div>-->
            <!--</el-form-item>-->
          </el-form>
        </div>
        <div class="videoSurveillance-bottom-button-box">
          <p></p>
          <p @click="offDrawer">{{buttonType?'取消':'关闭'}}</p>
          <p @click="submitForm" v-if="buttonType">提交</p>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

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

  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: "videoSurveillance",
    data() {
      return {
        tableButtonType:this.hasPermiDom(['laboratory:hardware:query','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,
        // 查询参数
        // queryParams: {
        //   pageNum: 1,
        //   pageSize:20,
        //   name: null,
        //   factory: null,
        //   type: null,
        //   hardwareNum: null,
        //   subjectId: null,
        //   deptId: null,
        //   deptName: null,
        //   operate: null,
        //   userId: null,
        //   status: null
        // },
        hardTypeOptions:{},
        // 表单参数
        form: {},
        // 表单校验
        rules: {
            name: [
                { required: true, message: "请输入硬件名称", trigger: "blur" },
              { required: true, message: "请输入硬件名称", validator: this.spaceJudgment, trigger: "blur" }
            ],
            type: [
                { required: true, message: "请选择硬件类型", trigger: "blur" }
            ],
            hardwareNum: [
                { required: true, message: "请输入设备编号", trigger: "blur" },
              { required: true, message: "请输入设备编号", validator: this.spaceJudgment, trigger: "blur" }
            ],
            subjectId:[
                { required: true, message: "请选择实验室", trigger: "blur" },
            ],
           ipAddress: [
              { required: true, message: "请输入硬件IP", trigger: "blur" },
              { required: true, message: "请输入硬件IP", validator: this.spaceJudgment, trigger: "blur" }
            ],


            // position: [
            //     { required: true, message: "请选择实验室", trigger: "blur" },
            // ],
        },
        labListOptions:{},
        //  关联实验室弹窗开关
        drawer:false,
        drawerData:{
          name:"甲烷检测实验室",
          text:"描述内容描述内容描述内容描述内容描述内容描述内容描述内容描述内容描述内容描述内容",
          img:"",
        },
        mapData:{
          widthData:"60",
          heightData:"123",
          list:[
            {
              id: "",
              top:0,
              left:0
            }
          ]
        },
        mapList:[],
        buttonType:false,
        disabledType:false,
        // 继电器
        // relayList: [],
        // relayNumList:[],
      };
    },
    created() {
      this.getList();
      this.getDeptList();

    },
    methods: {
      //删除
      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.disabledType = false;
          this.buttonType = true;
          this.handleUpdate(item.row)

        }else if(item.command == 2){
          this.handleDelete(item.row)
        }
      },
      /** 查询实验室字典列表 */
      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;
        });
      },
      // 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()
        // if(this.mapData.list[0]){
        //   console.log("heightData",this.mapData.heightData)
        //   console.log("y",this.mapData.list[0].top)
        //   if(this.mapData.list[0].top-10>this.mapData.heightData){
        //     console.log("heightData",this.mapData.heightData)
        //     console.log("y",this.mapData.list[0].top)
        //     this.mapData.list[0].top = stringify(this.mapData.heightData-10)
        //   }
        //   console.log("heightData",this.mapData.widthData)
        //   console.log("x",this.mapData.list[0].left)
        //   if(this.mapData.list[0].left-10>this.mapData.widthData){
        //     console.log("heightData",this.mapData.widthData)
        //     console.log("x",this.mapData.list[0].left)
        //     this.mapData.list[0].left = stringify(this.mapData.heightData-10)
        //   }
        //   this.$forceUpdate()
        // }
      },
      /** 查询硬件列表 */
      getList() {
        this.loading = true;
        this.queryParams.type = this.pageType;
        console.log("this.queryParams.type",this.queryParams.type)
        listHardware(this.queryParams).then(response => {
          this.hardwareList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      getLabList(){
          subjectDictList().then(response => {
              console.log(response)
              if(response.code==200){
                  this.labListOptions=response.data;
              }
          });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      /** 查询学院列表 */
      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,
          hardwareNum: null,
          subjectId: null,
          deptId: null,
          deptName: null,
          operate: 0,
          createTime: null,
          userId: null,
          createBy: null,
          updateTime: null,
          updateBy: null,
          remark: null,
          hardwarePosition:{
             horizontalAxis:'',
             verticalAxis:''
          },
          mapData:{
            widthData:"60",
            heightData:"123",
            list:[
              {
                id: "",
                top:0,
                left:0
              }
            ]
          },
          mapList:[],
          // 弹窗确定按钮
          buttonType:false,
        };
        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
      },
      //乘法
      accMul(arg1,arg2){
        var m=0,s1=arg1.toString(),s2=arg2.toString();
        try{m+=s1.split(".")[1].length}catch(e){}
        try{m+=s2.split(".")[1].length}catch(e){}
        return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m)
      },
      //加法
      accAdd(arg1,arg2){
        var r1,r2,m;
        try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
        try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
        m=Math.pow(10,Math.max(r1,r2))
        return ((arg1*m+arg2*m)/m).toFixed(0);
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.disabledType = false;
        this.buttonType = true;
        this.mapList = []
        this.mapData.list = [{
          id: "",
          top:0,
          left:0
        }];
        this.isUpdate=true;
        this.form.type=this.pageType;
        this.drawer = true;
        this.title = "添加硬件";
        this.getHardTypeList();
        this.getLabList();
      },
      /** 修改按钮操作 */
      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.title = "修改硬件";
          this.drawer = true;
        });
      },
      /** 查看按钮操作 */
      handleView(row) {
        this.reset();
        this.mapList = [];
        this.mapData.list = [];
        this.disabledType = true;
        this.buttonType = false;
        this.isUpdate=false;
        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;
          let subHardList = response.data.subjectHardPosiList;
          for(var i=0;i<subHardList.length;i++){
            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;
          this.drawer = true;
          this.title = "查看硬件";
        });

        getSubjectLayout(row.subjectId).then(response => {
          this.mapData.widthData = response.data.layWidth;
          this.mapData.heightData = response.data.layHeight;
          this.$forceUpdate;
        });
        // const id = row.id || this.ids
        // getHardware(id).then(response => {
        //   this.form = response.data;
        //   this.open = true;
        //   this.title = "修改硬件";
        // });
      },
      /** 提交按钮 */
      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();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      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`)
      }
    }
  };
</script>

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