<template>
  <div class="page-container newAddPlan">
    <div class="page-top-title-box">
      <p class="page-top-title-name-p">定制预案</p>
      <p class="page-top-title-out-p" @click="backButton">返回</p>
      <p class="page-top-title-submit-p" style="width:120px;" @click="associatedDialogClick">关联实验室</p>
    </div>
    <div class="plan-for-max-box scrollbar-box">
      <el-form :model="form" ref="form" :rules="rules" :inline="true" label-width="90px" class="form-box">
        <div class="plan-for-max-box-name-box">
          <el-form-item label="预案名称:" prop="name" style="margin:40px 0;">
            <el-input
              style="width:200px;"
              v-model="form.name"
              placeholder="请输入预案名称"
              maxLength="15"
              :disabled="inputType"
            />
          </el-form-item>
          <el-form-item label="疏散音乐:" prop="musicId" style="margin:40px 0;">
            <el-select v-model="form.musicId"
                       :disabled="inputType"
                       placeholder="请选择疏散音乐" style="width:200px;">
              <el-option
                v-for="dict in musicOptions"
                :key="dict.id"
                :label="dict.musicName"
                :value="dict.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <p class="plan-for-max-box-name-button-one add-button-two-90"
             v-if="inputType" @click="setNameButton(1)">编辑</p>
          <p class="plan-for-max-box-name-button-two reset-button-one"
             v-if="!inputType" @click="setNameButton(2)">取消</p>
          <p class="plan-for-max-box-name-button-three add-button-two-90"
             v-if="!inputType" @click="setNameButton(3)">保存</p>
        </div>
        <div class="for-plan-box" v-for="(item,index) in form.labRiskPlanLevels" :key="index">
          <p class="position-title-type"
             :class="item.riskPlanLevel==1?'type-color-a':(item.riskPlanLevel==2?'type-color-b':(item.riskPlanLevel==3?'type-color-c':(item.riskPlanLevel==4?'type-color-d':'')))">
            {{item.riskPlanLevel==1?'低风险':(item.riskPlanLevel==2?'中风险':(item.riskPlanLevel==3?'较高风险':(item.riskPlanLevel==4?'高风险':'')))}}
          </p>
          <div class="for-plan-img-box">
            <p class="for-plan-img-null-p"></p>
            <div class="for-plan-img-box-big">
              <div class="for-plan-img-box-one">
                <img v-if="item.riskPlanLevel==1" src="@/assets/ZDimages/emergencyManagement/icon_dzya_dfx.png">
                <img v-if="item.riskPlanLevel==2" src="@/assets/ZDimages/emergencyManagement/icon_dzya_zfx.png">
                <img v-if="item.riskPlanLevel==3" src="@/assets/ZDimages/emergencyManagement/icon_dzya_jgfx.png">
                <img v-if="item.riskPlanLevel==4" src="@/assets/ZDimages/emergencyManagement/icon_dzya_gfx.png">
              </div>
            </div>
            <p class="for-plan-img-null-p"></p>
          </div>
          <div class="min-for-text-box">
            <div>
              <div class="min-for-text-box-one" v-for="(minItemOne,minIndexOne) in item.bindingSensor"
                   :key="minItemOne.code">
                <div>
                  <p>启动条件：<span v-for="(sensorItem,sensorIndex) in sensorList" :key="'sensor'+sensorIndex"
                                v-if="sensorItem.code == minItemOne.code">{{sensorItem.name}}</span></p>
                  <p>监测区间：{{minItemOne.min}}-{{minItemOne.max}}</p>
                </div>
              </div>
            </div>
            <div>
              <div class="min-for-text-box-two" v-for="(minItemTwo,minIndexTwo) in item.bindingDevice"
                   :key="minIndexTwo">
                <div v-for="(hardwareItem,hardwareIndex) in hardwareList" :key="hardwareIndex"
                     v-if="hardwareItem.typeKey == minItemTwo.typeKey">
                  <p>执行动作：{{hardwareItem.riskDeviceTypeName}}</p>
                  <p v-if="minItemTwo.typeKey != 'airConditioner'">执行办法：<span>{{minItemTwo.startOperate == 0?'关闭':'开启'}}</span></p>
                  <p v-if="minItemTwo.typeKey != 'airConditioner'">结束操作：<span>{{minItemTwo.endOperate == 0?'关闭':'开启'}}</span></p>
                  <p v-if="minItemTwo.typeKey == 'airConditioner'">执行办法：<span v-for="(minTypeItem,minTypeIndex) in optionsTypeList" v-if="minItemTwo.startOperate == minTypeItem.value">{{minTypeItem.label}}</span></p>
                  <p v-if="minItemTwo.typeKey == 'airConditioner'">结束操作：<span v-for="(minTypeItem,minTypeIndex) in optionsTypeList" v-if="minItemTwo.endOperate == minTypeItem.value">{{minTypeItem.label}}</span></p>
                </div>
              </div>
            </div>
          </div>
          <div class="for-button-max-box">
            <div @click="buttonClick(2,item,index)">
              <img src="@/assets/ZDimages/basicsModules/icon_znwl_bj.png">
              <p>编辑</p>
            </div>
            <div @click="buttonClick(3,item,index)">
              <img src="@/assets/ZDimages/basicsModules/icon_znwl_sc.png">
              <p>删除</p>
            </div>
          </div>
        </div>
      </el-form>
      <div class="plan-for-max-button-box">
        <p class="plan-for-max-button-null"></p>
        <p class="plan-for-max-button" v-if="!form.labRiskPlanLevels[3]" @click="buttonClick(1)">+ 新增预案规则</p>
        <p class="plan-for-max-button-null"></p>
      </div>
    </div>
    <el-dialog :title='dialogTitle' v-if="dialogOpen" :visible.sync="dialogOpen" append-to-body
               width="800px" :close-on-click-modal="false">
      <div class="scrollbar-box" style="height:600px;">
        <el-form :model="dialogForm" ref="dialogForm" :rules="rules" label-width="100px">
          <el-form-item label="预案等级：" prop="riskPlanLevel">
            <el-radio-group v-model="dialogForm.riskPlanLevel" style="width:500px;">
              <el-radio :label="1">低风险</el-radio>
              <el-radio :label="2">中风险</el-radio>
              <el-radio :label="3">较高风险</el-radio>
              <el-radio :label="4">高风险</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="报警通知方式:" prop="alarmType">
            <el-checkbox-group v-model="dialogForm.alarmType" @change="alarmChange">
              <el-checkbox label="1">电话报警</el-checkbox>
              <el-checkbox label="2">短信报警</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="短信模板:" prop="msgTempId" v-if="businessType">
            <el-select placeholder="请选择短信模板" v-model="dialogForm.msgTempId" style="width:300px;">
              <el-option
                v-for="item in businessOptions"
                :key="item.templateId"
                :label="item.templateName"
                :value="item.templateId">
              </el-option>
            </el-select>
          </el-form-item>
          <div class="autoClose">
            <p class="autoClose_l">自动关闭:</p>
            <p class="autoClose_l2">传感器监测数值恢复正常</p>
            <el-input v-model="dialogForm.riskAutoOff" style="width:120px;" :min="1" :max="600" :controls="false">
              <template slot="append">秒</template>
            </el-input>
            <p class="autoClose_l5">以后预案自动关闭</p>
          </div>
          <div style="border-top:1px solid #e0e0e0;overflow: hidden;">
            <p style="line-height:60px;font-size:14px;margin-left:19px;">启动条件：</p>
            <div style="display: flex" v-for="(item,index) in dialogForm.bindingSensor" :key="index">
              <div style="flex:1;">
                <el-form-item label="监测设备：" :prop="'bindingSensor.'+index+'.code'" :rules="rules.code">
                  <el-select v-model="item.code" placeholder="请选择监测设备" @change="(val)=>sensorChange(val,index)">
                    <el-option
                      v-for="item in sensorList"
                      :key="item.code"
                      :label="item.name"
                      :value="item.code">
                    </el-option>
                  </el-select>
                </el-form-item>
              </div>
              <div style="flex:1;display: flex">
                <el-form-item label="监测区间：" :prop="'bindingSensor.'+index+'.min'" :rules="rules.min">
                  <el-input-number v-model="item.min" style="width:90px;" :disabled="item.suoType"
                                   :min="1" :max="99999" :controls="false" placeholder="监测区间"></el-input-number>
                </el-form-item>
                <p style="width:30px;text-align: center;line-height:40px;">-</p>
                <el-form-item label="" :prop="'bindingSensor.'+index+'.max'" :rules="rules.max" label-width="0">
                  <el-input-number v-model="item.max" style="width:90px;" :disabled="item.suoType"
                                   :min="1" :max="99999" :controls="false" placeholder="监测区间"></el-input-number>
                </el-form-item>
                <p class="el-icon-delete"
                   @click="delMinData(1,index)"
                   style="cursor: pointer;line-height:30px;width:30px;text-align:center;margin:5px 0 0 20px;"></p>
              </div>
            </div>
            <p
              style="cursor: pointer;width:200px;line-height:30px;border-radius:4px;border: 1px dashed #E0E0E0;color:#333333;text-align: center;margin:20px auto;"
              @click="addMinData(1)" :class="dialogForm.bindingSensor.length>8?'add-plan-max-button-color':''">+
              新增监测规则</p>
          </div>
          <div style="border-top:1px solid #e0e0e0;overflow: hidden;">
            <p style="line-height:60px;font-size:14px;margin-left:19px;">执行动作：</p>
            <div style="display: flex" v-for="(item,index) in dialogForm.bindingDevice" :key="index">
              <div style="flex:1;display: flex">
                <el-form-item label="执行设备：" :prop="'bindingDevice.'+index+'.typeKey'" :rules="rules.typeKey">
                  <el-select v-model="item.typeKey" placeholder="选择执行设备" style="width:130px;"
                             @change="(val)=>controlTypeList(val,index)">
                    <el-option
                      v-show="!optionItem.checkType"
                      v-for="optionItem in hardwareList"
                      :key="optionItem.typeKey"
                      :label="optionItem.riskDeviceTypeName"
                      :value="optionItem.typeKey">
                    </el-option>
                    <p v-show="hardwareShowType" style="text-align: center;color:#999;font-size:12px;line-height:30px;">
                      暂无更多</p>
                  </el-select>
                </el-form-item>
                <el-form-item v-if="item.typeKey == 'airConditioner'" label="执行办法："
                              :prop="'bindingDevice.'+index+'.startOperate'" :rules="rules.startOperate">
                  <el-cascader
                    style="width:130px;"
                    v-model="item.startOperate"
                    :props="{ emitPath:false }"
                    :options="options">
                  </el-cascader>
                </el-form-item>
                <el-form-item v-if="item.typeKey == 'airConditioner'" label="结束操作："
                              :prop="'bindingDevice.'+index+'.endOperate'" :rules="rules.endOperate">
                  <el-cascader
                    style="width:130px;"
                    v-model="item.endOperate"
                    :props="{ emitPath:false }"
                    :options="options">
                  </el-cascader>
                </el-form-item>
                <el-form-item v-if="item.typeKey != 'airConditioner'" label="执行办法："
                              :prop="'bindingDevice.'+index+'.startOperate'" :rules="rules.startOperate">
                  <el-select v-model="item.startOperate" placeholder="选择执行办法" style="width:130px;">
                    <el-option
                      v-for="optionItem in hardwareOption"
                      :key="optionItem.code"
                      :label="optionItem.describe"
                      :value="optionItem.code">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item v-if="item.typeKey != 'airConditioner'" label="结束操作："
                              :prop="'bindingDevice.'+index+'.endOperate'" :rules="rules.endOperate">
                  <el-select v-model="item.endOperate" placeholder="选择结束操作" style="width:130px;">
                    <el-option
                      v-for="optionItem in hardwareOption"
                      :key="optionItem.code"
                      :label="optionItem.describe"
                      :value="optionItem.code">
                    </el-option>
                  </el-select>
                </el-form-item>
                <p class="el-icon-delete"
                   @click="delMinData(2,index)"
                   style="cursor: pointer;line-height:30px;width:30px;text-align:center;margin:5px 0 0 20px;"></p>
              </div>
            </div>
            <p
              style="cursor: pointer;width:200px;line-height:30px;border-radius:4px;border: 1px dashed #E0E0E0;color:#333333;text-align: center;margin:20px auto;"
              @click="addMinData(2)" :class="dialogForm.bindingDevice.length>8?'add-plan-max-button-color':''">+
              新增执行动作</p>
          </div>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer dialog-footer-box">
        <p class="dialog-footer-button-null"></p>
        <p class="dialog-footer-button-info" @click="cancel">取消</p>
        <p class="dialog-footer-button-primary" @click="submitForm">提交</p>
        <p class="dialog-footer-button-null"></p>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    laboratoryMusicFindByType, laboratoryRiskDeviceTypeGetList, laboratoryRiskPlanLevelGetRiskPlanLeveList,
    laboratoryPlanUpdate, laboratoryRiskPlanLevelAdd, laboratoryRiskPlanLevelUpdate, laboratoryRiskPlanLevelDelete
  } from '@/api/emergencyManagement/index'
  import { iotAttributeGetByTypeKey } from '@/api/iotDevice/index'
  import { iotAlarmTemplateFindList } from '@/api/commonality/permission'

  export default {
    name: 'newAddPlan',
    props: {
      addPlanData: {}
    },
    data() {
      const exportconstvalidateContacts = (rule, value, callback) => {
        if (!/^[\u0391-\uFFE5_a-zA-Z0-9]+$/.test(value)) {
          callback(new Error('只可输入中文/英文与数字'))
        } else {
          callback()
        }
      }
      return {
        musicOptions: [],
        form: {
          name: '',
          labRiskPlanLevels: []
        },
        dialogTitle: '',
        dialogIndex: null,
        dialogOpen: false,
        dialogForm: {},
        //短信开关条件
        businessType: false,
        businessOptions: [],
        // 表单校验
        rules: {
          name: [
            { required: true, message: '请输入预案名称', trigger: 'change' },
            { required: true, message: '请输入预案名称', validator: this.spaceJudgment, trigger: 'change' },
            { required: true, validator: exportconstvalidateContacts, trigger: 'blur' }
          ],
          musicId: [
            { required: true, message: '请选择疏散音乐', trigger: 'change' },
            { required: true, message: '请选择疏散音乐', validator: this.spaceJudgment, trigger: 'change' }
          ],
          msgTempId: [
            { required: true, message: '请选择短信模板', trigger: 'change' }
          ],
          riskPlanLevel: [
            { required: true, message: '请选择预案等级', trigger: 'change' }
          ],
          ifExit: [
            { required: true, message: '请选择是否执行疏散', trigger: 'change' }
          ],
          code: [
            { required: true, message: '请选择监测设备', trigger: 'change' }
          ],
          min: [
            { required: true, message: '请选择监测区间', trigger: 'blur' }
          ],
          max: [
            { required: true, message: '请选择监测区间', trigger: 'blur' }
          ],
          typeKey: [
            { required: true, message: '请选择执行设备', trigger: 'change' }
          ],
          startOperate: [
            { required: true, message: '请选择执行办法', trigger: 'change' }
          ],
          endOperate: [
            { required: true, message: '请选择结束操作', trigger: 'change' }
          ],
          riskAutoOff: [
            { required: true, message: '请选择关闭时间', trigger: 'change' }
          ]
        },
        //空调动作
        options: [{
          value: '1',
          label: '开启',
          children: [
            {
              value: '3',
              label: '制冷',
              children: [{
                value: '3-18',
                label: '18°C'
              }, {
                value: '3-19',
                label: '19°C'
              }, {
                value: '3-21',
                label: '21°C'
              }, {
                value: '3-22',
                label: '22°C'
              }, {
                value: '3-23',
                label: '23°C'
              }, {
                value: '3-24',
                label: '24°C'
              }, {
                value: '3-25',
                label: '25°C'
              }, {
                value: '3-26',
                label: '26°C'
              }, {
                value: '3-27',
                label: '27°C'
              }, {
                value: '3-28',
                label: '28°C'
              }]
            }, {
              value: '4',
              label: '制热',
              children: [{
                value: '4-22',
                label: '22°C'
              }, {
                value: '4-23',
                label: '23°C'
              }, {
                value: '4-24',
                label: '24°C'
              }, {
                value: '4-25',
                label: '25°C'
              }, {
                value: '4-26',
                label: '26°C'
              }, {
                value: '4-27',
                label: '27°C'
              }, {
                value: '4-28',
                label: '28°C'
              }, {
                value: '4-29',
                label: '29°C'
              }, {
                value: '4-30',
                label: '30°C'
              }]
            }, {
              value: '2',
              label: '通风'
            }]
        }, {
          value: '0',
          label: '关闭'
        }],
        optionsTypeList: [{
          value: '0',
          label: '关闭'
        }, {
          value: '2',
          label: '通风'
        }, {
          value: '3-18',
          label: '制冷18°C'
        }, {
          value: '3-19',
          label: '制冷19°C'
        }, {
          value: '3-21',
          label: '制冷21°C'
        }, {
          value: '3-22',
          label: '制冷22°C'
        }, {
          value: '3-23',
          label: '制冷23°C'
        }, {
          value: '3-24',
          label: '制冷24°C'
        }, {
          value: '3-25',
          label: '制冷25°C'
        }, {
          value: '3-26',
          label: '制冷26°C'
        }, {
          value: '3-27',
          label: '制冷27°C'
        }, {
          value: '3-28',
          label: '制冷28°C'
        }, {
          value: '4-22',
          label: '制热22°C'
        }, {
          value: '4-23',
          label: '制热23°C'
        }, {
          value: '4-24',
          label: '制热24°C'
        }, {
          value: '4-25',
          label: '制热25°C'
        }, {
          value: '4-26',
          label: '制热26°C'
        }, {
          value: '4-27',
          label: '制热27°C'
        }, {
          value: '4-28',
          label: '制热28°C'
        }, {
          value: '4-29',
          label: '制热29°C'
        }, {
          value: '4-30',
          label: '制热30°C'
        }],
        //选择数据
        //传感器
        sensorList: [],
        sensorListData: [],
        //设备
        hardwareList: [],
        hardwareShowType: false,
        //设备动作
        hardwareOption: [{ code: 1, describe: '打开' }, { code: 0, describe: '关闭' }],
        //分类
        typeList: [],
        //分级
        levelList: [],
        // 关联实验室本地数据
        labSensorHazardRelations: [],
        // 新增/编辑时本地数据
        labRiskPlanLevels: [],
        //名称修改状态锁
        inputType: true,
        inputName: '',
        inputMusicId: ''
      }
    },
    created() {

    },
    mounted() {
      this.initialization()
    },
    methods: {
      //初始化
      initialization() {
        this.iotAlarmTemplateFindList()
        this.laboratoryMusicFindByType()
        this.iotAttributeGetByTypeKey()
        this.laboratoryRiskDeviceTypeGetList()
        this.laboratoryRiskPlanLevelGetRiskPlanLeveList(1)
      },
      //传感器选中事件
      sensorChange(val, index) {
        let self = this
        for (let i = 0; i < self.sensorList.length; i++) {
          if (self.sensorList[i].code == val) {
            this.$set(self.dialogForm.bindingSensor[index], 'funNum', self.sensorList[i].name)
            if (self.sensorList[i].enumName == 'FLAME') {
              self.dialogForm.bindingSensor[index].min = 1
              self.dialogForm.bindingSensor[index].max = 2
              self.$set(self.dialogForm.bindingSensor[index], 'min', 1)
              self.$set(self.dialogForm.bindingSensor[index], 'max', 2)
              self.$set(self.dialogForm.bindingSensor[index], 'suoType', true)
            } else {
              self.$set(self.dialogForm.bindingSensor[index], 'suoType', false)
            }
          }
        }
      },
      //修改预案名称
      setNameButton(type) {
        if (type == 1) {
          this.$set(this, 'inputType', false)
          this.$set(this, 'inputName', this.form.name)
          this.$set(this, 'inputMusicId', this.form.musicId)
        } else if (type == 2) {
          this.$set(this, 'inputType', true)
          this.$set(this.form, 'name', this.inputName)
          this.$set(this.form, 'musicId', this.inputMusicId)
        } else if (type == 3) {
          this.$refs['form'].validate(valid => {
            if (valid) {
              laboratoryPlanUpdate({
                id: this.addPlanData.id,
                name: this.form.name,
                musicId: this.form.musicId
              }).then((response) => {
                this.msgSuccess(response.message)
                this.$set(this, 'inputType', true)
              })
            }
          })
        }
      },
      //提交
      upDataButton() {
        this.$refs['form'].validate(valid => {
          if (valid) {
            if (!this.form.labRiskPlanLevels[0]) {
              this.msgError('请添加至少一个预案规则')
              return
            }
            setPlanData(this.form).then(response => {
              this.msgSuccess(response.message)
              this.$parent.tableClickButton(5)
            })
          }
        })
      },
      //新增验证是否可继续添加执行设备
      addFiltration() {
        let self = this
        let num = 0
        for (let i = 0; i < self.dialogForm.bindingDevice.length; i++) {
          if (self.dialogForm.bindingDevice[i].typeKey) {
            num++
          }
        }
        if (num < self.hardwareList.length) {
          return true
        } else {
          this.msgError('暂无更多的执行设备可选则')
          return false
        }
      },
      //处理选中后的设备是否继续展示
      actionFiltration() {
        let self = this
        let age = 0
        for (let o = 0; o < self.hardwareList.length; o++) {
          let num = 0
          for (let i = 0; i < self.dialogForm.bindingDevice.length; i++) {
            if (self.dialogForm.bindingDevice[i].typeKey == self.hardwareList[o].typeKey) {
              num++
              age++
            }
          }
          self.hardwareList[o].checkType = num != 0
        }
        //验证
        if (age < self.hardwareList.length) {
          this.$set(this, 'hardwareShowType', false)
        } else {
          for (let i = 0; i < self.dialogForm.bindingDevice.length; i++) {
            if (!self.dialogForm.bindingDevice[i].typeKey) {
              self.dialogForm.bindingDevice.splice(i, 1)
            }
          }
          this.$set(this, 'hardwareShowType', true)
        }
      },
      //报警通知方式变更
      alarmChange(val) {
        let num = 0
        val.forEach((item) => {
          if (item == '2') {
            num++
          }
        })
        if (num != 0) {
          this.$set(this, 'businessType', true)
        } else {
          this.$set(this, 'businessType', false)
        }
      },
      //查询设备功能
      controlTypeList(val, index) {
        let self = this
        // for(let i=0;i<self.hardwareList.length;i++){
        //   if(self.hardwareList[i].typeKey == val){
        //     this.$set(self.dialogForm.bindingDevice[index],'hardwareList',self.hardwareList[i].functionStatusList);
        //     this.actionFiltration()
        //     return
        //   }
        // }
        this.$set(this.dialogForm.bindingDevice[index], 'startOperate', null)
        this.$set(this.dialogForm.bindingDevice[index], 'endOperate', null)
      },
      //查询预案规则
      laboratoryRiskPlanLevelGetRiskPlanLeveList(type) {
        laboratoryRiskPlanLevelGetRiskPlanLeveList({ riskPlanId: this.addPlanData.id }).then((response) => {
          if (type == 1) {
            this.$set(this.form, 'name', this.addPlanData.name)
            this.$set(this.form, 'musicId', this.addPlanData.musicId)
            this.$set(this, 'inputType', true)
          }
          for (let i = 0; i < response.data.length; i++) {
            response.data[i].bindingSensor = response.data[i].bindingSensor ? JSON.parse(response.data[i].bindingSensor) : []
            response.data[i].bindingDevice = response.data[i].bindingDevice ? JSON.parse(response.data[i].bindingDevice) : []
          }
          this.$set(this.form, 'labRiskPlanLevels', response.data)
        })
      },
      //返回
      backButton() {
        this.$parent.tableClickButton(5)
      },
      //实验室关联开关
      associatedDialogClick(type) {
        if (!this.form.labRiskPlanLevels[0]) {
          this.msgError('请先添加预案规则')
        } else {
          this.$parent.tableClickButton(1, { id: this.addPlanData.id, type: 1 })
        }
      },
      //新增按钮
      addMinData(type) {
        if (this.addFiltration()) {
          if (type == 1) {
            if (this.dialogForm.bindingSensor.length > 8) {
              this.msgError('新增失败，最多只能新增九条监测规则')
              return
            }
            this.dialogForm.bindingSensor.push({
              code: null
            })
          } else if (type == 2) {
            if (this.dialogForm.bindingDevice.length > 8) {
              this.msgError('新增失败，最多只能新增九条处置规则')
              return
            }
            this.dialogForm.bindingDevice.push({
              typeKey: null,
              startOperate: null,
              endOperate: null
            })
          }
          this.actionFiltration()
        }
      },
      //删除按钮
      delMinData(type, index) {
        if (type == 1) {
          this.dialogForm.bindingSensor.splice(index, 1)
        } else if (type == 2) {
          this.dialogForm.bindingDevice.splice(index, 1)
        }
        this.actionFiltration()
      },
      //提交
      submitForm() {
        let self = this
        this.$refs['dialogForm'].validate(valid => {
          if (valid) {
            if (!this.dialogForm.bindingSensor[0]) {
              this.msgError('请添加至少一个启动条件')
              return
            }
            //提交数据检测条件区间是否重复(dialog本身数据查重)
            for (let i = 0; i < self.dialogForm.bindingSensor.length; i++) {
              if (self.dialogForm.bindingSensor[i].min >= self.dialogForm.bindingSensor[i].max) {
                self.msgError('监测区间数值异常，请重新输入')
                return
              }
              for (let x = 0; x < self.dialogForm.bindingSensor.length; x++) {
                if (self.dialogForm.bindingSensor[i].code == self.dialogForm.bindingSensor[x].code && i != x) {
                  if (self.dialogForm.bindingSensor[i].min >= self.dialogForm.bindingSensor[x].min &&
                    self.dialogForm.bindingSensor[i].min <= self.dialogForm.bindingSensor[x].max) {
                    self.msgError('监测区间不能重复，请重新输入')
                    return
                  }
                  if (self.dialogForm.bindingSensor[i].max >= self.dialogForm.bindingSensor[x].min &&
                    self.dialogForm.bindingSensor[i].max <= self.dialogForm.bindingSensor[x].max) {
                    self.msgError('监测区间不能重复，请重新输入')
                    return
                  }
                }
              }
            }
            //判断 当前为修改还是新增
            if (this.dialogIndex != null) {
              //编辑
              //判断是否已有同等级预案
              for (let i = 0; i < self.labRiskPlanLevels.length; i++) {
                if (self.labRiskPlanLevels[i].riskPlanLevel == self.dialogForm.riskPlanLevel) {
                  this.msgError('无法添加多个相同等级的预案.')
                  return
                }
              }
              for (let i = 0; i < self.labRiskPlanLevels.length; i++) {
                if (self.labRiskPlanLevels[i].bindingSensor.length == self.dialogForm.bindingSensor.length) {
                  let age = 0
                  for (let o = 0; o < self.labRiskPlanLevels[i].bindingSensor.length; o++) {
                    for (let x = 0; x < self.dialogForm.bindingSensor.length; x++) {
                      if (self.dialogForm.bindingSensor[x].code == self.labRiskPlanLevels[i].bindingSensor[o].code) {
                        if (self.dialogForm.bindingSensor[x].min >= self.labRiskPlanLevels[i].bindingSensor[o].min &&
                          self.dialogForm.bindingSensor[x].min <= self.labRiskPlanLevels[i].bindingSensor[o].max) {
                          age++
                        } else if (self.dialogForm.bindingSensor[x].max >= self.labRiskPlanLevels[i].bindingSensor[o].min &&
                          self.dialogForm.bindingSensor[x].max <= self.labRiskPlanLevels[i].bindingSensor[o].max) {
                          age++
                        } else if (self.labRiskPlanLevels[i].bindingSensor[o].min >= self.dialogForm.bindingSensor[x].min &&
                          self.labRiskPlanLevels[i].bindingSensor[o].min <= self.dialogForm.bindingSensor[x].max) {
                          age++
                        } else if (self.labRiskPlanLevels[i].bindingSensor[o].max >= self.dialogForm.bindingSensor[x].min &&
                          self.labRiskPlanLevels[i].bindingSensor[o].max <= self.dialogForm.bindingSensor[x].max) {
                          age++
                        }
                      }
                    }
                  }
                  if (self.dialogForm.bindingSensor.length == age) {
                    self.msgError('监测区间不能与其他级别检测条件完全重复，请重新输入')
                    return
                  }
                }
              }
            } else {
              //新增
              for (let i = 0; i < self.form.labRiskPlanLevels.length; i++) {
                if (self.form.labRiskPlanLevels[i].riskPlanLevel == self.dialogForm.riskPlanLevel) {
                  this.msgError('无法添加多个相同等级的预案.')
                  return
                }
              }
              for (let i = 0; i < self.form.labRiskPlanLevels.length; i++) {
                if (self.form.labRiskPlanLevels[i].bindingSensor.length == self.dialogForm.bindingSensor.length) {
                  let age = 0
                  for (let o = 0; o < self.form.labRiskPlanLevels[i].bindingSensor.length; o++) {
                    for (let x = 0; x < self.dialogForm.bindingSensor.length; x++) {
                      if (self.dialogForm.bindingSensor[x].code == self.form.labRiskPlanLevels[i].bindingSensor[o].code) {
                        if (self.dialogForm.bindingSensor[x].min >= self.form.labRiskPlanLevels[i].bindingSensor[o].min &&
                          self.dialogForm.bindingSensor[x].min <= self.form.labRiskPlanLevels[i].bindingSensor[o].max) {
                          age++
                        } else if (self.dialogForm.bindingSensor[x].max >= self.form.labRiskPlanLevels[i].bindingSensor[o].min &&
                          self.dialogForm.bindingSensor[x].max <= self.form.labRiskPlanLevels[i].bindingSensor[o].max) {
                          age++
                        } else if (self.form.labRiskPlanLevels[i].bindingSensor[o].min >= self.dialogForm.bindingSensor[x].min &&
                          self.form.labRiskPlanLevels[i].bindingSensor[o].min <= self.dialogForm.bindingSensor[x].max) {
                          age++
                        } else if (self.form.labRiskPlanLevels[i].bindingSensor[o].max >= self.dialogForm.bindingSensor[x].min &&
                          self.form.labRiskPlanLevels[i].bindingSensor[o].max <= self.dialogForm.bindingSensor[x].max) {
                          age++
                        }
                      }
                    }
                  }
                  if (self.dialogForm.bindingSensor.length == age) {
                    self.msgError('监测区间不能与其他级别检测条件完全重复，请重新输入')
                    return
                  }
                }
              }
            }
            // this.$refs["dialogForm"].validate(valid => {
            //   if (valid) {
            if (this.dialogIndex != null) {
              //修改预案级别数据
              let text = []
              for (let i = 0; i < self.form.labRiskPlanLevels.length; i++) {
                if (this.dialogIndex != i) {
                  for (let o = 0; o < self.form.labRiskPlanLevels[i].bindingSensor.length; o++) {
                    for (let x = 0; x < self.sensorList.length; x++) {
                      if (self.form.labRiskPlanLevels[i].bindingSensor[o].code == self.sensorList[x].code) {
                        text.push(self.sensorList[x].name)
                      }
                    }
                  }
                }
              }
              for (let i = 0; i < self.dialogForm.bindingSensor.length; i++) {
                for (let x = 0; x < self.sensorList.length; x++) {
                  if (self.dialogForm.bindingSensor[i].code == self.sensorList[x].code) {
                    text.push(self.sensorList[x].name)
                  }
                }
              }
              text = Array.from(new Set(text))
              text = text + ''
              text = text.replace(',', '+')
              let obj = JSON.parse(JSON.stringify(this.dialogForm))
              obj.riskAutoOff = Number(obj.riskAutoOff)
              obj.alarmType = obj.alarmType+'';
              obj.msgTempId = this.businessType ? obj.msgTempId : null
              obj.startCondition = text + ''
              obj.bindingSensor = obj.bindingSensor[0] ? JSON.stringify(obj.bindingSensor) : ''
              // obj.bindingDevice.forEach((item)=>{
              //   if(item.typeKey == 'airConditioner'){
              //     let textA = '';
              //     item.startOperate.forEach((minItem,minIndex)=>{
              //       textA = minIndex == 0 ? textA+''+minItem:textA+'-'+minItem
              //     })
              //     item.startOperate = textA;
              //     let textB = '';
              //     item.endOperate.forEach((minItem,minIndex)=>{
              //       textB = minIndex == 0 ? textB+''+minItem:textB+'-'+minItem
              //     })
              //     item.endOperate = textB;
              //   }
              // })
              obj.bindingDevice = obj.bindingDevice[0] ? JSON.stringify(obj.bindingDevice) : ''
              laboratoryRiskPlanLevelUpdate(obj).then((response) => {
                this.msgSuccess(response.message)
                this.laboratoryRiskPlanLevelGetRiskPlanLeveList()
                this.$set(this, 'dialogOpen', false)
              })
            } else {
              //新增预案级别数据
              let text = []
              for (let i = 0; i < self.form.labRiskPlanLevels.length; i++) {
                for (let o = 0; o < self.form.labRiskPlanLevels[i].bindingSensor.length; o++) {
                  for (let x = 0; x < self.sensorList.length; x++) {
                    if (self.form.labRiskPlanLevels[i].bindingSensor[o].code == self.sensorList[x].code) {
                      text.push(self.sensorList[x].name)
                    }
                  }
                }
              }
              for (let i = 0; i < self.dialogForm.bindingSensor.length; i++) {
                for (let x = 0; x < self.sensorList.length; x++) {
                  if (self.dialogForm.bindingSensor[i].code == self.sensorList[x].code) {
                    text.push(self.sensorList[x].name)
                  }
                }
              }
              text = Array.from(new Set(text))
              text = text + ''
              text = text.replace(',', '+')
              let obj = JSON.parse(JSON.stringify(this.dialogForm))
              obj.riskAutoOff = Number(obj.riskAutoOff)
              obj.alarmType = obj.alarmType+'';
              obj.msgTempId = this.businessType ? obj.msgTempId : null
              obj.riskPlanId = this.addPlanData.id
              obj.startCondition = text + ''
              obj.bindingSensor = obj.bindingSensor[0] ? JSON.stringify(obj.bindingSensor) : ''
              // obj.bindingDevice.forEach((item)=>{
              //   if(item.typeKey == 'airConditioner'){
              //     let textA = '';
              //     item.startOperate.forEach((minItem,minIndex)=>{
              //       textA = minIndex == 0 ? textA+''+minItem:textA+'-'+minItem
              //     })
              //     item.startOperate = textA;
              //     let textB = '';
              //     item.endOperate.forEach((minItem,minIndex)=>{
              //       textB = minIndex == 0 ? textB+''+minItem:textB+'-'+minItem
              //     })
              //     item.endOperate = textB;
              //   }
              // })
              obj.bindingDevice = obj.bindingDevice[0] ? JSON.stringify(obj.bindingDevice) : ''
              laboratoryRiskPlanLevelAdd(obj).then((response) => {
                this.msgSuccess(response.message)
                this.laboratoryRiskPlanLevelGetRiskPlanLeveList()
                this.$set(this, 'dialogOpen', false)
              })
            }
            //   }
            // })
          }
        })
      },
      //取消
      cancel() {
        this.$set(this, 'dialogOpen', false)
      },
      //新增/编辑预案按钮
      buttonClick(type, item, index) {
        let self = this
        if (type == 1) {
          let a = 0
          let b = 0
          let c = 0
          let d = 0
          for (let i = 0; i < self.form.labRiskPlanLevels.length; i++) {
            if (self.form.labRiskPlanLevels[i].riskPlanLevel == 1) {
              a++
            } else if (self.form.labRiskPlanLevels[i].riskPlanLevel == 2) {
              b++
            } else if (self.form.labRiskPlanLevels[i].riskPlanLevel == 3) {
              c++
            } else if (self.form.labRiskPlanLevels[i].riskPlanLevel == 4) {
              d++
            }
          }
          this.$set(this, 'dialogIndex', null)
          this.$set(this, 'dialogTitle', '新增预案规则')
          this.$set(this, 'dialogForm', {
            riskPlanLevel: a == 0 ? 1 : (b == 0 ? 2 : (c == 0 ? 3 : (d == 0 ? 4 : ''))),
            ifExit: true,
            alarmType: ['1', '2'],
            msgTempId: null,
            riskAutoOff: '60',
            bindingSensor: [],
            bindingDevice: []
          })
          this.$set(this, 'businessType', true)
          this.$set(this, 'dialogOpen', true)
        } else if (type == 2) {
          this.$set(this, 'dialogTitle', '编辑预案规则')
          this.$set(this, 'dialogIndex', index)
          let obj = JSON.parse(JSON.stringify(item))
          // obj.bindingDevice.forEach((item)=>{
          //   if(item.typeKey == 'airConditioner'){
          //     item.startOperate = item.startOperate.split('-')
          //     item.endOperate = item.endOperate.split('-')
          //   }
          // })
          this.$set(this, 'dialogForm', {
            id: obj.id,
            riskPlanId: obj.riskPlanId,
            riskPlanLevel: obj.riskPlanLevel,
            ifExit: obj.ifExit,
            alarmType: obj.alarmType?obj.alarmType.split(','):[],
            msgTempId: obj.msgTempId,
            riskAutoOff: obj.riskAutoOff + '',
            bindingSensor: obj.bindingSensor,
            bindingDevice: obj.bindingDevice
          })
          this.alarmChange(obj.alarmType?obj.alarmType.split(','):[])
          let list = []
          for (let i = 0; i < self.form.labRiskPlanLevels.length; i++) {
            if (i != index) {
              list.push(self.form.labRiskPlanLevels[i])
            }
          }
          this.$set(this, 'labRiskPlanLevels', JSON.parse(JSON.stringify(list)))
          this.$set(this, 'dialogOpen', true)
        } else if (type == 3) {
          this.$confirm('确定要删除该预案规则吗?', '警告', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(function() {
            let text = []
            for (let i = 0; i < self.form.labRiskPlanLevels.length; i++) {
              if (index != i) {
                for (let o = 0; o < self.form.labRiskPlanLevels[i].bindingSensor.length; o++) {
                  for (let x = 0; x < self.sensorList.length; x++) {
                    if (self.form.labRiskPlanLevels[i].bindingSensor[o].code == self.sensorList[x].code) {
                      text.push(self.sensorList[x].name)
                    }
                  }
                }
              }
            }
            text = Array.from(new Set(text))
            text = text + ''
            text = text.replace(',', '+')
            let obj = {
              id: item.id,
              startCondition: text,
              riskPlanId: item.riskPlanId
            }
            laboratoryRiskPlanLevelDelete(obj).then((response) => {
              self.msgSuccess(response.message)
              self.laboratoryRiskPlanLevelGetRiskPlanLeveList()
            })
          }).then(() => {
          }).catch(() => {
          })
        }
      },
      //按类型查询模板消息下拉列表
      iotAlarmTemplateFindList() {
        iotAlarmTemplateFindList({ businessType: 1 }).then(response => {
          this.$set(this, 'businessOptions', response.data)
        })
      },
      //音乐列表
      laboratoryMusicFindByType() {
        laboratoryMusicFindByType({ musicType: 1 }).then(response => {
          this.$set(this, 'musicOptions', response.data)
        })
      },
      //传感器
      iotAttributeGetByTypeKey() {
        iotAttributeGetByTypeKey({ typeKey: 'sensor' }).then(response => {
          this.$set(this, 'sensorList', response.data)
          this.$set(this, 'sensorListData', response.data)
        })
      },
      //设备列表
      laboratoryRiskDeviceTypeGetList() {
        laboratoryRiskDeviceTypeGetList({}).then(response => {
          this.$set(this, 'hardwareList', response.data)
        })
      }
    }
  }
</script>
<style lang="scss">
  .add-plan-max-button-color {
    color: #dedede !important;
  }

  //.el-form-item__content{
  //  margin-left: 0px!important;
  //  display: flex;
  //}
</style>
<style scoped lang="scss">
  .autoClose {
    display: flex;
    align-items: center;
    margin-bottom: 24px;
    .autoClose_l {
      width: 100px;
      color: #333;
      font-weight: 500;
      font-size: 14px;
      line-height: 40px !important;
      text-align: right;
      padding: 0 12px 0 0;
      box-sizing: border-box;
    }
    .autoClose_l:before {
      content: "*";
      color: #ff4949;
      margin-right: 4px;
    }

    .autoClose_l2 {
      color: #333;
      font-weight: 500;
      font-size: 14px;
      line-height: 40px !important;
      margin-right: 8px;
    }
    .el-form-item {
      margin: 0px !important;
    }

    .autoClose_l3 {

    }
    .autoClose_l4 {
      color: #333;
      font-weight: 500;
      font-size: 14px;
      line-height: 40px;
      background: #f5f7fa;
      border: 1px solid #DCDFE6;
      border-left: none;
      width: 40px;
      height: 40px;
      text-align: center;
    }
    .autoClose_l5 {
      color: #333;
      font-weight: 500;
      font-size: 14px;
      margin-left: 8px;
    }
  }

  .newAddPlan {
    .newAddPlan-title-box {
      height: 80px;
      display: flex;
      border-bottom: 1px solid #E0E0E0;
      p:nth-child(1) {
        flex: 1;
        margin-left: 20px;
        font-size: 16px;
        color: #0045AF;
        line-height: 80px;
        font-weight: 700;
      }
      p:nth-child(2) {
        font-size: 14px;
        margin-top: 20px;
        margin-right: 20px;
      }
      p:nth-child(3) {
        font-size: 14px;
        width: 130px;
        margin-top: 20px;
        margin-right: 20px;
      }
      p:nth-child(4) {
        font-size: 14px;
        width: 150px;
        margin: 20px;
      }
    }
    .plan-for-max-box {
      flex: 1;
      padding: 0 20px 20px 20px;
      .plan-for-max-box-name-box {
        display: flex;
        .plan-for-max-box-name-button-one {
          width: 80px;
          text-align: center;
          font-size: 14px;
          line-height: 40px;
          margin: 40px 0 0 40px;
          height: 40px;
          border: 1px solid #0183FA;
          border-radius: 4px;
          cursor: pointer;
          color: #0183FA;
        }
        .plan-for-max-box-name-button-two {
          width: 80px;
          text-align: center;
          font-size: 14px;
          line-height: 40px;
          margin: 40px 0 0 40px;
          height: 40px;
          border: 1px solid #999;
          border-radius: 4px;
          cursor: pointer;
          color: #999;
        }
        .plan-for-max-box-name-button-three {
          width: 80px;
          text-align: center;
          font-size: 14px;
          line-height: 40px;
          margin: 40px 0 0 20px;
          height: 40px;
          border: 1px solid #0183FA;
          background-color: #0183FA;
          border-radius: 4px;
          cursor: pointer;
          color: #fff;
        }
      }
      .for-plan-box {
        position: relative;
        border-radius: 10px;
        overflow: hidden;
        box-shadow: 0px 4px 10px 0px rgba(0, 0, 0, 0.302);
        margin-bottom: 24px;
        display: flex;
        .position-title-type {
          position: absolute;
          left: 0;
          top: 0;
          border-bottom-right-radius: 10px;
          width: 84px;
          line-height: 30px;
          font-size: 14px;
          text-align: center;
        }
        .type-color-a {
          color: #0183FA;
          background: #CCE6FE;
        }
        .type-color-b {
          color: #FF9900;
          background: rgb(256, 232, 206);
        }
        .type-color-c {
          color: #FF4800;
          background: rgb(251, 228, 206);
        }
        .type-color-d {
          color: #FF0000;
          background: rgba(248, 206, 205);;
        }
        .for-plan-img-box {
          width: 220px;
          display: flex;
          flex-direction: column;
          .for-plan-img-null-p {
            flex: 1;
          }
          .for-plan-img-box-big {
            display: flex;
            .for-plan-img-box-one {
              margin-left: 100px;
              width: 168px;
              display: flex;
              img {
                height: 60px;
                width: 60px;
              }
              p {
                margin-left: 20px;
                line-height: 50px;
                font-size: 14px;
                color: #333;
              }
            }
            .for-plan-img-box-two {
              display: flex;
              img {
                height: 50px;
                width: 50px;
              }
              p {
                line-height: 50px;
                font-size: 14px;
                color: #333;
              }
            }
          }
        }
        .min-for-text-box {
          width: 1030px;
          padding-top: 21px;
          .min-for-text-box-one {
            min-width: 560px;
            line-height: 30px;
            margin-bottom: 21px;
            margin-right: 40px;
            border-radius: 6px;
            color: #0183FA;
            background: rgb(209, 229, 253);
            display: inline-block;
            div {
              display: flex;
              p:nth-child(1) {
                margin-right: 15px;
                margin-left: 9px;
              }
            }
          }
          .min-for-text-box-two {
            min-width: 560px;
            line-height: 30px;
            margin-bottom: 21px;
            margin-right: 40px;
            border-radius: 6px;
            color: #333;
            background: rgb(253, 242, 227);
            display: inline-block;
            div {
              display: flex;
              p:nth-child(1) {
                margin-right: 15px;
                margin-left: 9px;
              }
              p:nth-child(2) {
                margin-right: 15px;
              }
            }
          }
        }
        .for-button-max-box {
          flex: 1;
          margin: 19px 0;
          border-left: 1px dashed #D8D8D8;
          display: flex;
          div {
            margin: auto 0 auto 34px;
            width: 85px;
            display: flex;
            height: 20px;
            cursor: pointer;
            img {
              height: 14px;
              margin-top: 3px;
            }
            p {
              font-size: 14px;
              margin-left: 9px;
            }
          }
        }
      }
      .plan-for-max-button-box {
        margin: 30px auto;
        display: flex;
        .plan-for-max-button-null {
          flex: 1;
        }
        .plan-for-max-button {
          cursor: pointer;
          color: #0183FA;
          border: 1px dashed #0183FA;
          border-radius: 4px;
          width: 300px;
          line-height: 40px;
          text-align: center;
          font-size: 14px;
        }

      }
    }
  }
</style>
