<template>
  <div class="addSubject scrollbar-box">
    <el-form ref="form" :model="form" label-width="120px" :rules="rules" >
      <div class="title-box">
        <p class="left-title">基本信息</p>
      </div>
      <el-form-item label="实验室名称" prop="name" class="form-item">
        <el-input
          style="width:320px;"
          maxlength="30"
          v-model="form.name"
          placeholder="请输实验室名称"
          clearable
          size="small"
        />
      </el-form-item>

      <el-form-item label="类型"  prop="moldId" class="form-item">
        <el-select v-model="form.moldId" placeholder="请选择类型" clearable style="width:320px;">
          <el-option
            v-for="dict in labMoldList"
            :key="dict.id"
            :label="dict.moldName"
            :value="dict.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="安全分类"  prop="typeId" class="form-item">
        <el-select v-model="form.typeId" placeholder="请选择安全分类" clearable style="width:320px;">
          <el-option
            v-for="dict in typeList"
            :key="dict.id"
            :label="dict.typeName"
            :value="dict.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="安全分级"  prop="level" class="form-item">
        <el-select v-model="form.level" placeholder="请选择安全分级" clearable style="width:320px;">
          <el-option
            v-for="dict in levelList"
            :key="dict.id"
            :label="dict.classifiedName"
            :value="dict.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="学院" prop="deptId" class="form-item">
        <el-select v-model="form.deptId" placeholder="请选择学院" style="width:320px;">
          <el-option
            v-for="dict in deptOptions"
            :key="dict.deptId"
            :label="dict.deptName"
            :value="dict.deptId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="楼栋"  prop="buildId" class="form-item">
        <el-select v-model="form.buildId" placeholder="请选择楼栋"  @change="getFloors" style="width:320px;">
          <el-option
            v-for="dict in buildings"
            :key="dict.id"
            :label="dict.name"
            :value="dict.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="楼层" prop="floorId" class="form-item">
        <el-select v-model="form.floorId"  placeholder="请选择层数" @change="getLayouts" style="width:320px;">
          <el-option
            v-for="dict in floors"
            :key="dict.id"
            :label="dict.name"
            :value="dict.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="房间号" prop="room" class="form-item">
        <el-input
          style="width:320px;"
          maxlength="10"
          v-model="form.room"
          placeholder="请输房间号"
          clearable
          size="small"
        />
      </el-form-item>
      <el-form-item label="准入设备"  class="form-item"  v-if="versionField() != 'xiBeiNongLinDaXue'">
        <el-select v-model="form.hardwareType" placeholder="请选择整改类型" style="width:320px;" @change="hardwareTypeFun()" >
          <el-option label="无"  :value="0" />
          <el-option label="海康智能门禁" :value="1" />
          <el-option label="电子信息牌" :value="2" />
        </el-select>
      </el-form-item>
      <!--<el-form-item label="详细位置" prop="layoutId" class="form-item">-->
        <!--<el-select v-model="form.layoutId"  placeholder="请选择详细位置" style="width:320px;">-->
          <!--<el-option-->
            <!--v-for="dict in layoutLists"-->
            <!--:key="dict.id"-->
            <!--:label="dict.room"-->
            <!--:value="dict.id"-->
          <!--&gt;</el-option>-->
        <!--</el-select>-->
      <!--</el-form-item>-->
      <div class="title-box">
        <p class="left-title">安全信息牌</p>
      </div>
      <div class="bottom-form-box">
        <div class="top-form-box">
          <el-form-item label="实验室负责人" prop="adminId" class="form-item" label-width="180px">
            <el-select
              style="width:500px;"
              v-model="form.adminId"
              filterable
              remote
              clearable
              reserve-keyword
              placeholder="请输入至少2个字符搜索相关人员"
              :remote-method="userSelectList"
              :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>
          <el-form-item label="安全责任人" prop="safeUserId" class="form-item" label-width="180px">
            <el-select
              style="width:500px;"
              v-model="form.safeUserId"
              :multiple-limit="2"
              multiple
              filterable
              remote
              clearable
              reserve-keyword
              placeholder="请输入至少2个字符搜索相关人员"
              :remote-method="userSelectListOne"
              :loading="loading">
              <el-option
                v-for="item in optionsUserOne"
                :key="item.userId"
                :label="item.nickName"
                :value="item.userId">
              </el-option>
            </el-select>
          </el-form-item>
        </div>
        <div class="bottom-form-box">
          <el-form-item v-if="item.publicList.length>0" :label="item.classifyName" prop="safeSigns" class="form-item" v-for="(item,index) in  safetyInfoList" label-width="180px">
            <el-select v-if="item.publicList.length>0" v-model="item.privateList" multiple  placeholder="请选择" style="width:500px;">
              <el-option
                v-for="dict in item.publicList"
                :key="dict.id"
                :label="dict.infoName"
                :value="dict.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </div>
      </div>
      <div class="title-box">
        <p class="left-title">实验室简介</p>
      </div>
      <div class="rich-text">
        <UEditor ref="UEditor" :content="form.details" :min-height="192" />
      </div>

      <div class="bottom-button-box">
        <p class="reset-button-one left-button" @click="backPage">取消</p>
        <p class="inquire-button-one right-button" @click="upData">提交</p>
      </div>
    </el-form>
  </div>
</template>

<script>
    import { listDepartments } from "@/api/system/dept";
    import { listClassifiedAll } from "@/api/laboratory/classified";
    import { listClasstypeAll } from "@/api/laboratory/classtype";
    import { onUselistLayoutByFloorId,onUselistLayoutByFloorIdTwo } from "@/api/laboratory/layout";
    import { buildFloorGetlist } from "@/api/laboratory/building";
    import { selectTeacherList } from "@/api/system/user";
    import { addSubject, getClassifyBySubId, updateSubject } from '@/api/laboratory/subject'
    import { labMoldQueryOption } from "@/api/laboratory/subjectClass";
    export default {
      name: "addSubject",
      props:{
        subjectData:{},
      },
      data() {
        return {
          loading:false,
          levelList:[],
          typeList:[],
          deptOptions:[],
          buildings:[],
          floors:[],
          layoutLists:[],
          optionsUser:[],
          optionsUserOne:[],
          //安全标识
          safetyWarning:[],
          //主要危险类别
          hazardCategory:[],
          //风险防控措施
          riskMeasure:[],
          //灭火要点
          extinguishingKeyPoints:[],
          //安全信息牌列表信息存储
          safetyInfoList:[],
          form:{
            details:"",
            hardwareType:0,
          },
          hardwareTypeTow:0,//临时存储准入设备状态
          // 表单校验
          rules: {
            name:[
              {required: true, message: '请输实验室名称', trigger: 'blur'},
              { required: true, message: "请输实验室名称", validator: this.spaceJudgment, trigger: "blur" }
            ],
            moldId:[
              {required: true, message: '请选择类型', trigger: 'blur'}
            ],
            typeId:[
              {required: true, message: '请选择安全分类', trigger: 'blur'}
            ],
            level:[
              {required: true, message: '请选择安全分级', trigger: 'blur'}
            ],
            deptId:[
              {required: true, message: '请选择学院', trigger: 'blur'}
            ],
            buildId:[
              {required: true, message: '请选择楼栋', trigger: 'blur'}
            ],
            floorId:[
              {required: true, message: '请选择层数', trigger: 'blur'}
            ],
            room:[
              {required: true, message: '请输入房间号', trigger: 'blur'}
            ],
            layoutId:[
              {required: true, message: '请选择详细位置', trigger: 'blur'}
            ],

          },
          labMoldList:[],
        }
      },
      created() {
      },
      mounted(){
        this.getDeptList();
        this.getListClassifiedAll();
        this.getListClasstypeAll();
        this.labMoldQueryOption();

        if(!this.subjectData.id){
          this.getClassifyBySubId();
        }
        //安全标识字典
        this.getDicts("sys_safety_warning").then(response => {
          this.safetyWarning = response.data;
        });
        //主要危险类别
        this.getDicts("sys_hazard_category").then(response => {
          this.hazardCategory = response.data;
        });
        //风险防控措施
        this.getDicts("sys_risk_measure").then(response => {
          this.riskMeasure = response.data;
        });
        //灭火要点
        this.getDicts("sys_extinguishing_key_points").then(response => {
          this.extinguishingKeyPoints = response.data;
        });
        //编辑数据回填
        if(this.subjectData.id){
          this.$set(this.form,'id',this.subjectData.id)
          this.$set(this.form,'name',this.subjectData.name)
          this.$set(this.form,'typeId',this.subjectData.typeId)
          this.$set(this.form,'level',this.subjectData.level)
          this.$set(this.form,'deptId',this.subjectData.deptId)
          this.$set(this.form,'buildId',this.subjectData.buildId)
          this.$set(this.form,'floorId',this.subjectData.floorId)
          this.$set(this.form,'room',this.subjectData.room)
          this.$set(this.form,'hardwareType',this.subjectData.hardwareType==null?0:this.subjectData.hardwareType)
          this.$set(this,'hardwareTypeTow',this.subjectData.hardwareType==null?0:this.subjectData.hardwareType)
          this.$set(this.form,'details',this.subjectData.details)
          this.$refs.UEditor.text=unescape(this.subjectData.details)
          this.$set(this.form,'moldId',this.subjectData.moldId)
          if(this.subjectData.adminId){
            this.$set(this.form,'adminId',this.subjectData.adminId)
            this.userSelectList(this.subjectData.adminName);
          }
          if(this.subjectData.safeSigns){
            this.$set(this.form,'safeSigns',this.subjectData.safeSigns.split(','))
          }
          if(this.subjectData.riskMeasure){
            this.$set(this.form,'riskMeasure',this.subjectData.riskMeasure.split(','))
          }
          if(this.subjectData.hazardCategory){
            this.$set(this.form,'hazardCategory',this.subjectData.hazardCategory.split(','))
          }
          if(this.subjectData.outfire){
            this.$set(this.form,'outfire',this.subjectData.outfire.split(','))
          }
          if(this.subjectData.safeUserId){
            let list = [];
            let safeUserIdList = [];
            let nameList = "";
            if(this.subjectData.safeUserName){
              nameList = this.subjectData.safeUserName.split(",");
            }
            let idList = "";
            if(this.subjectData.safeUserId){
              idList = this.subjectData.safeUserId.split(",");
            }
            for(let i=0;i<nameList.length;i++){
              safeUserIdList.push(parseInt(idList[i]))
              let obj = {
                nickName:nameList[i],
                userId:parseInt(idList[i]),
              };
              list.push(obj)
            }

            this.optionsUserOne = list;
            this.$set(this.form, 'safeUserId', safeUserIdList);
          }
          //安全信息牌
          if(this.subjectData.classifyList){
            //循环取安全信息牌信息
            let list=this.subjectData.classifyList
            for(let i=0;i<list.length;i++){
              let list2=[];
              if(list[i].privateList.length>0){
                for(let b=0;b<list[i].privateList.length;b++){
                  list2.push(list[i].privateList[b].id)
                }
                list[i].privateList=list2
              }
            }
            this.safetyInfoList=list
          }
          //根据学院获取楼栋
          buildFloorGetlist({type:2}).then(response => {
            this.buildings = response.rows;
            //根据楼栋获取层
            buildFloorGetlist({type:3,parentId:this.form.buildId}).then(response=>{
              this.floors = response.rows;
            });
          });
        }else{
          //根据学院获取楼栋
          buildFloorGetlist({type:2}).then(response => {
            this.buildings = response.rows;
          });
        }
      },
      methods:{
        hardwareTypeFun(){
          if(this.hardwareTypeTow==1 && this.subjectData.hKCount>0){
            this.msgError("删除现有准入设备后，才能更改准入设备类型!");
            this.form.hardwareType=this.hardwareTypeTow
          }else if(this.hardwareTypeTow==2 && this.subjectData.cardInfoCount>0){
            this.msgError("删除现有准入设备后，才能更改准入设备类型!");
            this.form.hardwareType=this.hardwareTypeTow
          }else{
            console.log(this.form.hardwareType)
          }
        },
        //获取实验室类型列表
        labMoldQueryOption(){
          labMoldQueryOption({}).then(response => {
            this.$set(this,'labMoldList',response.data);
          });
        },
        upData(){
          let self = this;
          this.$set(this.form,'details',this.$refs.UEditor.text);
          this.$refs["form"].validate(valid => {
            if (valid) {
              self.$confirm('是否确认提交?', "", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
              }).then(function() {
                if(self.form.hazardCategory) {
                  self.form.hazardCategory = self.form.hazardCategory.join() ;
                }
                if(self.form.outfire) {
                  self.form.outfire = self.form.outfire.join() ;
                }
                if(self.form.riskMeasure) {
                  self.form.riskMeasure = self.form.riskMeasure.join() ;
                }
                if(self.form.safeSigns) {
                  self.form.safeSigns = self.form.safeSigns.join() ;
                }
                if(self.form.safeUserId) {
                  self.form.safeUserId = self.form.safeUserId.join() ;
                }
                //循环取安全信息牌信息

                let list=[]
                for(let i=0;i<self.safetyInfoList.length;i++){
                  let list2=[];
                  if(self.safetyInfoList[i].privateList && self.safetyInfoList[i].privateList.length>0){
                    for(let b=0;b<self.safetyInfoList[i].privateList.length;b++){
                      list2.push({id:self.safetyInfoList[i].privateList[b]})
                    }
                    list.push({id:self.safetyInfoList[i].id,privateDetailList:list2})
                  }
                }
                self.form.classifyList=list
                if(self.form.id){
                  self.updateSubject();
                }else{
                  self.addSubject();
                }

              }).then(() => {}).catch(() => {});
            }
          })
        },
        //新增实验室
        addSubject(){
          this.form.details = escape(this.form.details);
          addSubject(this.form).then(response => {
            this.msgSuccess("新增成功");
            this.$parent.clickPage(1);
          });
        },
        //修改实验室
        updateSubject(){
          this.form.details = escape(this.form.details);
          updateSubject(this.form).then(response => {
            this.msgSuccess("修改成功");
            this.$parent.clickPage(1);
          });
        },
        backPage(){
          this.$parent.clickPage(1);
        },
        /** 查询学院列表 */
        getDeptList() {
          listDepartments().then(response => {
            this.$set(this, 'deptOptions', response.data)
          });
        },
        /** 查询楼栋列表  */
        getBuildings(id) {
          if(id) {
            this.$set(this.form, 'buildId', '');//楼栋
            this.buildings = [];
            this.$set(this.form, 'floorId', '');//楼层
            this.floors = [];
            // this.$set(this.form, 'layoutId', '');//房间
            this.layoutLists = [];
            buildFloorGetlist({type:2}).then(response => {
              this.buildings = response.rows;
            });
          }
        },
        //查询楼层
        getFloors(id) {
          if(id) {
            this.$set(this.form, 'floorId', '');//楼层
            this.floors = [];
            // this.$set(this.form, 'layoutId', '');//房间
            this.layoutLists = [];
            buildFloorGetlist({type:3,parentId:id}).then(response=>{
              this.floors = response.rows;
            });
          }
        },
        //查询布局信息
        getLayouts(id) {
          if(id) {
            // this.$set(this.form, 'layoutId', '');//房间
            this.layoutLists = [];
            onUselistLayoutByFloorId(id).then(response=>{
              this.layoutLists = response.data;
            });
          }
        },
        //获取分级
        getListClassifiedAll(){
          listClassifiedAll().then(response=>{
            if(response.code==200){
              this.levelList = response.data
            }
          })
        },
        //获取分类
        getListClasstypeAll(){
          listClasstypeAll().then(response=>{
            if(response.code==200){
              this.typeList = response.data;
            }
          });
        },
        //获取电子信息牌下拉列表数据
        getClassifyBySubId(){
          getClassifyBySubId().then(response=>{
            if(response.code==200){
              this.safetyInfoList=response.data;
            }
          });
        },
        /** 下列人员-懒加载 */
        userSelectList(query) {
          if (query !== '' && query.length>1) {
            selectTeacherList({"nickName":query}).then(response => {
              this.optionsUser = response.data;
            });
          } else {
            this.optionsUser = [];
          }
        },
        userSelectListOne(query) {
          if (query !== '' && query.length>1) {
            this.userSelectListOne.nickName=query;
            selectTeacherList(this.userSelectListOne).then(response => {
              this.optionsUserOne = response.data;
            });
          } else {
            this.optionsUserOne = [];
          }
        },
      }
    }
</script>

<style scoped lang="scss">
  .addSubject{
    flex:1;
    display: flex;
    flex-direction: column;
    border-radius:10px!important;
    margin:5px 20px 20px 10px!important;
    box-shadow: 0 0 8px 1px rgba(0, 0, 0, 0.1) !important;
    *{
      margin:0;
    }
    .title-box{
      display: flex;
      margin:0 20px 30px;
      border-bottom:1px solid #E0E0E0;
      .left-title{
        flex:1;
        height:80px;
        line-height:80px;
        color:#0045AF;
        font-size:18px;
      }
      .right-button{
        margin:20px 0;
      }
    }
    .form-item{
      display: inline-block;
      overflow: hidden;
      min-height:70px;
    }
    .bottom-form-box{
      //display: flex;
      .left-form-box{
        width:650px;
      }
      .right-form-box{
        width:650px;
      }
      .form-item{
        display: inline-block;
        overflow: hidden;
        min-height:40px;
        margin-bottom:30px;
      }
    }
    .rich-text{
      margin: 20px;
    }
    .bottom-button-box{
      display: flex;
      width:400px;
      margin:10px auto 40px;
      .null-p{
        flex:1;
      }
      .left-button{
        margin-right:20px;
      }
    }
  }
</style>
