<!--风险预案编辑-->
<template>
  <div class="addPlan">
    <p class="reset-button-one" style="float: right;" @click="backPage"><i class="el-icon-arrow-left"></i>返回</p>
    <p class="plan-title-p color_one">基本信息</p>
    <el-form :model="form" ref="form" :rules="rules" :inline="true" label-width="100px" class="form-box">

      <div class="plan-info-box">
        <el-row >
          <el-form-item label="预案名称:" prop="name">
            <el-input
              v-model="form.name"
              placeholder="请输入预案名称"
              clearable
              size="small"
              maxLength="50"
            />
          </el-form-item>
          <el-form-item label="关联实验室:" v-if="labShow==true">
            <el-input
              v-model="form.labname"
              placeholder="请选择关联实验室"
              clearable
              size="small"
              @focus="labClick()"
            />
          </el-form-item>
          <el-form-item label="同步执行疏散" prop="warehouse">
            <el-radio-group v-model="form.evacuation">
              <el-radio :label='0'>否</el-radio>
              <el-radio :label='1'>是</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-row>
      </div>
      <p class="plan-title-p color_one">启动条件</p>
      <div class="plan-info-box">
        <el-row v-for="(item,index) in form.riskPlanSensorList" :key="index">
          <div >
            <div style="display: inline-block;">
              <el-form-item label="选择传感器" :prop="'riskPlanSensorList.'+ index +'.funNum'" :rules="rules.funNum" style="margin-top: -10px;">
                <el-select v-model="item.funNum" placeholder="请选择传感器" clearable @change="(val)=>selectFunNum(val,index)">
                  <el-option
                    v-for="sensor in sensorList"
                    :key="sensor.funNum"
                    :label="sensor.describe"
                    :value="sensor.funNum"
                  ></el-option>
                </el-select>
              </el-form-item>
            </div>
            <div style="display: inline-block;" class="for-sensor-input">
              <el-form-item label="异常值区间:" style="width: 300px;" :prop="'riskPlanSensorList.'+ index +'.minMonitor'" :rules="rules.minMonitor">
                <el-input
                  type="number"
                  v-model="item.minMonitor"
                  oninput="if(value.length>6)value=value.slice(0,6)"
                  placeholder="请输入异常值"
                  clearable
                  size="small"
                />
              </el-form-item>
              <p style="margin:0; text-align:center;color:#E0E0E0;display:inline-block;margin-right:10px;line-height:40px;">-</p>
              <el-form-item label=""  :prop="'riskPlanSensorList.'+ index +'.maxMonitor'" :rules="rules.maxMonitor">
                <el-input
                  type="number"
                  v-model="item.maxMonitor"
                  placeholder="请输入异常值"
                  oninput="if(value.length>6)value=value.slice(0,6)"
                  clearable
                  size="small"
                  @keyup.focus.native="handleQuery"
                />
              </el-form-item>
              <i class="el-icon-delete" style="margin-left:20px;font-size:20px;color:#999;cursor:pointer;" @click="delSensor(index)"></i>
            </div>
          </div>
        </el-row>
        <p class="add-button-p color_99" @click="addSensor"><i class="el-icon-plus"></i>新增传感器规则</p>
      </div>
      <p class="plan-title-p color_one">执行动作</p>
      <div class="plan-info-box">
        <div v-for="(item,index) in form.riskPlanHardwareList" :key="index">
          <div style="display: inline-block">
            <el-form-item label="选择硬件" style="margin-top:-10px;" :prop="'riskPlanHardwareList.'+ index +'.hardwareType'" :rules="rules.hardwareType">
              <el-select v-model="item.hardwareType" placeholder="请选择硬件" clearable size="small" @change="(val)=>controlTypeList(val,index)">
                <el-option
                  v-for="hardware in hardwareList"
                  :key="hardware.id"
                  :label="hardware.name"
                  :value="hardware.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </div>
          <div style="display: inline-block">
            <el-form-item label="执行操作" :prop="'riskPlanHardwareList.'+ index +'.operate'" :rules="rules.operate">
              <el-select v-model="item.operate" placeholder="请选择执行操作" clearable size="small">
                <el-option
                  v-for="dict in item.controlTypeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="结束操作" :prop="'riskPlanHardwareList.'+ index +'.operate'" :rules="rules.overAct">
              <el-select v-model="item.overAct" placeholder="请选择预案结束操作" clearable size="small">
                <el-option
                  v-for="dict in item.controlTypeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
            <i class="el-icon-delete" style="font-size:20px;color:#999;cursor:pointer;margin:10px 0 0 20px;" @click="delHardware(index)"></i>
          </div>
        </div>
        <p class="add-button-p color_99" @click="addHardware"><i class="el-icon-plus"></i>添加</p>
      </div>
      <div class="bottom-button-box">
        <el-button class="color_99" @click="backPage">取消</el-button>
        <el-button class="color_ff back_one" @click="submitForm">确定</el-button>
      </div>
    </el-form>
    <!--关联实验室弹框-->
    <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="type" >
          <el-select v-model="dialogForm.deptId" placeholder="请选择学院" clearable size="small">
            <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="typeId" class="form-item">
          <el-select v-model="dialogForm.typeId" placeholder="请选择安全分类" clearable >
            <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="dialogForm.level" placeholder="请选择安全分级" clearable >
            <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="name" >
          <el-input
            v-model="dialogForm.adminName"
            placeholder="请输入实验室负责人"
            clearable
            size="small"
          />
        </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>已选择{{labRiskPlanjoinsubList.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()">取消</el-button>
          <el-button class="color_ff back_one" @click="confirmDialog()">确定</el-button>
        </div>
      </div>
      <el-table ref="multipleTable" border  tooltip-effect="dark" :data="dialogTable" highlight-current-row @selection-change="handleSelectionChange" style="cursor: pointer;">
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column label="实验室名称" show-overflow-tooltip align="left" prop="name"/>
        <el-table-column label="学院" align="left" prop="deptName" />
        <el-table-column label="安全分类" align="left" prop="typeName" />
        <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-column label="实验室负责人" align="left" prop="adminName" />
      </el-table>
      <pagination :page-sizes="[20, 30, 40, 50]"
        v-show="total>0"
        :total="total"
        :page.sync="dialogForm.pageNum"
        :limit.sync="dialogForm.pageSize"
        @pagination="getList"
      />
    </el-dialog>
  </div>
</template>

<script>
import {
  getPlan,
  addPlan,
  updatePlan,
  getUserRoleBySub,
  getLabRiskPlanRepeat,
  getUserRoleBySubOperation
} from "@/api/laboratory/plan";
import { optionHazard } from "@/api/laboratory/hazard";
import { optionSensor } from "@/api/laboratory/sensor";
import { optionHardware } from "@/api/laboratory/hardware";
import {listDepartments} from "@/api/system/dept";
import {listClassifiedAll} from "@/api/laboratory/classified";
import {listClasstypeAll} from "@/api/laboratory/classtype";
import {authListSubject} from "@/api/laboratory/subject";

export default {
  props:{
    pageData:{},
  },
  name: "addPlan",
  data() {
    return {
      form:{
        evacuation: 0,
        riskPlanSensorList:[],
        riskPlanHardwareList:[],
      },
      dialogVisible:false,
      //判断实验室框是否显示隐藏
      labShow:false,
      //实验室弹框
      dialogForm:{
        pageNum: 1,
        pageSize:20,
        name: null,
        deptId: null,
        typeId: null,
        level: null,
        adminName: null,

      },
      deptOptions:[],
      typeList:[],
      levelList:[],
      dialogTable:[],
      // 表单校验
      rules: {
        name: [
          { required: true, message: "请输入预案名称", trigger: "blur" },
          { required: true, message: "请输入预案名称", validator: this.spaceJudgment, trigger: "blur" }
        ],
        labname: [
          { required: true, message: "请选择关联实验室", trigger: "blur" },
          { required: true, message: "请选择关联实验室", validator: this.spaceJudgment, trigger: "blur" }
        ],
        hazardId: [
          { required: true, message: "危险源不能为空", trigger: "blur" }
        ],
        message: [
          { required: true, message: "短信提示不能为空", trigger: "change" },
          { required: true, message: "短信提示不能为空", validator: this.spaceJudgment, trigger: "blur" }
        ],
        voicebroadcast: [
          { required: true, message: "语音播报内容不能为空", trigger: "change" },
          { required: true, message: "语音播报内容不能为空", validator: this.spaceJudgment, trigger: "blur" }
        ],
        information: [
          { required: true, message: "消息推送内容不能为空", trigger: "blur" },
          { required: true, message: "消息推送内容不能为空", validator: this.spaceJudgment, trigger: "blur" }
        ],
        remark: [
          { required: true, message: "预案描述不能为空", trigger: "blur" },
          { required: true, message: "预案描述不能为空", validator: this.spaceJudgment, trigger: "blur" }
        ],
        funNum: [
          { required: true, message: "请选择传感器", trigger: "blur" }
        ],
        minMonitor: [
          { required: true, message: "请输入异常值", trigger: "blur" },
          { required: true, message: "请输入异常值", validator: this.spaceJudgment, trigger: "blur" },
        ],
        maxMonitor: [
          { required: true, message: "请输入异常值", trigger: "blur" },
          { required: true, message: "请输入异常值", validator: this.spaceJudgment, trigger: "blur" },
        ],
        hardwareType: [
          { required: true, message: "请选择硬件", trigger: "blur" }
        ],
        operate: [
          { required: true, message: "请选择执行操作", trigger: "blur" }
        ],
        overAct: [
          { required: false,trigger: "blur" }
        ],
      },
      // 危险源下拉
      hazardList: [],
      // 传感器下拉
      sensorList: [],
      sensorListData:[],
      // 硬件下拉
      hardwareList: [],
      // 硬件操作字典
      controlTypeOptions: [],
      labRiskPlanjoinsubList:[],//所选实验室id
      total: 0,
      joinSubOper:null,//返回true是实验室管理员，false不是实验室管理员

      arr:[],
    };
  },
  methods: {
    //select传感器选中
    selectFunNum(val,index){
      // let self = this;
      // let num = 0;
      // for(let i=0;i<self.form.riskPlanSensorList.length;i++){
      //   if(val == self.form.riskPlanSensorList[i].funNum){
      //     num++
      //   }
      // }
      // if(num>1){
      //   this.$set(this.form.riskPlanSensorList[index],'funNum','');
      //   this.msgError('已存在相同的传感器');
      // }
    },
    //查询
    onSearch() {
      this.dialogForm.pageNo = 1;
      this.getList();
    },
    //重置
    resetForm() {
      this.dialogForm.name = '';
      this.dialogForm.deptId = '';
      this.dialogForm.typeId = '';
      this.dialogForm.level = '';
      this.dialogForm.adminName = '';
      this.onSearch();
    },
    //实验室弹框
    labClick(){
      this.dialogVisible=true;
      console.log(this.arr)

      if(this.arr){
        console.log('实验室信息回显')
        this.$nextTick(() => {
          this.arr.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row);
          });
        })
      }
    },
    //关闭实验室弹窗
    closeDialog(){
     // this.labRiskPlanjoinsubList=[];
      this.dialogVisible=false;
    },
    //监听关联记录弹窗关闭
    handleClose(){
      console.log('弹窗关闭')
      if(this.arr){
        console.log('实验室信息回显')
        this.$nextTick(() => {
          this.arr.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row);
          });
        })
      }
    },
    //实验室弹窗确认
    confirmDialog(){
      this.dialogVisible=false;
    },
    //切换页面
    backPage(){
      this.$parent.handleClick('','','back');
    },
    /** 查询学院列表 */
    getDeptListTow() {
      listDepartments().then(response => {
        this.$set(this, 'deptOptions', 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;
        }
      });
    },

    /** 查询实验室列表 */
    getList() {
      this.loading = true;
      let _this=this;
      getUserRoleBySub(this.dialogForm).then(response => {
        if(response.code==200){
          this.dialogTable = response.rows;
          this.total = response.total;
          this.loading = false;

        }
      });
    },
    //选中实验室
    handleSelectionChange(val){

      let _this=this;
      _this.labRiskPlanjoinsubList=[];

      val.forEach(function (item,index){
        _this.labRiskPlanjoinsubList.push({'subjectId':item.id})
      })

    },
    //取消选中
    toggleSelection(rows) {

      if (rows) {
        this.$refs.multipleTable.clearSelection();
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    //新增传感器
    addSensor(){
      if(this.form.riskPlanSensorList.length>4){
        this.msgError('最多添加5项')
        return
      }
      let obj = {};
      console.log(this.form)
      this.form.riskPlanSensorList.push(obj);
    },
    delSensor(index){
      this.form.riskPlanSensorList.splice(index,1)
    },
    //新增规则
    addHardware(){
      if(this.form.riskPlanHardwareList.length>4){
        this.msgError('最多添加5项')
        return
      }
      let obj = {};
      this.form.riskPlanHardwareList.push(obj);
    },
    delHardware(index){
      this.form.riskPlanHardwareList.splice(index,1)
    },
    /** 修改按钮操作 */
    handleUpdate() {

      let _this=this;
      getPlan(this.form.id).then(response => {
        this.form = response.data;
        for(let i=0;i<response.data.riskPlanHardwareList.length;i++){
          this.controlTypeList(response.data.riskPlanHardwareList[i].hardwareType,i);
        }
        response.data.labRiskPlanjoinsubList.forEach(function (item,index){
          _this.labRiskPlanjoinsubList.push({'subjectId':item.subjectId})
        })
        _this.form.labRiskPlanjoinsubList=_this.labRiskPlanjoinsubList;
          //根据详情返回的实验室信息循环匹配相同实验室信息

          _this.dialogTable.forEach(function (item,index){
            _this.labRiskPlanjoinsubList.forEach(function (item2,index){
              if(item.id==item2.subjectId){
                console.log('有相同的实验室')
                _this.arr.push(item)
              }
            })
          })

      });
    },
    /** 查询实验室根据实验室管理员用户权限是否有操作权限 */
    getUserRoleBySubOperation(){
      getUserRoleBySubOperation({}).then(response => {

            if(response.code==200){
                  this.labShow= response.data  //返回true是实验室管理员，false不是实验室管理员
                  this.joinSubOper=response.data;
            }
      });
    },
    // 危险源下拉列表
    getHazardList () {
      optionHazard({}).then(response => {
        this.hazardList = response.data;
      });
    },
    /** 查询传感器列表 */
    getSensorList() {
      optionSensor({}).then(response => {
        this.sensorList = response.data;
        this.sensorListData = JSON.parse(JSON.stringify(response.data))
      });
    },
    /** 查询硬件下拉列表 */
    getHardwareList() {
      optionHardware({}).then(response => {
        var allDate = new Array();
        for(const key in response.data){
          allDate.push({"id":response.data[key].hardwareTypeEnum.code,"name":response.data[key].hardwareTypeEnum.name})
        }
        this.hardwareList = allDate;
      });
    },
    /** 查询功能列表 */
    controlTypeList(val,index) {

      optionHardware({}).then(response => {
        var allDate = new Array();
        for(const key in response.data){
          if(response.data[key].hardwareTypeEnum.code==val){
            for(const sta in response.data[key].functionStatusList){
              allDate.push({"dictLabel":response.data[key].functionStatusList[sta].describe,"dictValue":response.data[key].functionStatusList[sta].code})
            }
          }
        }
        this.$set(this.form.riskPlanHardwareList[index],'controlTypeOptions',allDate);
      });
    },
    /** 提交按钮 */
    submitForm() {
      let _this=this;
      this.$refs["form"].validate(valid => {
        if (valid) {
          for(let i=0;i<_this.form.riskPlanSensorList.length;i++){
            if(parseInt(_this.form.riskPlanSensorList[i].minMonitor)>=parseInt(_this.form.riskPlanSensorList[i].maxMonitor)){
              this.msgError('传感器异常区值的最小值无法超过最大值');
              return
            }
          }
          console.log(_this.labRiskPlanjoinsubList)
          _this.form.labRiskPlanjoinsubList=_this.labRiskPlanjoinsubList
          _this.form.joinSubOper=_this.joinSubOper

          getLabRiskPlanRepeat(_this.form).then(response => {
            if(response.code = 200){
              if(response.data.repeat==true){//：如果为true，就是有重复的，如果为false，就表示没有重复的

                this.$confirm(response.data.tipsStr, '提示', {
                  confirmButtonText: '是',
                  cancelButtonText: '否',
                  type: 'warning'
                }).then(() => {//确定
                  _this.form.yesOrNo=true;//是否覆盖提交，true是，false否
                  if (this.form.id != null) {
                    updatePlan(this.form).then(response => {
                      if(response.code = 200){
                        this.msgSuccess("修改成功");
                        this.$parent.handleClick('','','back');
                      }
                    });
                  } else {
                    addPlan(this.form).then(response => {
                      if(response.code = 200){
                        this.msgSuccess("新增成功");
                        this.$parent.handleClick('','','back');
                      }
                    });
                  }
                }).catch(() => {
                  _this.form.yesOrNo=false;//是否覆盖提交，true是，false否
                  if (this.form.id != null) {
                    updatePlan(this.form).then(response => {
                      if(response.code = 200){
                        this.msgSuccess("修改成功");
                        this.$parent.handleClick('','','back');
                      }
                    });
                  } else {
                    addPlan(this.form).then(response => {
                      if(response.code = 200){
                        this.msgSuccess("新增成功");
                        this.$parent.handleClick('','','back');
                      }
                    });
                  }
                });

              }else if(response.data.repeat==false){//：如果为true，就是有重复的，如果为false，就表示没有重复的

                _this.form.yesOrNo=false;//是否覆盖提交，true是，false否
                if (_this.form.id != null) {

                  updatePlan(_this.form).then(response => {
                    if(response.code = 200){
                      this.msgSuccess("修改成功");
                      this.$parent.handleClick('','','back');
                    }
                  });
                } else {
                  console.log('打印form')
                  console.log(_this.form)
                  addPlan(_this.form).then(response => {
                    if(response.code = 200){
                      this.msgSuccess("新增成功");
                      this.$parent.handleClick('','','back');
                    }
                  });
                }
              }
            }
          });
        }
      });
    },
  },
  beforeMount() {
    this.getDeptListTow();
    this.getListClassifiedAll();
    this.getListClasstypeAll();
    // this.controlTypeList();
    this.getUserRoleBySubOperation();
    this.getList();
    this.getHazardList();
    this.getSensorList();
    this.getHardwareList();
    if(this.pageData){
      this.form.id = this.pageData.id
    }
    if(this.form.id){
      this.handleUpdate()
    }
  },
  mounted(){
  },

};
</script>

<style scoped lang="scss">
  .addPlan{
    position: relative;
    margin-top:-11px;
    p{
      margin:0;
    }
    .plan-title-p{
      height:80px;
      line-height:80px;
      font-size:18px;
      padding-left:20px;
      border-bottom:1px solid #E0E0E0;
    }
    .reset-button-one{
     /* position: absolute;
      top:20px;
      right:0;*/
    }
    .plan-info-box{
      padding-top:30px;
      .add-button-p{
        width:300px;
        height:40px;
        line-height:36px;
        font-size:16px;
        border:2px dashed #E0E0E0;
        border-radius:4px;
        cursor:pointer;
        margin:20px auto 0;
        text-align: center;
        i{
          margin-right:5px;
        }
      }
    }
    .bottom-button-box{
      display: flex;
      justify-content: flex-start;
      width:220px;
      margin:80px auto 20px;
      p{
        font-size:14px;
        height:40px;
        width:100px;
        line-height:40px;
        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;
      }
    }
  }
  .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>
<style lang="scss">
  .addPlan{
    .for-sensor-input{
      input::-webkit-outer-spin-button,
      input::-webkit-inner-spin-button {
        -webkit-appearance: none!important;
      }
      /* 在Firefox浏览器下 */
      input[type="number"]{
        -moz-appearance: textfield!important;
      }
    }
  }
</style>
