<!--白名单新增-->
<template>
  <div class="page-container add-whitelist">
    <div class="page-top-title-box">
      <p class="page-top-title-name-p">{{pageData.whiteId?'编辑':'新增'}}准入白名单</p>
      <p class="page-top-title-out-p" @click="backPage">返回</p>
      <p class="page-top-title-submit-p" @click="upButton">提交</p>
    </div>
    <div class="form-max-box">
      <div class="left-max-box">
        <el-form :model="form" ref="drawerForm" :rules="rules" >
          <el-form-item label="姓名" prop="userIds">
            <el-select
              :disabled="isEdit"
              v-model="form.userIds"
              filterable
              remote
              reserve-keyword
              placeholder="请输入姓名"
              :remote-method="userSelectList"
              @change="selectChange"
              clearable>
              <el-option
                v-for="item in optionsUser"
                :key="item.userId"
                :label="item.userName"
                :value="item.userId">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div class="for-max-box scrollbar-box">
          <div class="for-box" v-for="(item,index) in userList" :key="index">
            <div class="for-min-box">
              <p>{{item.deptName ? item.deptName+'-'+item.userName:item.userName}}</p>
              <img src="@/assets/ZDimages/secureAccess/off.png" @click="delItem(index)" v-if="!isEdit">
            </div>
          </div>
        </div>
      </div>
      <div class="right-max-box">
        <div class="right-table-button-box">
          <p class="right-table-button-null-p"></p>
          <p class="page-add-common-style-button" style="width: 150px" @click="newAdmittance">新增准入实验室</p>
        </div>
        <el-table class="table-box" border v-loading="loading" :data="subjectList" :row-key="getRowKeys">
          <el-table-column label="申请实验室" align="left" prop="subName" />
          <el-table-column label="楼栋" align="left" prop="buildName" />
          <el-table-column label="楼层" align="left" prop="floorName" />
          <el-table-column label="学院" align="left" prop="deptName" />
          <el-table-column label="实验室负责人" align="left" prop="adminName" />
          <el-table-column label="安全分级" align="left" prop="levelName" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <div class="table-button-box">
                <p class="table-button-null"></p>
                <p class="table-button-p"  @click="handleClick(scope.$index, scope.row,'delete')" >删除</p>
                <p class="table-button-null"></p>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <!--关联实验室弹框-->
    <el-dialog title='新增准入实验室' @close="handleClose" :visible.sync="dialogVisible" width="80%"
               class="whiteListAdd-dialog" :close-on-click-modal="false" append-to-body :close-on-press-escape="false">
      <div class="whiteListAdd-dialog-box">
        <div class="page-form-title-box" style="border-bottom:none;">
          <el-form :model="dialogForm" ref="dialogForm" :inline="true" label-width="140px">
            <el-form-item label="" prop="subName" >
              <el-input
                v-model="dialogForm.subName"
                placeholder="请输入实验室名称"
                clearable
                size="small"
              />
            </el-form-item>
            <el-form-item label="" prop="buildId">
              <el-select v-model="dialogForm.buildId" placeholder="请选择楼栋" @change="(e)=>systemBuildingGetOptList(3,e)">
                <el-option v-for="(item,index) in buildsDataList" :key="index" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="" prop="floorId">
              <el-select v-model="dialogForm.floorId" placeholder="请选择楼层" >
                <el-option
                  v-for="dict in floorList"
                  :key="dict.id"
                  :label="dict.name"
                  :value="dict.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <p class="page-inquire-common-style-button" @click="onSearch">查询</p>
            <p class="page-reset-common-style-button" @click="resetForm">重置</p>
          </el-form>
        </div>
        <div class="page-content-box">
          <div class="btn_list">
            <i class="el-icon-warning"></i>
            <i>已选择 {{whiteJoinSubList.length}} 项</i>
            <i @click="toggleSelection(dialogTable)">全选本页</i>
            <!--        <i>选择全部</i>-->
            <i></i>
            <i @click="toggleSelection()">清除选项</i>
            <!--<div class="bottom-button-box">-->
              <!--<el-button class="color_99" @click="closeDialog(1)">关闭</el-button>-->
              <!--<el-button class="color_ff back_one" @click="closeDialog(2)">提交</el-button>-->
            <!--</div>-->
          </div>
          <el-table class="table-box" ref="multipleTable" border tooltip-effect="dark" :row-key="getRowKeys" :data="dialogTable"
                    highlight-current-row @selection-change="handleSelectionChange" style="cursor: pointer;height:500px;">
            <el-table-column type="selection"  width="55" :reserve-selection="true" align="center"></el-table-column>
            <el-table-column label="申请实验室名称" show-overflow-tooltip align="left" prop="subName"/>
            <el-table-column label="楼栋" align="left" prop="buildName" />
            <el-table-column label="楼层" align="left" prop="floorName" />
            <el-table-column label="学院" align="left" prop="deptName" />
            <el-table-column label="实验室负责人" align="left" prop="adminName" />
            <el-table-column label="安全分级" align="left" prop="levelName" >
              <template slot-scope="scope">
                <span :style="'color:'+scope.row.fiedColor+';'">{{scope.row.levelName}}</span>
              </template>
            </el-table-column>

          </el-table>
          <pagination :page-sizes="[20, 30, 40, 50]"
                      v-show="total>0"
                      :total="total"
                      :page.sync="dialogForm.page"
                      :limit.sync="dialogForm.pageSize"
                      @pagination="getUserRoleBySub"
          />
        </div>
      </div>
      <div slot="footer" class="dialog-footer dialog-footer-box">
        <p class="dialog-footer-button-null"></p>
        <p class="dialog-footer-button-info" @click="closeDialog(1)">取消</p>
        <p class="dialog-footer-button-primary" @click="closeDialog(2)">提交</p>
        <p class="dialog-footer-button-null"></p>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { laboratorySubRelInfoSelectUserBySubPage,systemBuildingGetOptList } from "@/api/commonality/permission";
import { laboratoryWhiteAdd,laboratoryWhiteEditWhiteBySubJoin,laboratoryWhiteSelectUserByNotWhite,laboratoryWhiteDetail,laboratoryWhiteSubList } from "@/api/secureAccess/index";

export default {
  name: "add-whitelist",
  props:{
    pageData:{},
  },
  data() {
    return {
      isEdit:false,
      form:{},
      loading:false,
      // 表单校验
      rules: {
        userIds: [
          { required: true, message: "请输入标题", trigger: "blur" },
          { required: true, message: "请输入标题", validator: this.spaceJudgment, trigger: "blur" }
        ],
      },
      //展示数组
      userList:[],
      //搜索角色数组
      optionsUser:[],
      queryParams:{
        page:1,
        pageSize:20,
      },
      total:0,
      subjectList:[],
      dialogVisible:false,
      dialogForm:{
        page: 1,
        pageSize:20,
        subName: null,
        buildId: null,
        floorId: null,
        whiteUserId:null,
      },
      dialogTable:[],
      buildsDataList:[],
      floorList:[],
      whiteJoinSubList:[],
      arr:[],
      labWhiteJoinSubList:[],

    };
  },
  created() {
    if(this.pageData.whiteId){
      this.isEdit=true;
      this.laboratoryWhiteDetail();
      this.laboratoryWhiteSubList();
      this.dialogForm.whiteUserId=this.pageData.userId;
      this.getUserRoleBySub();
    }else{
      this.isEdit=false;
      this.getUserRoleBySub();
    }
    this.systemBuildingGetOptList(2);
  },
  methods: {
    getRowKeys(row) {
      return row.subId;   //指定row-key的一个标识
    },
    //关闭实验室弹窗
    closeDialog(type){
      if(type == 1){
        this.dialogVisible=false;
      }else if(type == 2){
        let list = [];
        this.labWhiteJoinSubList.forEach((item1)=>{
          let num = 0;
          this.labWhiteJoinSubList.forEach((item2)=>{
            if(item1.subId == item2.subId){
              num++
            }
          })
          if(num == 1){
            list.push(item1)
          }
        })
        this.$set(this,'subjectList',list);
        // this.subjectList = JSON.parse(JSON.stringify(this.labWhiteJoinSubList));
        this.dialogVisible=false;
      }
    },
    //监听关联记录弹窗关闭
    handleClose(){

    },
    //取消选中
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row,true);
        });

      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    //选中实验室
    handleSelectionChange(val){
      this.$set(this,'labWhiteJoinSubList',JSON.parse(JSON.stringify(val)));
      this.$set(this,'arr',JSON.parse(JSON.stringify(val)));
    },
    //查询
    onSearch() {
      this.dialogForm.page = 1;
      this.getUserRoleBySub();
    },
    //重置
    resetForm() {
      this.dialogForm.subName = '';
      this.dialogForm.floorId = '';
      this.dialogForm.buildId = '';
      this.floorList=[];
      this.onSearch();
    },
    //新增准入实验室
    newAdmittance(){
      let _this=this;
      this.dialogVisible=true;
      if(_this.subjectList[0]){
        setTimeout(function(){
          _this.$refs.multipleTable.clearSelection();
          _this.subjectList.forEach(row => {
            _this.$refs.multipleTable.toggleRowSelection(row,true);
          });
          _this.getUserRoleBySub();
        },100);
      }else{
        if(_this.$refs.multipleTable){
          _this.$refs.multipleTable.clearSelection();
        }
      }
    },
    //编辑查询人员信息
    laboratoryWhiteDetail(){
      laboratoryWhiteDetail({whiteId:this.pageData.whiteId}).then(response => {
        let data=response.data;
        if(data.userId){
          this.$set(this.form,'userIds',data.userName)
          this.userSelectList(data.userName);
          let obj = {
            deptId:data.deptId,
            deptName:data.deptName,
            userId:data.userId,
            userName:data.userName,
            userNumber:data.userName,
            userTelephone:data.phonenumber,
            userType:data.userType,
          }
          this.userList.push(obj);
        }
      });
    },
    //编辑-查询实验室信息
    laboratoryWhiteSubList(){
      laboratoryWhiteSubList({userId:this.pageData.userId}).then(response => {
        if(response.code==200){
          this.$set(this,'subjectList',response.data);
        }
      });
    },
    /** 查询实验室列表 */
    getUserRoleBySub() {
      this.loading = true;
      let _this=this;
      laboratorySubRelInfoSelectUserBySubPage(this.dialogForm).then(response => {
        if(response.code==200){
          this.$set(this,'dialogTable',response.data.records);
          this.$set(this,'total',response.data.total);
          this.loading = false;
          if(_this.arr.length==0){
            _this.dialogTable.forEach(function (item,index){
              _this.subjectList.forEach(function (item2,index2){
                if(item.subId==item2.subId){
                  _this.arr.push(item)
                  if(_this.$refs.multipleTable){
                    _this.$nextTick(() => {
                      _this.$refs.multipleTable.toggleRowSelection(item,true);
                    })
                  }
                }
              })
            })
          }else{
            _this.dialogTable.forEach(function (item,index){
              _this.arr.forEach(function (item2,index2){
                if(item.subId==item2.subId){
                  if(_this.$refs.multipleTable){
                    _this.$nextTick(() => {
                      _this.$refs.multipleTable.toggleRowSelection(item,true);
                    })
                  }

                }
              })
            })
          }
        }
      });
    },
    // 提交按钮
    upButton(){
      let self = this;
      if(!this.userList[0]){
        this.msgError("请先添加人员")
        return
      }
      this.$confirm('是否确认提交?', "", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        if(self.pageData.whiteId){
          self.laboratoryWhiteEditWhiteBySubJoin();
        }else{
          self.laboratoryWhiteAdd();
        }
      }).then(() => {}).catch(() => {});
    },
    //新增提交
    laboratoryWhiteAdd(){
      let self = this;
      let whiteJoinSubList=[];
      self.subjectList.forEach(function (item,index){
        whiteJoinSubList.push({'subId':item.subId})
      })
      let obj = {
        whiteModelList:self.userList,
        whiteJoinSubList:whiteJoinSubList
      }
      laboratoryWhiteAdd(obj).then(response => {
        if(response.code==200){
          self.msgSuccess("操作成功")
          self.backPage();
        }else if(response.code==205){
          self.$confirm(response.message, "警告", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(() => {
            //  确定
            self.$router.push({ path: '/comprehensive/laboratoryManagement/accessAuthorization' });
          }).catch(function() {
            //  取消
            self.backPage();
          });
        }
      });
    },
    //编辑提交
    laboratoryWhiteEditWhiteBySubJoin(){
      let whiteJoinSubList=[];
      //循环取出实验室id
      this.subjectList.forEach(function (item,index){
        whiteJoinSubList.push({'subId':item.subId})
      })
      let obj = {
        whiteUserId:this.userList[0].userId,
        labWhiteJoinsubModelList:whiteJoinSubList
      }
      laboratoryWhiteEditWhiteBySubJoin(obj).then(response => {
        this.msgSuccess("操作成功")
        this.backPage();
      });
    },
    handleClick(index, row, doType){
      let _this=this;
      if(doType == 'delete'){//定制预案
        this.$confirm('是否确认删除?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          if(_this.$refs.multipleTable){
            _this.$refs.multipleTable.toggleRowSelection(row,false);
          }
          let index = this.subjectList.indexOf(row);
          if(index!=-1){
            this.subjectList.splice(index,1);
            return
          }
          _this.arr=[];
          _this.subjectList.forEach(function (item,index){
            _this.dialogTable.forEach(function (item2,index2){
              if(item.subId==item2.subId){
                _this.arr.push(item2)
              }else{
              }
            })
          })
          this.msgSuccess("删除成功");
        }).catch(() => {

        });
      }
    },
    //删除
    delItem(index){
      this.userList.splice(index,1);
    },
    //新增
    selectChange(id){
      let self = this;
      for(let o=0;o<self.optionsUser.length;o++){
        if( id == self.optionsUser[o].userId){
          let num = 0;
          for(let s=0;s<self.userList.length;s++){
            if(self.userList[s].userId == self.optionsUser[o].userId){
              num++
            }
          }
          if(num == 0){
            let obj = {
              deptId:self.optionsUser[o].deptId,
              deptName:self.optionsUser[o].deptName,
              userId:self.optionsUser[o].userId,
              userName:self.optionsUser[o].userName,
              userNumber:self.optionsUser[o].account,
              userTelephone:self.optionsUser[o].mobile,
              userType:self.optionsUser[o].userType,
            }
            self.userList.push(obj);
          }else{
            self.msgError(self.optionsUser[o].userName+'已在列表中')
          }
        }
      }
    },
    //返回
    backPage(){
      this.$parent.pageClick(1);
    },
    //数据懒加载
    userSelectList(query) {
      if (query !== '' && query.length>1) {
        this.loading = true;
        laboratoryWhiteSelectUserByNotWhite({userName:query}).then(response => {
          this.$set(this,'optionsUser',response.data);
          this.loading = false;
        });
      } else {
        this.optionsUser = [];
      }
    },
    //查询楼栋/楼层数据
    systemBuildingGetOptList(type,id){
      systemBuildingGetOptList({type:type}).then(response => {
        if(type == 2){
          this.$set(this,'buildsDataList',response.data);
        }else if(type == 3){
          this.$set(this,'floorList',response.data);
        }
      })
    },
  }
};
</script>

<style scoped lang="scss">
.add-whitelist {
  .form-max-box{
    flex:1;
    display: flex;
    overflow: hidden;
    .left-max-box{
      display: flex;
      flex-direction: column;
      overflow: hidden;
      width:370px;
      border-right:1px dashed #dedede;
      padding-left:20px;
      margin:20px 0;
      .for-max-box{
        flex: 1;
        margin-left:40px;
        padding-right:20px;
        .for-box{
          border-radius:6px;
          background: rgba(1,131,250,0.2);
          margin:0 0 10px 10px;
          .for-min-box{
            display: flex;
            overflow: hidden;
            p{
              flex:1;
              padding:10px 0 10px 20px;
              margin:0;
              line-height:20px;
              color:#0183FA;
            }
            img{
              width:16px;
              height:16px;
              margin:12px 12px;
              cursor: pointer;
            }
          }
        }
      }
    }
    .right-max-box{
      padding:20px;
      flex:1;
      display: flex;
      flex-direction: column;
      overflow: hidden;
      position: relative;
      .right-table-button-box{
        display: flex;
        margin-bottom:20px;
        .right-table-button-null-p{
          flex:1;
        }
      }
      .right_b{
        margin-top: 80px;
      }
    }
  }
}
</style>
<style lang="scss">
  .whiteListAdd-dialog{
    .el-dialog__body{
      padding:20px;
    }
    .whiteListAdd-dialog-box{
      height:600px;
      display: flex;
      flex-direction: column;
      overflow: hidden;
      .page-form-title-box{
        height:60px;
        padding:0;
      }
      .page-content-box{
        padding:0;
      }
      .btn_list{
        width: 100%;
        height: 40px;
        background: rgba(1,131,250,0.1);
        border-radius: 6px;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        margin-bottom: 20px;
        >i{
          font-style: normal;
          display: inline-block;
          cursor: pointer;
        }
        >i:nth-of-type(1){
          font-size: 20px;
          color: #0045AF;
          margin: 0 16px 0 14px;
        }
        >i:nth-of-type(2){
          font-size: 16px;
          font-family: Source Han Sans CN;
          font-weight: bold;
          color: #999999;
          line-height: 16px;
        }
        >i:nth-of-type(3){
          font-size: 16px;
          font-family: Source Han Sans CN;
          font-weight: bold;
          color: #0045AF;
          line-height: 16px;
          margin: 0 28px 0 46px;
        }
        >i:nth-of-type(4){
          font-size: 16px;
          font-family: Source Han Sans CN;
          font-weight: bold;
          color: #0045AF;
          line-height: 16px;
        }
        >i:nth-of-type(5){
          font-size: 16px;
          font-family: Source Han Sans CN;
          font-weight: bold;
          color: #FFA312;
          line-height: 16px;
          margin: 0 40px 0 28px;
        }
        .bottom-button-box{
          display: flex;
          width:220px;
          margin: 0;
          p{
            font-size:14px;
            height:30px;
            width:100px;
            line-height:30px;
            text-align: center;
            border-radius:4px;
          }
          p:nth-child(1){
            border:1px solid #E0E0E0;
            margin-right:20px;
          }
          p:nth-child(2){
            border:1px solid #0045AF;
          }
        }
      }
    }
  }
</style>
