<template>
  <div class="smartLock">
    <div class="smartLock-min-page" v-if="pageType == 1">
      <div class="title-box">
        <p>智能锁</p>
        <p class="reset-button-one" @click="backPage"><i class="el-icon-arrow-left"></i>返回</p>
      </div>
      <div class="smartLock-min-page-min">
        <el-form :model="queryParamsData" class="form-box" ref="queryForm" :inline="true">
          <el-form-item label="关键字" prop="searchValue">
            <el-input
              maxLength="30"
              v-model="queryParamsData.searchValue"
              placeholder="设备编号/名称"
              clearable
              size="small"
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item label="设备状态" prop="useStatus">
            <el-select v-model="queryParamsData.operate" clearable placeholder="请选择状态">
              <el-option
                v-for="item in optionsList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <p class="inquire-button-one" @click="handleQuery" style="margin-right:10px;">查询</p>
            <p class="reset-button-one" @click="resetQuery">重置</p>
          </el-form-item>
          <!--<el-form-item style="float: right;">-->
            <!--<el-col :span="1.5" v-hasPermi="['']">-->
              <!--<p class="add-button-one-90"-->
                 <!--@click="pageToggle(4)"-->
              <!--&gt;柜锁设置</p>-->
            <!--</el-col>-->
          <!--</el-form-item>-->
        </el-form>
        <el-table  border :data="tableList" @selection-change="handleSelectionChange" ref="multipleTable" :row-key="getRowKeys">
          <!--<el-table-column type="selection" width="50" align="center"/>-->
          <el-table-column label="智能柜锁编号" align="center" prop="hardwareNum"/>
          <el-table-column label="柜锁名称" align="center" prop="name" width="150"/>
          <el-table-column label="位置" align="center" prop="posi" width="400"/>
          <!--sass后放开-->
          <!--<el-table-column label="设备状态" align="center" prop="status" width="100">-->
            <!--<template slot-scope="scope">{{scope.row.status == 3||scope.row.status == 4?'在线':'离线'}}</template>-->
          <!--</el-table-column>-->
          <el-table-column label="关联时间" align="center" prop="joinCabinetTime" width="160"/>
          <el-table-column label="操作人" align="center" prop="createBy" width="120"/>
          <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width" v-if="tableButtonType">
            <template slot-scope="scope">
              <div class="button-box">
                <p class="table-min-button" v-hasPermi="['chemical:locklog2:list']" @click="pageToggle(3,scope.row)">操作记录</p>
                <el-dropdown @command="moreClick" v-hasPermi="['laboratory:hardware10:edit','laboratory:hardware10: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-hasPermi="['laboratory:hardware10:edit']">编辑</el-dropdown-item>
                    <el-dropdown-item style="margin:0 10px;" :command="{row:scope.row,command:2}" v-hasPermi="['laboratory:hardware10:remove']">删除</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div style="display: flex;height:32px;margin:15px 0;">
          <!--<p style="flex:4;"></p>-->
          <p style="text-align: left;margin:0;line-height:32px;margin-right:20px;font-size:14px;color:#999;">
            <i class="el-icon-warning" style="color:#0183FA;"></i>
            已选择 {{selectedNum}} 项
          </p>
          <div style="flex:5;">
            <pagination :page-sizes="[20, 30, 40, 50]"
              v-show="total>0"
              :total="total"
              style="margin:0;"
              :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize"
              @pagination="getList"
            />
          </div>
        </div>
      </div>
    </div>
    <!--新增/编辑-->
    <el-dialog :title="dialogTitle" :visible.sync="addDialogType" v-if="addDialogType" width="520px" append-to-body class="add-dialog-box">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="智能终端编号：" prop="hardwareNum">
          <el-input v-model="form.hardwareNum" placeholder="最大20个字符，包含大小写字母、数字" onkeyup="value=value.replace(/[^\w\.\/]/ig,'')" maxlength="30" style="width:360px;"/>
        </el-form-item>
        <el-form-item label="智能柜锁名称：" prop="name">
          <el-input v-model="form.name" placeholder="最大10个字符，包含汉字、大小写字母、数字、符号" maxlength="10" style="width:360px;"/>
        </el-form-item>
        <el-form-item label="实验室：" prop="subjectId">
          <el-select
            style="width:360px;"
            v-model="form.subjectId"
            filterable
            remote
            clearable
            @focus="selectFocus"
            reserve-keyword
            @clear="clearClick"
            placeholder="搜索选择实验室"
            :remote-method="getSelectList">
            <el-option
              v-for="item in selectList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="锁柜ID：" prop="lockId">
          <el-input v-model="form.lockId" placeholder="0-253" maxlength="3" style="width:360px;" onkeyup="value=value.replace(/[^\d]/g,'')"/>
        </el-form-item>
        <el-form-item label="摄像头ip：" prop="ipAddress">
          <el-input v-model="form.ipAddress" placeholder="请输入摄像头ip" maxlength="20" style="width:360px;"/>
        </el-form-item>
        <el-form-item label="采集器编号：" prop="relayCode">
          <el-input v-model="form.relayCode" placeholder="请输入采集器编号" maxlength="20" onkeyup="value=value.replace(/[^\w\.\/]/ig,'')" style="width:360px;"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!--柜锁设置-->
    <el-dialog title="柜锁设置" :visible.sync="setUpType" v-if="setUpType" width="520px" append-to-body class="add-dialog-box">
      <el-form ref="setUpForm" :model="setUpForm" :rules="rules" label-width="100px">
        <el-form-item label="操作时长：" prop="operateTime">
          <el-input v-model="setUpForm.operateTime" placeholder="请输入操作时长" min="1" max="999" maxlength="3" style="width:360px;">
            <template slot="append">分钟</template>
          </el-input>
        </el-form-item>
        <p style="font-size:14px;line-height:20px;color:#999;">
          <i class="el-icon-warning" style="color:#FFA312;font-size:16px;margin-left:100px;"></i>
          设置开锁后操作的最大有效时长
        </p>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="setUpFormSubmitForm">确 定</el-button>
        <el-button @click="setUpFormCancel">取 消</el-button>
      </div>
    </el-dialog>
    <!--操作记录-->
    <operation-record v-if="pageType == 3" :operationRecordPropsData="operationRecordPropsData"></operation-record>
  </div>
</template>

<script>
  import { filterDept,getSubList, delHardware, addHardware, updateHardware,setLock,hardwareList } from "@/api/medicUniversity-3_1/index";
  import operationRecord from "./operationRecord.vue"
    export default {
      name: "smartLock",
      props:{
        smartLockPropsData:{},
      },
      components: {
        operationRecord
      },
      data() {
        let digitalJudgment = (rule, value, callback) => {
          if(value>253||value<0){
            return callback(new Error(''));
          }else{
            callback()
          }
        }
        return {
          // table操作按钮校验
          tableButtonType:this.hasPermiDom(['chemical:locklog2:list','laboratory:hardware10:edit','laboratory:hardware10:remove']),
          pageType:1,
          //操作方式
          optionsList:[{id:"ONLINE",name:"在线"},{id:"OFFLINE",name:"离线"}],
          //表格扩展选择器---需要在@selection-change绑定的方法内监控selection数组长度
          selectedNum:0,
          // 选中数组
          ids: [],
          // 非单个禁用
          single: true,
          // 非多个禁用
          multiple: true,
          // 搜索数据
          queryParamsData:{
            pageNum:1,
            pageSize:20,
          },
          // 搜索实际发送数据
          queryParams:{
            pageNum:1,
            pageSize:20,
          },
          tableList:[],
          total:0,
          //锁柜设置
          setUpType:false,
          setUpForm:{},
          rules:{
            hardwareNum: [
              { required: true, trigger: "blur", message: "最大20个字符，包含大小写字母、数字" },
              { required: true, message: "最大20个字符，包含大小写字母、数字", validator: this.spaceJudgment, trigger: "blur" }
            ],
            name: [
              { required: true, trigger: "blur", message: "最大10个字符，包含汉字、大小写字母、数字、符号" },
              { required: true, message: "最大10个字符，包含汉字、大小写字母、数字、符号", validator: this.spaceJudgment, trigger: "blur" }
            ],
            subjectId: [
              { required: true, trigger: "blur", message: "搜索选择实验室" },
            ],
            operateTime: [
              { required: true, trigger: "blur", message: "请输入操作时长" },
              { required: true, message: "请输入操作时长", validator: this.spaceJudgment, trigger: "blur" },
              { required: true, message: "只能输入数字", validator: this.isNum, trigger: "blur" },
            ],
            lockId: [
              { required: true, trigger: "blur", message: "请输入0-253之间的数字" },
              { required: true, message: "请输入0-253之间的数字", validator: this.spaceJudgment, trigger: "blur" },
              { required: true, message: "请输入0-253之间的数字", validator: digitalJudgment, trigger: "blur" }
            ],
            ipAddress: [
              { required: true, trigger: "blur", message: "请输入摄像头ip" },
              { required: true, message: "请输入摄像头ip", validator: this.spaceJudgment, trigger: "blur" }
            ],
            relayCode: [
              { required: true, trigger: "blur", message: "请输入采集器编号" },
              { required: true, message: "请输入采集器编号", validator: this.spaceJudgment, trigger: "blur" }
            ],
          },
          //操作记录传参
          operationRecordPropsData:{},
          //编辑新增相关
          dialogTitle:"",
          addDialogType:false,
          form:{},
          selectList:[],
          selectListData:[],
        }
      },
      created() {

      },
      mounted(){
        this.filterDept();
        this.getList();
      },
      methods:{
        selectFocus(){
          if(!this.selectList[0]){
            this.filterDept();
          }
        },
        getList(){
          this.queryParamsData = JSON.parse(JSON.stringify(this.queryParams));
          this.queryParamsData.joinCabinet = this.smartLockPropsData.id;
          this.queryParamsData.type = "AI_CABINETLOCK";
          hardwareList(this.queryParamsData).then(response => {
            this.selectedNum = 0;
            this.ids = [];
            this.tableList = response.rows;
          });
        },
        /** 搜索按钮操作 */
        handleQuery() {
          this.queryParamsData.pageNum = 1;
          this.queryParamsData.pageSize = 20;
          this.queryParams = JSON.parse(JSON.stringify(this.queryParamsData));
          this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
          this.$set(this,'queryParamsData',{});
          this.$set(this,'queryParams',{});
          this.handleQuery();
        },
        //更多按钮
        moreClick(data){
          let self = this;
          if(data.command == 1){
            this.pageToggle(1,data.row);
          }else if(data.command == 2){
            this.pageToggle(2,data.row);
          }
        },
        pageToggle(type,item){
          let self = this;
          if(type == 0){
            this.pageType = 1;
            this.getList();
          }else if(type == 1){
            // 编辑
            this.dialogTitle = '编辑';
            let obj = {
              id:item.id,
              subjectId:item.subjectId,
              name:item.name,
              hardwareNum:item.hardwareNum,
              lockId:item.lockId,
              ipAddress:item.ipAddress,
              relayCode:item.relayCode,
            };
            this.$set(this,'form',obj);
            this.clearClick();
            this.addDialogType = true;
          }else if(type == 2){
            // 删除
            if(item.joinCabinetId){
              this.msgError('已关联化学品柜,无法删除')
              return
            }
            this.$confirm('确认要删除吗?', "警告", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }).then(function() {
              delHardware(item.id).then(response => {
                if (response.code == 200){
                  self.msgSuccess(response.msg);
                  self.getList();
                }
              });
            }).then(() => {
            }).catch(() => {});
          }else if (type == 3){
            //操作记录
            this.operationRecordPropsData = item;
            this.pageType = 3;
          }else if (type == 4){
            //锁柜设置
            if(self.ids.length>0) {
              this.setUpForm = {
                operateTime:"",
              }
              this.setUpType = true;
            }else{
              this.msgError('请选择要设置的锁柜')
            }
          }
        },
        //查询当前院系
        filterDept(){
          filterDept().then(response => {
            let idText = "";
            for(let i=0;i<response.data.length;i++){
              if(i==0){
                idText = idText + response.data[i].deptId;
              }else{
                idText = idText +','+ response.data[i].deptId;
              }
            }
            //查询院系下实验室
            getSubList(idText).then(response => {
              //当前列表
              this.selectList = JSON.parse(JSON.stringify(response.data));
              //原始列表数据
              this.selectListData = JSON.parse(JSON.stringify(response.data));
            });
          });
        },
        /** 实验室-本地懒加载 */
        getSelectList(val) {
          let self = this;
          let list = [];
          for(let i=0;i<self.selectListData.length;i++){
            if(self.selectListData[i].name.indexOf(val) != -1){
              list.push(self.selectListData[i]);
            }
          }
          this.selectList = JSON.parse(JSON.stringify(list))
        },
        //实验室选中清除
        clearClick(){
          this.selectList = JSON.parse(JSON.stringify(this.selectListData))
        },
        submitForm(){
          this.$refs["form"].validate((valid) => {
            if (valid) {
              if(this.form.id){
                //编辑
                this.form.type = "AI_CABINETLOCK";
                updateHardware(this.form).then(response => {
                  if (response.code == 200){
                    this.addDialogType = false;
                    this.msgSuccess(response.msg);
                    this.getList();
                  }
                });
              }else{
                //新增
                this.form.type = "AI_CABINETLOCK";
                addHardware(this.form).then(response => {
                  if (response.code == 200){
                    this.addDialogType = false;
                    this.msgSuccess(response.msg);
                    this.resetQuery();
                  }
                });
              }
            }
          })
        },
        cancel(){
          this.addDialogType = false;
        },
        //柜锁设置
        setUpFormSubmitForm(){
          this.$refs["setUpForm"].validate((valid) => {
            if (valid) {
              let obj = {
                ids:this.ids,
                operateTime:parseInt(this.setUpForm.operateTime),
              }
              setLock(obj).then(response => {
                if(response.code == 200){
                  this.setUpType = false;
                  this.msgSuccess(response.msg);
                  this.getList();
                }
              });
            }
          })
        },
        setUpFormCancel(){
          this.setUpType = false;
        },
        backPage(){
          this.$parent.pageToggle(1);
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
          this.selectedNum = selection.length;
          this.ids = selection.map(item => item.id);
          this.single = selection.length != 1;
          this.multiple = !selection.length;
        },
        /*===记录勾选数据===
          需要再el-table 添加  :row-key="getRowKeys"
          需要在selection 添加 :reserve-selection="true"
        */
        getRowKeys(row) {
          return row.id
        },
      }
    }
</script>

<style scoped lang="scss">
  .smartLock{
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    p{
      margin:0;
    }
    .button-box{
      display: flex;
    }
    .smartLock-min-page{
      flex: 1;
      display: flex;
      flex-direction: column;
      overflow: hidden;
      .title-box{
        display: flex;
        height:90px;
        border-bottom: 1px solid #D8D8D8;
        p:nth-child(1){
          flex:1;
          font-size:16px;
          line-height:90px;
          margin-left:18px;
          color:#0045AF;
        }
        p:nth-child(2){
          margin:25px 25px 0 0;
        }
      }
      .smartLock-min-page-min{
        flex: 1;
        display: flex;
        flex-direction: column;
        overflow: hidden;
        padding:20px;
      }
    }

  }
</style>
