<!--白名单新增-->
<template>
  <div class="add-whitelist">
    <div class="top-max-button-title-box">
      <p>新增准入白名单</p>
      <p class="button-p reset-button-one" @click="backPage">返回</p>
    </div>
    <div class="form-max-box">
      <div class="left">
        <el-form :model="form" ref="drawerForm" :rules="rules" >
          <el-form-item label="姓名" prop="userIds" style="margin-top:40px;">
            <el-select
              :disabled="isEdit"
              v-model="form.userIds"
              filterable
              remote
              reserve-keyword
              placeholder="请输入姓名"
              :remote-method="userSelectList"
              @change="selectChange"
              :loading="loading">
              <el-option
                v-for="item in optionsUser"
                :key="item.userId"
                :label="item.nickName"
                :value="item.userId">
              </el-option>
            </el-select>
          </el-form-item>
          <div class="for-max-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/newImages/off.png" @click="delItem(index)" v-if="!isEdit">
              </div>
            </div>
          </div>
          <p class="inquire-button-one" style="margin:100px 50px;" @click="upButton">提交</p>
        </el-form>
      </div>
      <div class="right">
        <div style="text-align: right;margin: 20px;" class="right_t"> <p class="inquire-button-one"  style="width: 150px" @click="newAdmittance">新增准入实验室</p></div>
        <el-table class="right_b" border v-loading="loading" :data="subjectList">
          <el-table-column label="申请实验室" align="left" prop="name" />
          <el-table-column label="楼栋" align="left" prop="building" />
          <el-table-column label="楼层" align="left" prop="buildName" />
          <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="button-box">
                <p class="table-min-button"  @click="handleClick(scope.$index, scope.row,'delete')" ><i class="el-icon-delete"></i>删除</p>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <!--关联实验室弹框-->
    <el-dialog title='新增准入实验室' @close="handleClose" :visible.sync="dialogVisible" width="80%">
      <el-form :model="dialogForm" ref="dialogForm" :inline="true" label-width="140px">
        <el-form-item label="实验室名称" prop="name" >
          <el-input
            v-model="dialogForm.name"
            placeholder="请输入实验室名称"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item label="楼栋" prop="buildId">
          <el-select v-model="dialogForm.buildId" placeholder="请选择楼栋" clearable  @change="buildChange">
            <el-option v-for="(item,index) in buildsDataList" :key="index" :label="item.deptName" :value="item.deptId" />
          </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>

        <el-form-item>
          <p class="inquire-button-one" style="margin-left:20px;" @click="onSearch">查询</p>
          <p class="reset-button-one" style="margin-left:20px;" @click="resetForm">重置</p>
        </el-form-item>
      </el-form>
      <div class="btn_list">
        <i class="el-icon-warning"></i>
        <i>已选择 {{labWhiteJoinSubList.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 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="name"/>
        <el-table-column label="楼栋" align="left" prop="building" />
        <el-table-column label="楼层" align="left" prop="buildName" />
        <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
        v-show="total>0"
        :total="total"
        :page.sync="dialogForm.pageNum"
        :limit.sync="dialogForm.pageSize"
        @pagination="getUserRoleBySub"
      />
<!--      <div class="bottom-button-box" style="padding-top: 20px;text-align: right;">
        <el-button class="color_99" @click="closeDialog()">取消</el-button>
        <el-button class="color_ff back_one" @click="confirmDialog()">确定</el-button>
      </div>-->
    </el-dialog>
  </div>
</template>

<script>
import {
  getAllSubjectByParame,
  selectUserListByName,
  whitelistAddList,
  whitelistEdit, whitelistEditList,
  whitelistList,
  whitelistSubListEdit
} from "@/api/laboratory/whitelist";
  import {listInfo} from "@/api/laboratory/gradeManage";
  import {delPlan, getUserRoleBySub} from "@/api/laboratory/plan";
  import {buildsList} from "@/api/laboratory/sparseHardware";
  import {listFloorByBuildId} from "@/api/laboratory/building";
  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:{
          pageNum:1,
          pageSize: 10,
        },
        total:0,
        subjectList:[],
        dialogVisible:false,
        dialogForm:{
          pageNum: 1,
          pageSize: 10,
          name: null,
          floorId: null,
          whiteUserId:null,

        },
        dialogTable:[],
        buildsDataList:[],
        floorList:[],
        labWhiteJoinSubList:[],
        arr:[],

      };
    },
    created() {
      if(this.pageData.id){
        console.log('编辑')
        this.isEdit=true;
        this.whitelistEdit();
        this.whitelistSubListEdit();
        this.dialogForm.whiteUserId=this.pageData.userId;
        this.getUserRoleBySub();
      }else{
        this.isEdit=false;
        this.getUserRoleBySub();
      }
      this.buildsList();
    },
    methods: {

      getRowKeys(row) {
        return row.subjectId;   //指定row-key的一个标识
      },
      //关闭实验室弹窗
      closeDialog(type){
        if(type == 1){
          this.dialogVisible=false;
        }else if(type == 2){
          this.subjectList = JSON.parse(JSON.stringify(this.labWhiteJoinSubList));
          this.dialogVisible=false;
        }
      },
      //监听关联记录弹窗关闭
      handleClose(){
        console.log('弹窗关闭');
        /*if(this.arr){
          console.log('实验室信息回显')
          this.$nextTick(() => {
            this.arr.forEach(row => {
              this.$refs.multipleTable.toggleRowSelection(row,true);
            });
          })
        }*/
      },
      //取消选中
      toggleSelection(rows) {
        let _this=this;
        if (rows) {
         // this.$refs.multipleTable.clearSelection();
          rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row,true);
            //_this.arr.push(row)
            //_this.subjectList.push(row)
          });

        } else {
          this.$refs.multipleTable.clearSelection();
        }
      },
      //选中实验室
      handleSelectionChange(val){
        console.log(val)
        console.log(this.labWhiteJoinSubList)
        let _this=this;
        this.labWhiteJoinSubList=[];
        this.labWhiteJoinSubList=val;

        // _this.subjectList=this.labWhiteJoinSubList
        _this.arr=this.labWhiteJoinSubList

      },
      //查询楼栋
      buildsList(){
        buildsList().then( response => {
          this.buildsDataList = response.data;
        });
      },
      //选择楼栋
      buildChange(e){
        console.log("选择楼栋",e)
        //根据学院获取楼栋
        listFloorByBuildId(this.dialogForm.buildId).then(response => {
          this.$set(this,'floorList', response.data)
          this.$set(this.form,'floorId', "")
        });
      },
      //查询
      onSearch() {
        this.dialogForm.pageNo = 1;
        this.getUserRoleBySub();
      },
      //重置
      resetForm() {
        this.dialogForm.name = '';
        this.dialogForm.floorId = '';
        this.dialogForm.buildId = '';
        this.onSearch();
      },
      //新增准入实验室
      newAdmittance(){
        let _this=this;
        this.dialogVisible=true;
        if(_this.subjectList[0]){
          setTimeout(function(){
            _this.$refs.multipleTable.clearSelection();
            console.log("============>1")
            _this.subjectList.forEach(row => {
              console.log("============>2")
              _this.$refs.multipleTable.toggleRowSelection(row,true);
            });
            _this.getUserRoleBySub();
          },100);
        }else{
          if(_this.$refs.multipleTable){
            _this.$refs.multipleTable.clearSelection();
          }
        }
        // if(this.arr){
        //   console.log('实验室信息回显')
        //   console.log(this.arr)
        //   if(_this.arr.length==0){
        //     if(_this.$refs.multipleTable){
        //       _this.$refs.multipleTable.clearSelection();
        //     }
        //   }else{
        //     _this.$nextTick(() => {
        //       setTimeout(function(){
        //         console.log("============>1")
        //         _this.subjectList.forEach(row => {
        //           console.log("============>2")
        //           _this.$refs.multipleTable.toggleRowSelection(row,true);
        //         });
        //       },300);
        //     })
        //   }
        // }
      },
      //确认按钮
      confirmDialog(){
          let _this=this;
         /*if(_this.labWhiteJoinSubList){
           _this.subjectList= _this.labWhiteJoinSubList
           _this.arr= _this.labWhiteJoinSubList
           _this.dialogVisible=false;
         }*/
      },
      //编辑查询人员信息
      whitelistEdit(){
        whitelistEdit(this.pageData.id).then(response => {
          let data=response.data;
          console.log(data)
          if(data.userId){
            this.$set(this.form,'userIds',data.userName)
            this.userSelectList(data.userName);
            //this.userList=data
            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);
          }
        });
      },
      //编辑-查询实验室信息
      whitelistSubListEdit(){
        whitelistSubListEdit(this.pageData.userId).then(response => {
          if(response.code==200){
            let data=response.rows;
            this.subjectList=data
          }

        });
      },
      /** 查询实验室列表 */
      getUserRoleBySub() {
        this.loading = true;
        let _this=this;
        getAllSubjectByParame(this.dialogForm).then(response => {
          if(response.code==200){
            this.dialogTable = response.rows;
            this.total = response.total;
            this.loading = false;
            console.log(_this.subjectList)
            console.log(_this.arr)
            if(_this.arr.length==0){
              _this.dialogTable.forEach(function (item,index){
                _this.subjectList.forEach(function (item2,index2){
                  if(item.subjectId==item2.subjectId){
                    _this.arr.push(item)
                    console.log(_this.arr)
                    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.subjectId==item2.subjectId){
                    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() {
            console.log(444444)
            console.log(self.pageData.id)

          if(self.pageData.id){
            console.log('编辑提交')
            self.whitelistEditList();
          }else{
            console.log('新增提交')
            self.whitelistAddList();
          }
        }).then(() => {}).catch(() => {});
      },
      //新增提交
      whitelistAddList(){
        let labWhiteJoinSubList=[];
        this.subjectList.forEach(function (item,index){
          labWhiteJoinSubList.push({'subjectId':item.subjectId})
        })
        let obj = {
          labWhitelist:this.userList,
          labWhiteJoinSubList:labWhiteJoinSubList
        }
        whitelistAddList(obj).then(response => {
          this.msgSuccess("操作成功")
          this.backPage();
        });
      },
      //编辑提交
      whitelistEditList(){
        console.log(this.subjectList)
        let labWhiteJoinSubList=[];
        //循环取出实验室id
        this.subjectList.forEach(function (item,index){
          labWhiteJoinSubList.push({'subjectId':item.subjectId})
        })
        let obj = {
          userId:this.userList[0].userId,
          labWhiteJoinSubList:labWhiteJoinSubList
        }
        whitelistEditList(obj).then(response => {
          this.msgSuccess("操作成功")
          this.backPage();
        });
      },
      handleClick(index, row, doType){
        console.log(this.subjectList)
        let _this=this;
        if(doType == 'delete'){//定制预案
          this.$confirm('是否确认删除?', "警告", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(() => {
            if(_this.$refs.multipleTable){
              _this.$refs.multipleTable.toggleRowSelection(row,false);
            }
            //this.subjectList.splice(this.subjectList.indexOf(row),1);
            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.subjectId==item2.subjectId){
                  _this.arr.push(item2)
                }else{
                }
              })
            })


            this.msgSuccess("删除成功");
          }).catch(() => {
            this.msgInfo("取消成功");
          });
        }
      },
      //删除
      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].nickName,
                userNumber:self.optionsUser[o].userName,
                userTelephone:self.optionsUser[o].phonenumber,
                userType:self.optionsUser[o].userType,
              }
              self.userList.push(obj);
            }else{
              self.msgError(self.optionsUser[o].nickName+'已在列表中')
            }
          }
        }
      },
      //返回
      backPage(){
        this.$parent.pageClick(1);
      },
      //数据懒加载
      userSelectList(query) {
        if (query !== '' && query.length>1) {
          this.loading = true;
          this.userSelectList.nickName=query;
          selectUserListByName(query).then(response => {
            this.optionsUser = response.data;
            this.loading = false;
          });
        } else {
          this.optionsUser = [];
        }
      },
    }
  };
</script>

<style scoped lang="scss">
  .add-whitelist {
    display: flex !important;
    flex-direction: column;
    height: 100%;
    /*box-shadow: 0 0 8px 2px rgba(0, 0, 0, 0.1);*/
    padding:20px 20px 20px!important;
    .top-max-button-title-box{
      display: flex;
      border-bottom:1px solid #E0E0E0;
      p:nth-child(1){
        flex:1;
        font-size:16px;
        color:#0045AF;
      }
      p:nth-child(2){
        margin-right:20px;
      }
    }
    .form-max-box{
      height: 100%;
      display: flex;
      .left{
        width: 24%;
        .for-max-box{
          margin-left:40px;
          .for-box{
            display: inline-block;
            border-radius:6px;
            background: rgba(1,131,250,0.2);
            margin:0 10px 10px;
            .for-min-box{
              display: flex;
              p{
                flex:1;
                padding:0 20px;
                margin:0;
                line-height:40px;
                color:#0183FA;
              }
              img{
                width:16px;
                height:16px;
                margin:12px 12px;
                cursor: pointer;
              }
            }
          }
        }
      }
      .right{
        display: flex;
        width: 76%;
        position: relative;
        .right_t{
          position: absolute;
          right: 20px;
        }
        .right_b{
          margin-top: 80px;
        }
      }

    }
  }
  .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: 32px;
    >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>
