<template lang="pug">
    el-dialog.dialog( width='86%'  :close-on-click-modal='false' :close-on-press-escape='false' :visible.sync='visible' :append-to-body='true' :before-close="closeForm" )
        div(slot='title')
            span.title-bold {{id ? '编辑联动规则' :'新增联动规则' }}
        div(style="padding:20px;")
          el-form(:model='dataForm' ref='dataForm' :rules='dataRule' size='mini')
            el-form-item( label="联动规则名称:" prop="name")
              el-input(v-model="dataForm.name"  placeholder="联动规则名称" clearable style='width:200px')
            div(style="height:500px")
              <div class="instruct-list-dialog instruct-list-dialog-left">
                  <div :class="[dialogLeftVal == 1?'now':'']" @click="dialogLeftClick(1)"> 报警类型 <span v-if="dialogLeftVal == 1" class="jiao"></span></div>
                  <div :class="[dialogLeftVal == 2?'now':'']" @click="dialogLeftClick(2)">动作<span v-if="dialogLeftVal == 2" class="jiao"></span></div>
              </div>
              <div class="instruct-list-dialog" >
                <div class="header">
                  span 资源点列表 &nbsp;
                  <i style='color:#21ACFC'  class="el-icon-caret-bottom"></i>
                  <el-input v-if="dialogLeftVal == 1" v-model="filterText1"  placeholder="输入关键字进行过滤" style='width:130px;float:right;margin-right:15px' suffix-icon="el-icon-search" size="mini" clearable></el-input>
                  <el-input v-if="dialogLeftVal == 2" v-model="filterText2"  placeholder="输入关键字进行过滤" style='width:130px;float:right;margin-right:15px' suffix-icon="el-icon-search" size="mini" clearable></el-input>
                </div>
                <div class="tree-container" v-if="dialogLeftVal == 1">
                  el-tree.dic_tree(:data="treeData1" accordion :highlight-current='true'  node-key='id' v-loading="loadingFlag" :props="defaultProps" :default-expanded-keys='defaultExpandedKeys1' :filter-node-method="filterNode" :default-expand-all="false" @node-click="handleNodeClick1" ref="tree1")
                    <span class="custom-tree-node" style='width:100%;line-height: 18px;' slot-scope="{ node, data }">
                      <span v-if="node.data.level == 4 && node.data.iconB" class="el-icon-wq-treeIcon1"></span>
                      <span v-if="node.data.level == 4 && !node.data.iconB" class="el-icon-wq-treeIcon"></span>
                      <span v-if="node.data.level == 5 && node.data.name == '视频监控'" class="el-icon-shipin"></span>
                      <span v-if="node.data.level == 5 && node.data.name == '出入口控制'" class="el-icon-churukoukongzhi"></span>
                      <span v-if="node.data.level == 5 && node.data.name == '入侵报警'" class="el-icon-ruqinbaojing"></span>
                      <span v-if="node.data.level == 5 && node.data.name == '安全检查'" class="el-icon-anquanjiancha"></span>
                      <span v-if="node.data.level == 6 " :class="node.data.icon+'7'"></span>
                      <span>&nbsp;{{node.label}}</span>
                    </span>
                </div>
                <div class="tree-container" v-if="dialogLeftVal == 2">
                  el-tree.dic_tree(:data="treeData2" accordion  :highlight-current='true'  node-key='id' v-loading="loadingFlag" :props="defaultProps" :default-expanded-keys='defaultExpandedKeys2' :filter-node-method="filterNode" :default-expand-all="false" @node-click="handleNodeClick2" ref="tree2")
                    <span class="custom-tree-node" style='width:100%;line-height: 18px;' slot-scope="{ node, data }">
                      <span v-if="node.data.level == 4 && node.data.iconB" class="el-icon-wq-treeIcon1"></span>
                      <span v-if="node.data.level == 4 && !node.data.iconB" class="el-icon-wq-treeIcon"></span>
                      <span v-if="node.data.level == 5 && node.data.name == '视频监控'" class="el-icon-shipin"></span>
                      <span v-if="node.data.level == 5 && node.data.name == '出入口控制'" class="el-icon-churukoukongzhi"></span>
                      <span v-if="node.data.level == 5 && node.data.name == '入侵报警'" class="el-icon-ruqinbaojing"></span>
                      <span v-if="node.data.level == 5 && node.data.name == '安全检查'" class="el-icon-anquanjiancha"></span>
                      <span v-if="node.data.level == 6 " :class="node.data.icon+'7'"></span>
                      <span>&nbsp;{{node.label}}</span>
                    </span>
                </div>
              </div>
              div.img_warp
                  img(src='../../../assets/images/toRight.png')
              <div class="instruct-list-dialog instruct-list-dialog-center" style="width:400px">
                <div class="header">
                  span {{dialogLeftVal == 1?'选择报警类型':'选择动作'}}
                </div>
                <div v-if="dialogLeftVal == 1" style="padding-left:20px;">
                  el-form-item(label="" )
                    el-radio-group.radioGroup( v-model="dataForm.sjId")
                      el-radio.item(v-for='item in radioList' :key='item.event_id' :label="item.event_id"   @change='eventChange(item)') {{item.event_name}}
                </div>
                <div v-if="dialogLeftVal == 2" style='padding: 0 20px;'>
                  el-form-item(label="")
                    el-checkbox-group.radioGroup(v-model="checkList")
                      div(v-for='(item,indexItem) in actionList' :key='indexItem')
                        el-checkbox.item( :key='item.id' :label="item" @change='actionChange(item,indexItem)') {{item.title}}
                        <div style="font-size:14px" >
                          <el-form label-width="200px" label-position='right' :inline='false' :ref="'form2'+ item.resourceId + indexItem" :model='item'>
                          <el-form-item style='margin-bottom: 15px' :label='formItem.label' :prop="'formList.' + index + '.value'" v-for='(formItem,index) in item.formList' :key='index' :rules="formItem.rules">
                            <el-input class='mywidth' v-if="formItem.label && formItem.label!=='预置位名称'" size="mini" @input='paramsChange(item,formItem)' v-model.number="formItem.value" @blur="chec(item,indexItem,'formList.' + index + '.value')"/>

                            <el-select class='mywidth' v-if="formItem.label=='预置位名称'" v-model='formItem.value'  size="mini" placeholder="" @change="yzChange(item,indexItem,'formList.' + index + '.value')">
                              <el-option v-for="(item,index) in options" :key="index" :label="item.name" :value="item.id">{{item.name}}</el-option>
                            </el-select>

                          </el-form-item>
                          </el-form>
                        </div>
                </div>
              </div>
              div.img_warp
                img(src='../../../assets/images/toRight.png')
              <div class="instruct-list-dialog instruct-list-dialog-right" style="width:480px;">
                <div class="header">
                    span 联动规则
                </div>
                <div style="padding-left:20px">
                  el-form-item(label="执行模式:" )
                    el-radio-group( v-model="dataForm.executionMode" style='margin-left:25px;')
                      el-radio( :label='1' @change='typeChange') 顺序执行
                      el-radio( :label='2' @change='typeChange') 同时执行
                  el-row.event_warp(:span='24')
                      el-col.event_title(:span='20' :offset='1' ) 报警类型:
                      el-col.event_content( v-if='eventName' :span='22' :offset='2' )
                          span.event_title {{tierName1}}-{{subSystem1}}-{{resourceName1}}-{{resourceCode1}}-{{eventName}}
                          div
                              img( v-if='eventName' src='../../../assets/images/shan.png' @click='eventRemove')
                  el-row.event_warp(:span='24')
                      el-col.event_title(:span='20' :offset='1' ) 动作:
                      el-col.action_content(:span='22' :offset='2' v-for='(item,index) in checkNameList' :key='index' )
                          span.action_title(v-if="!item.params_name1") {{item.stationName}}{{item.deployLocation}}{{item.resourceName}}{{item.action_info}}
                          span.action_title(v-if="item.params_name1&&item.params_name1!=='预置位名称'") {{item.stationName}}{{item.deployLocation}}{{item.resourceName}}{{item.action_info}}{{item.params_value1?',' + (/(.+)?(?:\(|()(.+)(?=\)|))/.exec(item.params_name1))[1]+(item.params_value1)+(item.unit1?item.unit1:''):''}}{{item.params_value2?','+(/(.+)?(?:\(|()(.+)(?=\)|))/.exec(item.params_name2))[1]+item.params_value2+(item.unit2?item.unit2:''):''}}
                          span.action_title(v-if="item.params_name1=='预置位名称'") {{item.stationName}}{{item.deployLocation}}{{item.resourceName}}{{item.action_info}}{{item.params_value1?',' + item.params_name1 + item.csValue + (item.unit1?item.unit1:''):''}}{{item.params_value2?','+(/(.+)?(?:\(|()(.+)(?=\)|))/.exec(item.params_name2))[1]+item.params_value2+(item.unit2?item.unit2:''):''}}
                          div
                              img( v-if='dataForm.executionMode==1&&index!==0' src='../../../assets/images/shang.png'  @click='topHandle(item,index)')
                              img( v-if='dataForm.executionMode==1&&index!==(checkNameList.length-1)' src='../../../assets/images/xia.png'  @click='downHandle(item,index)')
                              img( v-if='item' src='../../../assets/images/shan.png' @click='actionRemove(item,index)')
                </div>
              </div>
        span.dialog-footer(slot='footer')
          div( style="text-align:center;line-height:50px")
            el-button( size='medium' type='primary' @click='cancel') 取消
            el-button( size='medium' type='primary', @click='dataFormSubmit()' v-prevent-re-click) 保存
</template>

<script>
import Vue from 'vue'
export default {
  data() {
    // let numberValidator = (rule, value, callback) => { if (value) { callback(new Error('参数不能为空')) } else if (typeof (value) === 'number') { if (value < 0 || value > 10000) { callback(new Error('参数值超过范围')) } else { callback(new Error('参数只能为数值')) } } else { callback() } }
    return {
      numberValidator: (rule, value, callback) => {
        if (typeof value === 'number') {
          if (value < 0 || value > 10000) { callback(new Error('参数值超过范围')) }
        }
        callback()
      },
      strValidator: (rule, value, callback) => {
        callback()
      },
      yzd: '',
      options: '',
      id: '',
      dialogLeftVal: 1,
      stationId: localStorage.getItem('stationId'),
      defaultExpandedKeys1: [],
      defaultExpandedKeys2: [],
      loadingFlag: false,
      eventId: '',
      show: true,
      clickFlag: false,
      visible: false,
      roleList: [],
      eventName: '',
      actionName: [],
      dataForm: {},
      dzList: [],
      oldResourceId1: '',
      oldResourceId2: '',
      eventResourceTree: {},
      oldSjId: '',
      actionForm: {
        action: []
      },
      checkList: [],
      checkNameList: [],
      checkeds: [],
      actionList: [],
      radioList: [],
      filterText1: '',
      filterText2: '',
      treeData1: [],
      treeData2: [],
      resourceId1: '',
      tierName1: '',
      subSystem1: '',
      resourceName1: '',
      resourceCode1: '',
      resourceName: '',
      stationName: '',
      csValue: '',
      deployLocation: '',
      resourceId2: '',
      defaultProps: {
        children: 'children',
        label: 'name',
        id: 'id'
      },
      dataRule: {
        name: [{ required: true, message: '联动规则名称不能为空', trigger: ['blur', 'change'] },
        { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }]
      }
    }
  },
  watch: {
    filterText1(val) {
      this.$refs.tree1.filter(val)
    },
    filterText2(val) {
      this.$refs.tree2.filter(val)
    }
  },

  methods: {
    yzChange(item, indexItem, prop) {
      this.chec(item, indexItem, prop)
      var id = item.formList[0].value
      this.options.forEach((e) => {
        if (e.id === id) {
          this.csValue = e.name
          return false
        }
      })

      let cList = JSON.parse(JSON.stringify(this.checkNameList))
      for (let i = cList.length - 1; i >= 0; i--) {
        if (
          cList[i].resourceId === item.resourceId &&
          cList[i].action_id === item.id
        ) {
          cList.splice(i, 1)
        }
      }
      let ccList = JSON.parse(JSON.stringify(cList))

      if (this.checkList == null || this.checkList.length == 0) {
        this.actionList.forEach((res) => {
          res.formList.forEach((e) => {
            e.value = ''
          })
        })
      } else {
        this.checkList.forEach((i) => {
          let check = {
            resourceId: '',
            resourceName: '',
            stationName: '',
            deployLocation: '',
            action_id: '',
            action_info: '',
            params_name1: '',
            params_value1: '',
            unit1: '',
            params_name2: '',
            params_value2: '',
            unit2: '',
            csValue: this.csValue
          }
          this.actionList.forEach((res) => {
            if (res.id === i.id) {
              check.action_id = res.id
              check.action_info = res.title
              check.resourceId = res.resourceId
              check.resourceName = res.resourceName
              check.stationName = res.stationName
              check.deployLocation = res.deployLocation

              for (var j = 0; j < res.formList.length; j++) {
                if (j === 0) {
                  check.params_name1 = res.formList[j].label
                  check.params_value1 = res.formList[j].value
                  check.unit1 = res.formList[j].unit
                } else {
                  check.params_name2 = res.formList[j].label
                  check.params_value2 = res.formList[j].value
                  check.unit2 = res.formList[j].unit
                }
              }
            }
            var flag = true
            this.checkList.forEach((el) => {
              if (res.id === el.id) {
                flag = false
              }
            })
            if (flag) {
              res.formList.forEach((e) => {
                e.value = ''
              })
            }
          })
          if (item.id === i.id) {
            ccList.push(check)
          }
        })
      }
      this.checkNameList = []
      this.checkNameList = JSON.parse(JSON.stringify(ccList))
    },
    // 球机下拉列表
    sysPresetList(id) {
      this.$http({
        url: this.$http.adornUrlEq('/sysPreset/queryByResourceId'),
        method: 'post',
        data: {
          resourceId: id,
          stationId: this.stationId,
          page: 1,
          rows: 100
        }
      }).then((data) => {
        if (data && data.code === 0) {
          this.options = data.page
        }
      })
    },
    initTree() {
      this.loadingFlag = true
      this.$http({
        url: this.$http.adornUrl('/liResource/getStationMapTreeList'),
        method: 'post',
        data: {
          stationId: this.stationId //站点id
        }
      }).then((data) => {
        if (data && data.code === 0) {
          this.loadingFlag = false
          this.treeData1 = JSON.parse(JSON.stringify(data.nodes))
          this.treeData2 = JSON.parse(JSON.stringify(data.nodes))
          this.$nextTick(() => {
            // 回显选中
            this.$refs.tree1.setCurrentKey(this.resourceId1 || '')
            if (this.resourceId1) {
              this.defaultExpandedKeys1 = [this.resourceId1]
              this.handleNodeClick1(this.$refs.tree1.getCurrentNode())
            }
          })
        }
      })
    },
    topHandle(item, index) {
      this.checkNameList.splice(index - 1, 0, item)
      this.checkNameList.splice(index + 1, 1)

      var a = this.checkList[index]
      this.checkList.splice(index - 1, 0, a)
      this.checkList.splice(index + 1, 1)
    },
    downHandle(item, index) {
      this.checkNameList.splice(index + 2, 0, item)
      this.checkNameList.splice(index, 1)

      var a = this.checkList[index]
      this.checkList.splice(index + 2, 0, a)
      this.checkList.splice(index, 1)
    },
    // 动作删除
    actionRemove(item, index) {
      // this.checkList.splice(index, 1)
      this.checkNameList.splice(index, 1)

      this.checkList.forEach((e, i) => {
        if (e.id === item.action_id && item.resourceId === e.resourceId) {
          console.log('删除')
          this.checkList.splice(i, 1)
        }
      })

      // console.log('item', item)
      // console.log('checkList', this.checkList)
      // console.log('actionList', this.actionList)

      this.actionList.forEach((res, index) => {
        if (res.id === item.action_id && item.resourceId === res.resourceId) {
          for (var j = 0; j < res.formList.length; j++) {
            res.formList[j].value = null
          }
          this.$set(res, 'checked', false)
          res.formList.forEach((e, index) => {
            this.$set(e, 'rules', [])
          })
          this.$refs['form2' + item.resourceId + index][0].clearValidate()
        }
      })

      // this.checkList = this.checkList.filter(item => item !== id)
      // this.checkNameList = this.checkNameList.filter(item => item !== id)
    },
    // 事件删除
    eventRemove(e) {
      // 删除置空
      this.dataForm.sjId = ''
      this.eventName = ''
    },
    // 执行类型选择
    typeChange(e) {},
    // 事件选择
    eventChange(item) {
      this.eventName = item.event_name
    },
    actionChange(item, indexItem) {
      // console.log('ref', this.$refs['form2' + item.resourceId + indexItem])
      // console.log('item', item)

      // console.log(item)
      // 必填状态修改
      // !item.checked ? this.$set(item, 'checked', true) : this.$set(item, 'checked', !item.checked)
      if (!item.checked) {
        this.$set(item, 'checked', true)
        // 添加校验规则
        let reg = /\((.+?)\)/g
        let reg1 = /([0-9]\d*\.?\d*)|(0\.\d*[1-9])/g

        item.formList.forEach((e, index) => {
          if (e.label) {
            let rules = [{ required: true, message: '参数值不能为空' }]
            if (e.label != '预置位名称') {
              rules.push({ type: 'number', message: '参数值必须为数字' })
              let p = e.label.match(reg).pop().split('-')
              let min = p[0].match(reg1).pop()
              let max = p[1].match(reg1).pop()
              let fun = (rule, value, callback) => {
                if (value < min || value > max) {
                  callback(new Error('参数值在' + min + '-' + max + '之间'))
                } else {
                  callback()
                }
              }
              rules.push({ validator: fun, trigger: ['blur', 'change'] })
              // console.log(min, max)
            }
            Vue.set(e, 'rules', rules)
          }
        })
      } else {
        this.$set(item, 'checked', !item.checked)
        item.formList.forEach((e, index) => {
          Vue.set(e, 'rules', [])
        })
      }
      // this.$nextTick(() => {
        // console.log(this.$refs['form2' + index], '1222222222222222223')
      this.$refs['form2' + item.resourceId + indexItem][0].clearValidate()
        // item.validate()
      // })
      // this.$forceUpdate()
      // console.log(item, '++++++')
      // console.log(this.checkNameList, '1++++++1')
      let a = false
      let flag = false
      this.checkList.forEach(res => {
        if (item.id === res.id && item.resourceId === res.resourceId) {
          a = true
          return false
        }
      })
      if (a) {
          this.checkNameList.forEach(element => {
            if (item.id === element.action_id && item.resourceId === element.resourceId) {
              flag = true
              return false
            }
          })

        // console.log(this.checkList, '2++++++2')
        if (flag) {
          this.$nextTick(() => {
              this.checkList.forEach((e, index) => {
                if (item.id === e.id && item.resourceId === e.resourceId) {
                  this.checkList.splice(index, 1)
                  this.$set(item, 'checked', false)
                  item.formList.forEach((e, index) => {
                    this.$set(e, 'rules', [])
                  })
                  // this.$set(item, 'rules', [])
                  this.$refs['form2' + item.resourceId + indexItem][0].clearValidate()
                }
              })
          })
          this.$message({
            message: '该动作已经添加过,请先删除,再添加',
            type: 'warning'
          })
          return
        }
      }

      if (item.title === '录像下载') {
          let i = 0
          this.checkNameList.forEach(element => {
            if (element.action_info === '录像下载') {
              i++
            }
          })
          // console.log('i:' + i)
          if (i === 4) {
              this.$nextTick(() => {
                this.checkList.forEach((e, index) => {
                  if (item.id === e.id && item.resourceId === e.resourceId) {
                    this.checkList.splice(index, 1)
                    this.$set(item, 'checked', false)
                    this.$refs['form2' + item.resourceId + index][0].clearValidate()
                  }
                })
              })
              this.$message({
                message: '最多只能添加4个录像下载动作',
                type: 'warning'
              })
              return
          }
      }
      // 动作集合
      this.paramsChange(item, null)
    },
    paramsChange(item, formItem) {
      // this.$forceUpdate()
      // this.$refs['form2'].validate((valid) => {
      //   if (valid) console.log(123)
      // })

      let cList = JSON.parse(JSON.stringify(this.checkNameList))
      for (let i = cList.length - 1; i >= 0; i--) {
        if (
          cList[i].resourceId === item.resourceId &&
          cList[i].action_id === item.id
        ) {
          cList.splice(i, 1)
        }
      }
      let ccList = JSON.parse(JSON.stringify(cList))
      // console.log(item, 'item')
      // console.log(this.checkList, 'checkList')
      if (this.checkList == null || this.checkList.length == 0) {
        this.actionList.forEach(res => {
          res.formList.forEach(e => {
              e.value = ''
          })
        })
      } else {
          this.checkList.forEach(i => {
          let check = {
            resourceId: '',
            resourceName: '',
            stationName: '',
            deployLocation: '',
            action_id: '',
            action_info: '',
            params_name1: '',
            params_value1: '',
            unit1: '',
            params_name2: '',
            params_value2: '',
            unit2: '',
            csValue: this.csValue
          }

          this.actionList.forEach(res => {
            if (res.id === i.id) {
              check.action_id = res.id
              check.action_info = res.title
              check.resourceId = res.resourceId
              check.resourceName = res.resourceName
              check.stationName = res.stationName
              check.deployLocation = res.deployLocation

              for (var j = 0; j < res.formList.length; j++) {
                if (j === 0) {
                  check.params_name1 = res.formList[j].label
                  check.params_value1 = res.formList[j].value
                  check.unit1 = res.formList[j].unit
                } else {
                  check.params_name2 = res.formList[j].label
                  check.params_value2 = res.formList[j].value
                  check.unit2 = res.formList[j].unit
                }
              }
            }
            var flag = true
            this.checkList.forEach((el) => {
              if (res.id === el.id) {
                flag = false
              }
            })
            if (flag) {
              // console.log('1111')
              res.formList.forEach(e => {
                // console.log(e.label)
                e.value = ''
              })
            }
          })
          if (item.id === i.id) {
            ccList.push(check)
          }
        })
      }
      this.checkNameList = []
      this.checkNameList = JSON.parse(JSON.stringify(ccList))
    },
    dialogLeftClick(val) {
      this.dialogLeftVal = val
      if (val === 1) {
        this.$nextTick(() => {
          // 回显选中
          if (this.resourceId1) {
            this.$refs.tree1.setCurrentKey(this.resourceId1)
            this.defaultExpandedKeys1 = [this.resourceId1]
            this.handleNodeClick1(this.$refs.tree1.getCurrentNode())
          }
        })
      } else if (val === 2) {
        // this.$nextTick(() => {
        //   // 回显选中
        //   if (this.resourceId2) {
        //     this.$refs.tree2.setCurrentKey(this.resourceId2)
        //     this.defaultExpandedKeys2 = [this.resourceId2]
        //     this.handleNodeClick2(this.$refs.tree2.getCurrentNode())
        //   }
        // })
      }
    },
    handleNodeClick1(data) {
      if (data.id !== this.resourceId1) {
        this.radioList = []
        this.eventName = ''
        this.dataForm.sjId = ''
      }
      if (data.type) {
        var type = data.type
        this.resourceId1 = data.id
        this.tierName1 = data.tierName
        this.subSystem1 = data.subSystem
        this.resourceName1 = data.name
        this.resourceCode1 = data.code
        // this.oldResourceId1 = data.id
        this.$http({
          url: this.$http.adornUrlAlarm(
            '/linkResourceEvent/getEventByResourceType/'
          ),
          method: 'get',
          params: {
              resourceType: type
            }
        }).then((data) => {
          this.radioList = data.list
          if (this.dataForm.sjId) {
            this.radioList.forEach((e) => {
              if (this.dataForm.sjId === e.event_id) {
                let eItem = {
                  event_id: e.event_id,
                  event_name: e.event_name
                }
                this.eventChange(eItem)
                return false
              }
            })
          }
        })
      }
    },
    // 表单校验
    chec(item, index, prop) {
      // console.log(prop)
      this.$refs['form2' + item.resourceId + index][0].validateField(prop, () => {})
      // this.$refs['form2' + item.resourceId + index][0].validate(() => {})
    },
    // 校验是否填写完毕
    checkAll() {
      // console.log('this.actionList', this.actionList)
      let allCheck = true
      this.actionList.forEach((item, index) => {
        // console.log(item.checked)
        if (item.checked) {
          if (this.$refs['form2' + item.resourceId + index][0]) {
            this.$refs['form2' + item.resourceId + index][0].validate(valida => {
            if (!valida) allCheck = false
            })
          }
        }
        // console.log(this.$refs['form2' + index])
      })
      return allCheck
    },
    // 清除所有校验
    cleanCheck() {
      this.actionList.forEach((item, index) => {
          this.$refs['form2' + item.resourceId + index][0].clearValidate()
      })
    },
    handleNodeClick2(data) {
      // 校验是否填写完毕
      if (!this.checkAll()) return

      if (data.id !== this.resourceId2) {
        this.actionList = []
        this.checkList = []
        this.dzList = []
        this.csValue = ''
        // this.checkNameList = []
      }
      if (data.type) {
        // 点击动作选择资源点列表为球机时
        if (data.type == 'ece0b8b2db27411886254e81134988a3') {
          this.sysPresetList(data.id) //// 预置点球机下拉数据
        }
        var type = data.type
        this.resourceId2 = data.id
        let resourceId = data.id
        let resourceName = data.name
        let stationName = data.stationName
        let deployLocation = data.deployLocation
        this.$http({
          url: this.$http.adornUrlAlarm(
            '/linkResourceAction/getActionByResourceType/'
          ),
          method: 'get',
          params: {
                  resourceType: type,
                  stationId: this.stationId
                  }
        }).then((data) => {
          let newArr = data.list.map((e) => {
            let value1 = ''
            let value2 = ''
            // if (this.checkNameList && this.checkNameList.length > 0) {
            //   this.checkNameList.forEach(el => {
            //     if (e.action_id === el.action_id) {
            //       value1 = el.params_value1
            //       value2 = el.params_value2
            //     }
            //   })
            // }
            let formList = []
            formList.push({
              label: e.params_name1,
              value: value1,
              unit: e.unit1
            })
            if (e.params_name2) {
              formList.push({
                label: e.params_name2,
                value: value2,
                unit: e.unit2
              })
            }
            return {
              id: e.action_id,
              title: e.action_info,
              formList: formList,
              resourceId: resourceId,
              resourceName: resourceName,
              stationName: stationName,
              deployLocation: deployLocation
            }
          })
          this.actionList = newArr
        })
      }
    },
    // 树节点过滤
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    init(id) {
      this.csValue = ''
      this.id = id || ''
      this.visible = true
      if (id) {
        this.$http({
          url: this.$http.adornUrlAlarm('/linkLinkageRule/getId/'),
          method: 'get',
          params: {
                    id: id,
                    stationId: this.stationId
                  }
          }).then((data) => {
            // console.log(data.bean, '++++')
            this.dataForm = data.bean
            this.resourceId1 = data.bean.resourceId
            // this.resourceId2 = data.dzList[0].resource_id
            // this.oldResourceId1 = data.bean.resourceId
            // this.oldResourceId2 = data.dzList[0].resource_id
            // this.oldSjId = data.bean.sjId
            // this.resourceName = data.dzList[0].resourceName
            // this.stationName = data.dzList[0].stationName
            // this.deployLocation = data.dzList[0].deployLocation
            this.dzList = data.dzList
            // this.checkList = data.dzList.map(e => {
            //   return e.action_info
            // })

            this.checkNameList = this.dzList.map((e) => {
              return {
                resourceId: e.resource_id,
                resourceName: e.resourceName,
                stationName: e.stationName,
                deployLocation: e.deployLocation,
                action_id: e.action_id,
                action_info: e.action_info,
                params_name1: e.params_name1,
                params_value1: e.params_value1,
                unit1: e.unit1,
                params_name2: e.params_name2,
                params_value2: e.params_value2,
                unit2: e.unit2,
                csValue: e.presetName
              }
            })
            // this.checkNameList = this.dzList.map(e => {
            //   return {
            //     resourceId: e.resource_id,
            //     action_id: e.action_id,
            //     action_info: e.action_info,
            //     params_name1: e.params_name1,
            //     params_value1: e.params_value1,
            //     unit1: e.unit1,
            //     params_name2: e.params_name2,
            //     params_value2: e.params_value2,
            //     unit2: e.unit2,
            //     csValue: e.presetName || ''
            //   }
            // })
          })
          .then(() => {
            this.initTree()
          })
      } else {
        this.dataForm = {}
        this.initTree()
      }
    },

    // 表单提交
    dataFormSubmit() {
      //校验是否全部填写
      if (!this.checkAll()) return
      // debugger
      if (this.dataForm.name === '' || this.dataForm.name === undefined) {
        this.$message({
          message: '联动规则名称不能为空',
          type: 'warning'
        })
        return
      }

      if (this.resourceId1 === '' || this.resourceId1 === undefined) {
        this.$message({
          message: '报警类型关联资源点不能为空',
          type: 'warning'
        })
        return
      }

      if (this.dataForm.sjId === '' || this.dataForm.sjId === undefined) {
        this.$message({
          message: '报警类型不能为空',
          type: 'warning'
        })
        return
      }

      // if (this.resourceId2 === '' || this.resourceId2 === undefined) {
      //   this.$message({
      //     message: '动作关联资源点不能为空',
      //     type: 'warning'
      //   })
      //   return
      // }

      if (this.checkNameList.length === 0 || this.checkNameList === null) {
        this.$message({
          message: '动作不能为空',
          type: 'warning'
        })
        return
      } else if (this.checkNameList && this.checkNameList.length > 0) {
        var flag = false
        var vflag = false
        this.checkNameList.forEach((e) => {
          if (
            (e.params_name1 &&
              (e.params_value1 === null ||
                e.params_value1 === '' ||
                e.params_value1 === undefined)) ||
            (e.params_name2 &&
              (e.params_value2 === null ||
                e.params_value2 === '' ||
                e.params_value1 === undefined))
          ) {
            flag = true
            return false
          } else {
            if (e.params_value1) {
              if (e.params_name1 != '预置位名称') {
                var fw = /(.+)?(?:\(|()(.+)(?=\)|))/.exec(e.params_name1)[2]
                let fws = fw.split('-')
                var min =
                  fws[0].indexOf(e.unit1) > -1
                    ? fws[0].substring(0, fws[0].indexOf(e.unit1))
                    : fws[0]
                var max =
                  fws[1].indexOf(e.unit1) > -1
                    ? fws[1].substring(0, fws[1].indexOf(e.unit1))
                    : fws[1]

                if (
                  Number(e.params_value1) < Number(min) ||
                  Number(e.params_value1) > Number(max)
                ) {
                  vflag = true
                  return false
                }
              }
            }

            if (e.params_value2) {
              var fw2 = /(.+)?(?:\(|()(.+)(?=\)|))/.exec(e.params_name2)[2]
              let fws2 = fw2.split('-')
              var min2 =
                fws2[0].indexOf(e.unit2) > -1
                  ? fws2[0].substring(0, fws2[0].indexOf(e.unit2))
                  : fws2[0]
              var max2 =
                fws2[1].indexOf(e.unit2) > -1
                  ? fws2[1].substring(0, fws2[1].indexOf(e.unit2))
                  : fws2[1]

              if (
                Number(e.params_value2) < Number(min2) ||
                Number(e.params_value2) > Number(max2)
              ) {
                vflag = true
                return false
              }
            }
          }
        })
        if (flag) {
          this.$message({
            message: '动作参数值不能为空',
            type: 'warning'
          })
          return
        }

        if (vflag) {
          this.$message({
            message: '有参数值不在范围中',
            type: 'warning'
          })
          return
        }
      }

      if (
        this.dataForm.executionMode === '' ||
        this.dataForm.executionMode === undefined
      ) {
        this.$message({
          message: '执行模式不能为空',
          type: 'warning'
        })
        return
      }

      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrlAlarm(
              `/linkLinkageRule/${!this.dataForm.id ? 'save' : 'update'}`
            ),
            method: 'post',
            data: {
              id: this.id,
              name: this.dataForm.name,
              resourceId: this.resourceId1,
              sjId: this.dataForm.sjId,
              dzList: this.checkNameList,
              stationId: this.stationId,
              executionMode: this.dataForm.executionMode
            }
          }).then((data) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.dialogLeftVal = 1
                  this.dataForm = {}
                  this.defaultExpandedKeys1 = []
                  this.defaultExpandedKeys2 = []
                  this.treeData1 = []
                  this.treeData2 = []
                  this.resourceId1 = ''
                  this.resourceName = ''
                  this.stationName = ''
                  this.deployLocation = ''
                  this.resourceId2 = ''
                  this.radioList = []
                  this.eventName = ''
                  this.actionList = []
                  this.dzList = []
                  this.checkList = []
                  this.checkNameList = []
                  this.visible = false
                  this.$emit('refreshdatalist')
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      })
    },
    closeForm() {
      // this.dataForm = {}
      this.dialogLeftVal = 1
      this.resourceId1 = ''
      this.defaultExpandedKeys1 = []
      this.defaultExpandedKeys2 = []
      this.treeData1 = []
      this.treeData2 = []
      this.resourceName = ''
      this.stationName = ''
      this.deployLocation = ''
      this.resourceId2 = ''
      this.radioList = []
      this.eventName = ''
      this.actionList = []
      this.dzList = []
      this.checkList = []
      this.checkNameList = []
      this.$refs.dataForm.resetFields()
      this.visible = false
    },
    //取消
    cancel() {
      this.$confirm('确认取消?', this.id ? '编辑联动规则' : '新增联动规则', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.closeForm()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消退出'
          })
        })
    }
  }
}
</script>
<style lang="scss" scoped>
.dic_tree {
  background: #f4f4f4;
  font-size: 14px;
  transform: translateX(-6px);
  margin-top: 20px;
}
.dic_tree /deep/ .el-tree-node__content {
  padding-left: 0px !important;
}

.dic_tree /deep/ .el-tree-node {
  position: relative;
  padding-left: 16px;
}

.dic_tree /deep/ .el-tree-node__children {
  padding-left: 10px;
}

.dic_tree /deep/ .el-tree-node :last-child:before {
  height: 38px;
}

.dic_tree /deep/ .el-tree > .el-tree-node:before {
  border-left: none;
}

.tree-container /deep/ .el-tree > .el-tree-node:after {
  border-top: none;
}

.dic_tree /deep/ .el-tree-node:before {
  content: "";
  left: -4px;
  position: absolute;
  right: auto;
  border-width: 1px;
}

.dic_tree /deep/ .el-tree-node:after {
  content: "";
  left: -4px;
  position: absolute;
  right: auto;
  border-width: 1px;
}

.dic_tree /deep/ .el-tree-node:before {
  border-left: 1px dashed #bfbfbf;
  bottom: 0px;
  height: 100%;
  top: -26px;
  width: 1px;
}

.dic_tree /deep/ .el-tree-node:after {
  border-top: 1px dashed #bfbfbf;
  height: 20px;
  top: 12px;
  width: 35px;
}
.tree-container /deep/ .el-tree > .el-tree-node:after {
  border-top: none;
}

.tree-container {
  /* 树的parent,样式自定 */
}
.dic_tree /deep/ .el-tree-node__expand-icon.expanded {
  transform: rotate(0deg);
  -webkit-transform: rotate(0deg);
}
.dic_tree /deep/ .el-icon-caret-right:before {
  background: url("../../../assets/images/add.png");
  content: "";
  display: block;
  width: 18px;
  height: 18px;
  font-size: 18px;
  background-size: 18px;
}
.dic_tree
  /deep/
  .el-tree-node__expand-icon.expanded.el-icon-caret-right:before {
  background: url("../../../assets/images/sub.png");
  content: "";
  display: block;
  width: 18px;
  height: 18px;
  font-size: 18px;
  background-size: 18px;
}
.dic_tree /deep/.el-tree-node__content > .el-tree-node__expand-icon{
  padding:0 2px 0 2px;
}
.dic_tree /deep/.el-tree-node__expand-icon.is-leaf::before {
  opacity: 0;
}
.instruct-list-dialog {
  height: 500px;
  width: 330px;
  float: left;
  background: #fff;
  box-shadow: 0px 2px 8px 0px rgba(0, 0, 0, 0.2);
  overflow: auto;
  .header {
    height: 40px;
    background: #eef8ff;
    line-height: 40px;
    padding-left: 15px;
    font-weight: 400;
    margin-bottom: 20px;
    span {
      font-family: Microsoft YaHei;
      font-weight: bold;
      font-size: 14px;
    }
    /deep/ .el-input--mini .el-icon-search {
      line-height: 28px;
      color: #35aff8;
      font-weight: bold;
    }
  }
  .el-tree {
    background: rgba(255, 255, 255, 0);
  }
  .el-tree-node__content:hover {
    background: #35aff8;
  }
  .el-input {
    width: 90%;
  }
}
.checkInput {
  /deep/.el-input__inner {
    padding: 0 5px;
  }
}
.instruct-list-dialog-left {
  margin-right: 20px;
  margin-left: 10px;
  width: 70px;
  background: rgba(255, 255, 255, 0);
  box-shadow: none;
  div {
    height: 250px;
    width: 60px;
    font-size: 16px;
    background: #f4f4f4;
    cursor: pointer;
    position: relative;
    display:flex;
    -webkit-display:flex;
    flex-direction:column; 
    justify-content:center;
     writing-mode: vertical-rl;
    writing-mode: tb-rl;
    text-align: center;
    letter-spacing: 20px;
  }
  .now {
    background: #35aff8;
    color: #fff;
  }
  .jiao {
    width: 0;
    height: 0;
    position: absolute;
    right: -7px;
    top: 110px;
    border-top: 7px solid transparent;
    border-left: 7px solid #35aff8;
    border-bottom: 7px solid transparent;
  }
}
</style>

<style lang="scss">
.dialog > .el-card__header {
  padding: 0 !important;
}

.dialog .el-dialog__body {
  padding: 0;
  color: #606266;
  font-family: Microsoft YaHei;
  font-size: 14px;
  word-break: break-all;
}

.container {
  display: flex;
  display: -moz-box; /* Firefox */
  display: -ms-flexbox; /* IE10 */
  display: -webkit-box; /* Safari */
  display: -webkit-flex; /* Chrome, WebKit */
}
.img_warp {
  display: flex;
  align-items: center;
  margin: 240px 25px 0 25px;
  float: left;
  img {
    width: 50px;
    height: 18px;
  }
}
.treeBox {
  width: 400px;
  height: 600px;
  overflow: auto;
}

.tabBox {
  width: 400px;
  padding: 0;
  margin-left: 20px;

  .el-tabs__nav-scroll {
    background: #eef8ff;
  }
}

.radioGroup {
  display: flex;
  flex-direction: column;

  .item {
    margin-top: 10px;
  }
}

.rule_warp .el-card__header {
  height: 42px;
  line-height: 42px;
  background: #eef8ff;
  padding: 0 0 0 10px !important;
}

.event_warp {
  width: 440px;
  padding-bottom: 10px;
  background: rgba(246, 247, 251, 1);

  .event_title {
    font-size: 14px;
    font-family: Microsoft YaHei;
    font-weight: 400;
    color: rgba(51, 51, 51, 1);
    padding: 10px;
  }

  .event_content {
    height: 70px;
    // line-height: 50px;
    // text-indent: 20px;
    background: #fff;
    border-top-left-radius: 35px;
    border-bottom-left-radius: 35px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
    box-shadow: 0px 0px 8px 0px rgba(0, 0, 0, 0.05);

    .event_title {
      width: 300px;
      padding-left: 20px;
    }

    img {
      display: inline-block;
      width: 18px;
      height: 18px;
      vertical-align: middle;
      margin-right: 20px;
    }
  }

  .action_content {
    height: 70px;
    background: #fff;
    border-top-left-radius: 35px;
    border-bottom-left-radius: 35px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
    box-shadow: 0px 0px 8px 0px rgba(0, 0, 0, 0.05);

    .action_title {
      width: 260px;
      padding-left: 20px;
    }

    img {
      display: inline-block;
      width: 18px;
      height: 18px;
      vertical-align: middle;
      margin-right: 20px;
    }
  }
}
</style>