<template>
  <div>
    <add-page-layout>
      <div slot="Header-Content">
        <span>关联告警策略 {{ opType }}</span>
        <i class="el-icon-close close" @click="$router.go(-1)" />
      </div>
      <div slot="Form-Content">
        <div style="margin:15px">
          <el-row>
            <el-steps :active="active" align-center finish-status="success">
              <el-step title="告警规则" description="新增一条关联告警规则基础信息" />
              <el-step title="补充逻辑规则" description="对新增的规则进行完善，也可以跳过根节点需先新增逻辑" />
            </el-steps>
          </el-row>
          <el-row v-show="active == 0" style="margin-top:20px">
            <el-form ref="addruleForm" :model="addNewRuleForm" label-width="140px">
              <el-row>
                <el-col :span="24">
                  <el-form-item
                    label="规则名称:"
                    :rules="[{ required: true, message: '规则名称不能为空', trigger: 'change' }]"
                    prop="name"
                  >
                    <el-input
                      v-model="addNewRuleForm.name"
                      placeholder="请输入..."
                      :disabled="disabled"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item
                    label="可信度:"
                    prop="reliability"
                    :rules="[{ required: false, message: '请输入0-100的数字', trigger: 'change',type:'number',max:100,min:0 }]"
                  >
                    <el-input-number
                      v-model="addNewRuleForm.reliability"
                      :min="0"
                      :max="100"
                      style="width:100%"
                      placeholder="请输入0-100"
                      :disabled="disabled"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    label="匹配次数:"
                    :rules="[{ required: true, message: '匹配次数不能为空', trigger: 'change',type:'number' }]"
                    prop="matchCount"
                  >
                    <el-input-number
                      v-model="addNewRuleForm.matchCount"
                      :min="0"
                      style="width:100%"
                      placeholder="请输入..."
                      :disabled="disabled"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item
                    label="规则等级:"
                    :rules="[{ required: true, message: '告警级别不能为空', trigger: 'change' }]"
                    prop="ruleLevel"
                  >
                    <el-select v-model="addNewRuleForm.ruleLevel" :disabled="disabled">
                      <el-option
                        v-for="item in ruleLevel"
                        :key="item.dataId"
                        :label="item.dataName"
                        :value="item.dataId"
                      >{{ item.dataName }}
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    label="超时时间（秒）:"
                    :rules="[{ required: true, message: '超时时间不能为空', trigger: 'change' ,type:'number'}]"
                    prop="timeOut"
                  >
                    <el-input-number
                      v-model="addNewRuleForm.timeOut"
                      style="width:100%"
                      :min="0"
                      placeholder="请输入..."
                      :disabled="disabled"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item
                    label="关联类型:"
                    :rules="[{ required: true, message: '关联类型不能为空', trigger: 'change'}]"
                    prop="type"
                  >
                    <el-select v-model="addNewRuleForm.type" :disabled="disabled">
                      <el-option
                        v-for="item in associateType"
                        :key="item.dataId"
                        :value="item.dataId"
                        :label="item.dataName"
                      >{{ item.dataName }}
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    label="告警类型:"
                    :rules="[{ required: true, message: '告警类型不能为空', trigger: 'change'}]"
                    prop="alertTypeList"
                  >
                    <el-cascader
                      style="width: 100%"
                      v-model="addNewRuleForm.alertTypeList"
                      :options="bigdataAlarmTypeTree"
                      :props="{ expandTrigger: 'hover',value:'key', label:'label',children:'children'}"
                      :disabled="disabled"
                    >
                      <!--                      <el-option-->
                      <!--                        v-for="item in bigdataAlarmTypeTree"-->
                      <!--                        :key="item.key"-->
                      <!--                        :value="item.key"-->
                      <!--                        :label="item.label"-->
                      <!--                        :children="item.children"-->
                      <!--                      >{{ item.dataName }}-->
                      <!--                      </el-option>-->
                    </el-cascader>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item
                    label="攻击链阶段:"
                    prop="attackChainStage"
                    :rules="[{ required: true, message: '攻击链阶段不能为空', trigger: 'change'}]"
                  >
                    <el-select v-model="addNewRuleForm.attackChainStage" :disabled="disabled">
                      <el-option
                        v-for="item in attackType"
                        :key="item.dataId"
                        :value="item.dataId"
                        :label="item.dataName"
                      >{{ item.dataName }}
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    label="组件:"
                    :rules="[{ required: true,message: '组件id不能为空', trigger: 'change'}]"
                    prop="componentId"
                  >
                    <el-select v-model="addNewRuleForm.componentId" multiple :disabled="disabled">
                      <el-option
                        v-for="item in allComponent"
                        :key="item.dataId"
                        :value="item.dataId"
                        :label="item.dataName"
                      >{{ item.dataName }}
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item
                    label="归并方式:"
                    prop="uniteWay"
                    :rules="[{ required: true,type:'array', message: '归并方式不能为空', trigger: 'change'}]"
                  >
                    <el-select v-model="addNewRuleForm.uniteWay" multiple :disabled="disabled">
                      <el-option
                        v-for="item in uniteWay"
                        :key="item.dataId"
                        :value="item.dataId"
                        :label="item.dataName"
                      >{{ item.dataName }}
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item
                    label="规则描述:"
                    prop="description"
                  >
                    <el-input
                      v-model="addNewRuleForm.description"
                      type="textarea"
                      :rows="4"
                      placeholder="请输入..."
                      :disabled="disabled"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item
                    label="整改建议:"
                    prop="rectification"
                  >
                    <el-input
                      v-model="addNewRuleForm.rectification"
                      type="textarea"
                      :rows="4"
                      placeholder="请输入..."
                      :disabled="disabled"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <!-- <el-row>
            <el-col :span="12">
              <el-form-item label="是否启用:" prop="enableTag">
                  <el-select v-model="addNewRuleForm.enableTag" :disabled="disabled">
                    <el-option
                    v-for="item in [{value:1,label:'是'},{value:0,label:'否'}]"
                    :value="item.value"
                    :key="item.value"
                    >{{item.label}}
                    </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="是否有效:" prop="validTag">
                  <el-select v-model="addNewRuleForm.validTag" :disabled="disabled">
                    <el-option
                    v-for="item in [{value:1,label:'是'},{value:0,label:'否'}]"
                    :value="item.value"
                    :key="item.value"
                    >{{item.label}}
                    </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row> -->

            </el-form>
          </el-row>
        </div>
        <!--逻辑规则-->
        <el-row v-show="active == 1">
          <!-- <el-row class="rowBorder"> -->
          <el-col :span="24">
            <div class="sub-title">
              规则配置：
            </div>
            <div style="width:100%;border:1px solid #b7b7b7;margin: 10px;overflow-x: auto;min-height: 340px;position:relative;">
              <vue2-org-tree
                :data="tree"
                horizontal
                :disabled="disabled"
                :label-class-name="labelClass"
                :render-content="renderContent"
                @on-expand="onAddChildren"
                @on-delete="onDelete"
                @on-node-click="onNodeClick"
                @on-node-mouseover="onNodeMouseOver"
                @on-node-mouseout="onNodeMouseOut"
              />
            </div>
            <div class="sub-title">
              输出字段：
            </div>
            <div>
              <el-row v-for="(item,index) in output" :key="index" style="margin:10px">
                <el-col :span="3">
                  <el-select v-model="item.logicNameId" :disabled="disabled" placeholder="请选择">
                    <el-option
                      v-for="item in logicNameOutputList"
                      :key="item.dataId"
                      :label="item.dataName"
                      :value="item.dataId"
                    >{{ item.dataName }}</el-option>
                  </el-select>
                </el-col>
                <el-col :span="3">
                  <el-select v-model="item.field" :disabled="disabled" placeholder="请选择">
                    <el-option
                      v-for="item in sourceAssociation"
                      :key="item.dataId"
                      :label="item.dataName"
                      :value="item.dataId"
                    >{{ item.dataName }}</el-option>
                  </el-select>
                </el-col>
                <el-col :span="2">
                  <div class="rule-rename">
                    重命名为
                  </div>
                </el-col>
                <el-col :span="3">
                  <el-select v-model="item.alarmField" :disabled="disabled" placeholder="请选择">
                    <el-option
                      v-for="item in alarmOutputRules"
                      :key="item.dataId"
                      :label="item.dataName"
                      :value="item.dataId"
                    >{{ item.dataName }}</el-option>
                  </el-select>
                </el-col>
                <el-col v-show="!disabled" :span="2">
                  <div class="rule-rename">
                    <i v-show="index == output.length-1" class="el-icon-circle-plus-outline" color="green" size="24" @click="addOutput" />
                    <i class="el-icon-remove-outline" color="red" size="24" @click="removeOutput(index)" />
                  </div>
                </el-col>
              </el-row>

            </div>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="7" :offset="8">
            <div style="width:200px;margin: 0 auto 10px auto">
              <el-button
                v-show="active!=0"
                style="margin-left:5px"
                icon="arrow-left"
                @click="backLast"
              >上一步 </el-button>
              <el-button
                v-show="nextShow"
                style="margin-left:5px"
                type="primary"
                :icon="nextIcon"
                @click="next"
              ><span>{{ nextName }}</span> </el-button>
            </div>
          </el-col>
        </el-row>

      </div>

      <manager-dialog
        v-model="addnewLogicVisible"
        title="新增节点"
      >
        <el-row>
          <el-form ref="addNewNodeRef" :model="addNewNodeForm" :rules="ruleAddNewNode" label-width="80px">
            <el-form-item label="节点类型" prop="nodeType">
              <el-select v-model="addNewNodeForm.nodeType" :disabled="disabled" placeholder="请选择">
                <el-option
                  v-for="item in statics.nodeType"
                  :key="item.dataId"
                  :label="item.dataName"
                  :value="item.dataId"
                >{{ item.dataName }}</el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </el-row>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addnewLogicVisible=false">关闭</el-button>
          <el-button type="primary" @click="addnewNode('logics')">确定</el-button>
        </div>
      </manager-dialog>

      <manager-dialog
        v-model="addnewRuleVisible"
        title="新增规则"
      >
        <el-row>
          <el-form ref="addNewRuleRef" :model="addNewNodeForm" :rules="ruleAddNewNode" label-width="80px">
            <el-form-item label="节点类型" prop="logicType">
              <el-select v-model="addNewNodeForm.logicType" :disabled="disabled" placeholder="请选择">
                <el-option
                  v-for="item in logicType"
                  :key="item.dataId"
                  :label="item.dataName"
                  :value="item.dataId"
                >{{ item.dataName }}</el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </el-row>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addnewRuleVisible=false">关闭</el-button>
          <el-button type="primary" @click="addnewNode('details')">确定</el-button>
        </div>
      </manager-dialog>
    </add-page-layout>

  </div>
</template>

<script>
import Vue2OrgTree from '@ability/components/OrgTree'
import { generateUUID } from '@ability/utils/index'
import {
  addBigdataAssociationRules,
  updateBigdataAssociationRules,
  queryBigdataAssociationRules
} from './api/alarm-result'

export default {
  name: 'AlarmStrategyAdd',
  components: {
    Vue2OrgTree
  },
  data() {
    return {
      addNewNodeForm: {
        nodeType: '',
        logicType: ''
      },
      ruleAddNewNode: {
        nodeType: [
          { required: true, message: '请选择节点类型', trigger: 'change' }
        ],
        logicType: [
          { required: true, message: '请选择节点类型', trigger: 'change' }
        ]
      },
      opType: '新增',
      oper: '',
      filterText: '',
      nextShow: null,
      nextIcon: null,
      nextName: null,
      active: 0,
      chooseEventvisible: false,
      addnewLogicVisible: false,
      addnewRuleVisible: false,
      // 新增规则
      addNewRuleForm: {
        alertType: null,
        alertTypeList: [],
        id: null,
        type: null,
        name: null,
        reliability: null,
        ruleLevel: null,
        timeOut: null,
        description: null,
        enableTag: 1,
        componentId: [],
        validTag: 1,
        uniteWay: [],
        matchCount: null
      },
      disabled: false,
      logics: {

      },
      statics: {
        defaultprops: {
          value: 'dataId',
          label: 'label',
          children: 'children'
        },
        nodeType: [
          {
            dataId: '1',
            dataName: '逻辑节点'
          },
          {
            dataId: '0',
            dataName: '规则节点'
          }
        ],
        logicNameList: [{
          dataId: 1,
          dataName: '1-AND'
        }
        ]
      },

      // 树型组织图-model,默认创建一个根节点
      tree: {
        logicNameId: 1,
        logicName: '',
        type: null,
        renderType: 'Logic',
        // initValue:null,
        // initData:[],
        // isAddable:true,
        time: 1,
        overtime: 1,
        dataSource: null, // 默认日志
        peerNode: false,
        children: []
      },
      selectedLoginId: null,
      maxLogicNum: 1,
      logicNodeDefault: {},
      ruleNodeDefault: {},
      // 规则输出结果
      output: [{
        'logicNameId': null,
        'field': null,
        'alarmField': null,
        'logicName': null
      }]
    }
  },
  computed: {
    bigdataAlarmTypeParent() {
      return this.$store.state.alarm.newAlarmTypeParent
    },
    bigdataAlarmTypeSub() {
      return this.$store.state.alarm.newAlarmTypeSub
    },
    reliability() {
      return this.$store.state.alarm.reliability
    },
    ruleLevel() {
      return this.$store.state.alarm.ruleLevel
    },
    associateType() {
      return this.$store.state.alarm.type
    },
    alertType() {
      return this.$store.state.alarm.newAlarmType
    },
    alertTypeParent() {
      return this.$store.state.alarm.newAlarmTypeParent
    },
    alertTypeSub() {
      return this.$store.state.alarm.newAlarmTypeSub
    },
    bigdataAlarmTypeTree() {
      console.log(this.$store.state.alarm.newAlarmTypeTree)
      return this.$store.state.alarm.newAlarmTypeTree
    },
    attackType() {
      return this.$store.state.alarm.attackType
    },
    allComponent() {
      return this.$store.state.alarm.allComponent
    },
    uniteWay() {
      return this.$store.state.alarm.uniteWay
    },
    logicType() {
      return this.$store.state.alarm.logicType
    },
    operationType() {
      return this.$store.state.alarm.operationType
    },
    matchType() {
      return this.$store.state.alarm.matchType
    },
    datasourceType() {
      return this.$store.state.alarm.datasourceType
    },
    dataSet() {
      return this.$store.state.alarm.dataSet
    },
    singleSourceAssociation() {
      return this.$store.state.alarm.singleSourceAssociation
    },
    multiSourceAssociationFlow() {
      return this.$store.state.alarm.multiSourceAssociationFlow
    },
    multiSourceAssociation() {
      return this.$store.state.alarm.multiSourceAssociation
    },
    sourceAssociation() {
      if (this.addNewRuleForm.type == '1') {
        return this.$store.state.alarm.singleSourceAssociation
      } else {
        return this.$store.state.alarm.multiSourceAssociation
      }
    },
    sourceAssociationWithRelated() {
      let temp = []
      if (this.addNewRuleForm.type == '1') {
        temp = JSON.parse(JSON.stringify(this.$store.state.alarm.singleSourceAssociation))
      } else {
        temp = JSON.parse(JSON.stringify(this.$store.state.alarm.multiSourceAssociation))
      }
      temp.push(
        {
          dataId: 'SAME',
          dataName: 'SAME'
        }
      )
      temp.push(
        {
          dataId: 'DISTINCT',
          dataName: 'DISTINCT'
        }
      )
      return temp
    },
    alarmOutputRules() {
      return this.$store.state.alarm.alarmOutputRules
    },
    logicNameOutputList() {
      return this.statics.logicNameList.filter(item => {
        return item.dataName.indexOf('RULE') != -1
      })
    }
  },
  watch: {
    active: function() {
      this.nextButton()
    }
  },
  created() {
    // this.tree.initValue = this.logicType[0].dataId
    this.tree.type = this.logicType[0].dataId
    this.tree.dataSource = this.datasourceType[0].dataId
    this.tree.logicName = this.tree.logicNameId + '-' + this.logicType[0].dataName
    this.logicNodeDefault = {
      logicName: this.logicType[0].dataName,
      type: this.logicType[0].dataId,
      renderType: 'Logic',
      // initValue:this.logicType[0].dataId,
      // isAddable:true,
      // expand : true,
      time: 1,
      overtime: 1,
      dataSource: this.datasourceType[0].dataId, // 默认日志
      peerNode: false,
      children: []
    }
    this.ruleNodeDefault = {
      detailViewId: null,
      detailId: null,
      matchType: '1', // 默认-用户输入值
      field: null,
      operation: this.operationType[0].dataId,
      renderType: 'Rule',
      rlogicId: null,
      key: null,
      rangekey: null,
      fileList: []
    }
  },
  mounted() {
    this.oper = this.$route.params.oper
    const id = this.$route.params.id
    this.nextButton()
    if (this.oper == 'add') {
      this.opType = '新增'
      this.disabled = false
    } else if (this.oper == 'detail') {
      this.opType = '查看'
      this.disabled = true
      this.backFill(id)
    } else {
      this.opType = '编辑'
      this.disabled = false
      this.backFill(id)
    }
  },
  methods: {
    ipValidate(rule, value, callback) {
      console.log(value)
      //
      if (value) {
        if (value === 'ANY') {
          callback()
        } else {
          if (value.indexOf(',') > 0) {
            const arr = value.split(',')
            for (const ip in arr) {
              var reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/
              if (!reg.test(ip)) {
                callback('请输入合法的ip')
              } else {
                callback()
              }
            }
          } else {
            var reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/
            if (!reg.test(value)) {
              callback('请输入合法的ip')
            } else {
              callback()
            }
          }
        }
      } else {
        callback()
      }
    },
    // 步骤
    nextButton: function() {
      if (this.active == 0) {
        // 第一步
        if (this.oper == 'detail') {
          this.nextName = '下一步'
          this.nextShow = true
          this.nextIcon = 'ios-arrow-forward'
        } else {
          this.nextName = '下一步'
          this.nextShow = true
          this.nextIcon = 'md-checkmark'
        }
      } else if (this.active == 1) {
        // 第二步，且逻辑规则关闭状态
        if (this.oper == 'detail') {
          this.nextShow = false
        } else {
          this.nextName = '完成'
          this.nextShow = true
          this.nextIcon = 'md-checkmark'
        }
      } else if (this.active == 1) {
        // 第二步，且逻辑规则开启状态
        if (this.oper == 'detail') {
          this.nextShow = false
        } else if (this.oper == 'add') {
          this.nextName = '下一步'
          this.nextShow = true
          this.nextIcon = 'md-checkmark'
        } else if (this.oper == 'modify') {
          this.nextName = '下一步'
          this.nextShow = true
          this.nextIcon = 'md-checkmark'
        }
      }
    },

    next: function() {
      if (this.active == 0 &&
          this.oper == 'add') {
        this.$refs.addruleForm.validate(valid => {
          if (valid) {
            this.active++
          }
        })
      } else if (this.active == 0) {
        this.active++
      } else if (
        this.active == 1 &&
          this.oper == 'add'
      ) {
        console.log(this.tree)
        this.addNewRuleForm.logics = JSON.parse(JSON.stringify(this.tree))
        this.addNewRuleForm.output = JSON.parse(JSON.stringify(this.output))
        console.log(this.addNewRuleForm)
        addBigdataAssociationRules(this.addNewRuleForm).then(resp => {
          if (resp.data.returnCode == '0') {
            this.$message.success('新增规则节点成功')
            this.closeMe()
          } else {
            this.$message.error(resp.data.returnMsg)
          }
        })
          .catch(error => {
            if (error.response) {
              this.$message.error(error.response.data.detail)
            }
          })
      } else if (
        this.active == 1 &&
          this.oper == 'modify'
      ) {
        this.addNewRuleForm.logics = JSON.parse(JSON.stringify(this.tree))
        this.addNewRuleForm.output = JSON.parse(JSON.stringify(this.output))
        updateBigdataAssociationRules(this.addNewRuleForm)
          .then(resp => {
            if (resp.data.returnCode == '0') {
              this.$message.success('修改规则节点成功')
              this.closeMe()
            } else {
              this.$message.error(resp.data.returnMsg)
            }
          })
          .catch(error => {
            if (error.response) {
              this.$message.error(error.response.data.detail)
            }
          })
      } else {
        this.closeMe()
      }
    },

    backLast: function() {
      this.active = this.active - 1
    },
    back: function() {
      this.ruleVisible = false
    },
    closeMe() {
      this.$router.go(-1)
    },
    // 树形组织图-function
    labelClass(data) {
      return 'bg_node'
    },
    renderContent(h, data, pData) {
      const renderType = data.renderType// 增加类型，指定要创建的是什么
      const that = this
      if (renderType == 'Logic') {
        // let options = ;
        const peerRender = []
        if (data.peerNode) {
          // let options = ;
          const timeRender = h('el-form', {}, [
            h('el-form-item', {
              props: {
                label: '满足次数：',
                'label-width': '100px'
              }
            }, [h('el-input-number', {
              props: {
                value: data.time
              },
              on: {
                'change'(v) {
                  data.time = v
                }
              }
            })]),
            h('el-form-item', {
              props: {
                label: '超时时间：',
                'label-width': '100px'
              }
            }, [h('el-input-number', {
              props: {
                value: data.overtime
              },
              on: {
                'change'(v) {
                  data.overtime = v
                }
              }
            })]),
            h('el-form-item', {
              props: {
                label: '数据源类型：',
                'label-width': '100px'
              }
            }, [h('el-select', {
              props: {
                value: data.dataSource
                // labelInValue:true
              },
              on: {
                'change'(v) {
                  data.dataSource = v
                }
              }
            },
            this.datasourceType.map(item => {
              return h('el-option', {
                props: {
                  value: item.dataId,
                  label: item.dataName
                }
              })
            })
            )])
          ])
          peerRender.push(timeRender)
        }
        return h('div', [
          h('span', { style: { color: 'blue' }}, data.logicName),
          h('el-select',
            {
              props: {
                value: data.type
                // labelInValue:true
              },
              on: {
                'change'(v) {
                  data.type = v
                  // data.initValue = v;
                  const label = that.logicType.filter(item => {
                    return item.dataId == v
                  })[0].dataName
                  data.logicName = data.logicNameId + '-' + label
                  that.statics.logicNameList.forEach(item => {
                    if (item.dataId == data.logicNameId) {
                      item.dataName = data.logicName
                    }
                  })
                  if (data.logicName.indexOf('RULE') > -1) {
                    data.children = []
                    data.peerNode = true
                  } else {
                    if (data.children && data.children.length > 0 && data.children[0].renderType == 'Rule') {
                      data.children = []
                    }
                    data.peerNode = false
                  }
                }
              }
            },
            this.logicType.map(item => {
              return h('el-option', {
                props: {
                  value: item.dataId,
                  label: item.dataName
                }
              })
            })
          )
        ].concat(peerRender))
      }
      if (renderType == 'Rule') {
        const peerRender = []
        // key
        if (['1', '4', '5'].includes(data.matchType)) {
          let alarmList = []
          if (pData.dataSource == '9') {
            switch (data.field) {
              case '136': // 告警大类
                alarmList = this.bigdataAlarmTypeParent
                break;
              case '137': // 告警小类
                alarmList = this.bigdataAlarmTypeSub
                break;
            }
          }
          let select = h('el-select', 
            {
              class: {
                'alarm-rule-selectKey': true
              },
              props: {
                value: typeof data.key == 'string' && data.key != "" ? data.key.split(',') : data.handleKey || [],
                multiple: true,
                clearable: true
              },
              on: {
                'change'(v) {
                  data.key = v.join(',')
                  data.handleKey = v
                }
              }
            },
            alarmList.map(item => {
              return h('el-option', {
                props: {
                  value: item.dataId,
                  label: item.dataName
                }
              })
            })
          )
          let input = h('el-input',
            {
              props: {
                value: data.key
                // labelInValue:true
              },
              on: {
                'input'(v) {
                  data.key = v
                }
              }
            }
          )
          // key
          const keyRender = h('el-col', {
            props: {
              span: pData.dataSource == '9' && (data.field == '136' || data.field == '137') ? 6 : 4,
              className: 'alarm-rule-key'
            }
          }, [
            pData.dataSource == '9' && (data.field == '136' || data.field == '137') ? select : input
          ])
          peerRender.push(keyRender)
        } else {
          let staticsList = []
          switch (data.matchType) {
            case '2':
              staticsList = this.dataSet
              break
            case '3':
              staticsList = this.sourceAssociationWithRelated
              break
            default:
              break
          }
          if (data.matchType === '3') {
            const fieldRender = h('el-col', {
              props: {
                span: 4,
                className: 'alarm-rule-key'
              }
            }, [
              h('el-select',
                {
                  props: {
                    value: data.rlogicId
                    // labelInValue:true
                  },
                  on: {
                    'change'(v) {
                      data.rlogicId = v
                    }
                  }
                },
                this.statics.logicNameList.map(item => {
                  if (item.dataName.indexOf('RULE') != -1) {
                    return h('el-option', {
                      props: {
                        value: item.dataId,
                        label: item.dataName
                      }
                    })
                  }
                })
              )
            ])
            peerRender.push(fieldRender)
          }
          const keyRender = h('el-col', {
            props: {
              span: 4,
              className: 'alarm-rule-key'
            }
          }, [
            h('el-select',
              {
                props: {
                  value: data.key
                  // labelInValue:true
                },
                on: {
                  'change'(v) {
                    data.key = v
                  }
                }
              },
              staticsList.map(item => {
                return h('el-option', {
                  props: {
                    value: item.dataId,
                    label: item.dataName
                  }
                })
              })
            )
          ])
          peerRender.push(keyRender)
        }
        // rangekey
        if (data.operation == 12) {
          const rangeRender = h('el-col', {
            props: {
              span: 1,
              className: 'alarm-rule-arrow'
            }
          }, [
            h('span',
              {
                style: {
                  lineHeight: '30px'
                }
              },
              '至'
            )
          ])

          peerRender.push(rangeRender)

          // rangekey
          if (['1', '4', '5'].includes(data.matchType)) {
            const rangekey = h('el-col', {
              props: {
                span: 4,
                className: 'alarm-rule-rangekey'
              }
            }, [
              h('el-input',
                {
                  props: {
                    value: data.rangekey
                    // labelInValue:true
                  },
                  on: {
                    'input'(v) {
                      data.rangekey = v
                    }
                  }
                }
              )
            ])
            peerRender.push(rangekey)
          } else {
            let staticsList = []
            switch (data.matchType) {
              case '2':
                staticsList = this.dataSet
                break
              case '3':
                staticsList = this.sourceAssociation
                break
              default:
                break
            }
            const rangekey = h('el-col', {
              props: {
                span: 4,
                className: 'alarm-rule-key'
              }
            }, [
              h('el-select',
                {
                  props: {
                    value: data.rangekey
                    // labelInValue:true
                  },
                  on: {
                    'change'(v) {
                      data.key = v
                    }
                  }
                },
                staticsList.map(item => {
                  return h('el-option', {
                    props: {
                      value: item.dataId,
                      label: item.dataName
                    }
                  })
                })
              )
            ])
            peerRender.push(rangekey)
          }
        }

        // 根据父节点不同的数据源类型，切换不同字段选择器
        // 初始化
        let fileList = []
        switch (pData.dataSource) {
          case '2':
            fileList = this.multiSourceAssociationFlow
            break
          case '9':
            fileList = this.multiSourceAssociation
            break
          default:
            fileList = this.singleSourceAssociation
            break
        }
        // data.field =data.fieList[0].dataId
        // 返回，并生成节点
        return h('el-row', {
          props: {

          }
        }, [h('el-col', {
          props: {
            span: 5,
            className: 'alarm-rule-matchType'
          }
        }, [
          h('el-select',
            {
              props: {
                value: data.matchType
                // labelInValue:true
              },
              on: {
                'change'(v) {
                  data.matchType = v
                }
              }
            },
            this.matchType.map(item => {
              return h('el-option', {
                props: {
                  value: item.dataId,
                  label: item.dataName
                }
              })
            })
          )
        ]),
        // 选择 MULTI-SOURCE_ASSOCIATION_FLOW
        h('el-col', {
          props: {
            span: 5,
            className: 'alarm-rule-field'
          }
        }, [
          h('el-select',
            {
              props: {
                value: data.field
                // labelInValue:true
              },
              on: {
                'change'(v) {
                  data.field = v
                }
              }
            },
            // this.sourceAssociation.map(item => {
            //   return h('el-option', {
            //     props: {
            //       value: item.dataId,
            //       label: item.dataName
            //     }
            //   })
            // })
            fileList.map(item => {
              return h('el-option', {
                props: {
                  value: item.dataId,
                  label: item.dataName
                }
              })
            })
          )
        ]),

        h('el-col', {
          props: {
            span: 3,
            className: 'alarm-rule-operation'
          }
        }, [
          h('el-select',
            {
              props: {
                value: data.operation
                // labelInValue:true
              },
              on: {
                'change'(v) {
                  data.operation = v
                }
              }
            },
            this.operationType.map(item => {
              return h('el-option', {
                props: {
                  value: item.dataId,
                  label: item.dataName
                }
              })
            })
          )
        ])

        ].concat(peerRender))
      }
    },
    onAddChildren(e, data) {
      if (data.logicName.indexOf('RULE') > -1) {
        const nodeDefault = JSON.parse(JSON.stringify(this.ruleNodeDefault))
        nodeDefault.logicNameId = data.logicNameId
        // nodeDefault.field = this.sourceAssociation[0].dataId;
        nodeDefault.detailViewId = generateUUID()
        // nodeDefault.field =nodeDefault.fieList[0].dataId;
        data.children.push(nodeDefault)
      } else {
        const nodeDefault = JSON.parse(JSON.stringify(this.logicNodeDefault))
        nodeDefault.logicNameId = this.maxLogicNum + 1
        nodeDefault.logicName = nodeDefault.logicNameId + '-' + nodeDefault.logicName
        this.statics.logicNameList.push({
          dataName: nodeDefault.logicName,
          dataId: nodeDefault.logicNameId
        })
        data.children.push(nodeDefault)
        this.maxLogicNum++
      }
    },
    onDelete(e, data) {
      if (data.logicNameId === 1 && data.renderType == 'Logic') {
        this.$message.error('根节点不能删除!')
        return
      }
      this.$confirm('是否确认删除?', '提示', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning'
      }).then(() => {
        this.iterateTreeDeleteNode(this.tree.children, data)
      }).catch(() => {

      })
    },
    collapse(nodes) {
      nodes.forEach(node => {
        if (node.expand) {
          node.expand = false
        }

        node.children && this.collapse(node.children)
      })
    },
    onNodeClick(e, data) {
      //   console.log('CLICK', e);
    },
    onNodeMouseOver(e, data) {
      //   console.log('MOUSE OVER', e);
    },
    onNodeMouseOut(e, data) {
      //   console.log('MOUSE OUT', e);
    },
    iterateTreeDeleteNode(array, childNode) {
      let isFind = false
      array.forEach((item, index) => {
        if (childNode.detailViewId) {
          if (item.detailViewId == childNode.detailViewId) {
            isFind = true
          }
        } else {
          if (item.logicNameId == childNode.logicNameId) {
            isFind = true
          }
        }
        if (isFind) {
          array.splice(index, 1)
          isFind = false
          // 删除时，同步logicNameList
          // this.delLogicNameList([item]);
        } else {
          item.children && this.iterateTreeDeleteNode(item.children, childNode)
        }
      })
    },
    iterateTreeAddNode(array, contentType) {
      let isFind = false
      array.forEach(item => {
        if (item.logicNameId == this.selectedLoginId) {
          if (contentType == 'logics') {
            const nodeDefault = JSON.parse(JSON.stringify(this.logicNodeDefault))
            // let treeTmp = JSON.parse(JSON.stringify(this.tree))
            nodeDefault.logicNameId = this.maxLogicNum + 1
            nodeDefault.logicName = nodeDefault.logicNameId + '-' + nodeDefault.logicName
            item.children.push(nodeDefault)
            this.maxLogicNum++
            isFind = true
          }
          if (contentType == 'details') {

          }
          item.expand = true
        }
        if (isFind) {
          return
        } else {
          item.children && this.iterateTreeAddNode(item.children, contentType)
        }
      })
    },
    delLogicNameList(array) {
      array.forEach((item, index) => {
        if (item.renderType == 'Logic') {
          for (let i = 0; i < this.statics.logicNameList.length; i++) {
            if (this.statics.logicNameList[i].dataId == item.logicNameId) {
              this.statics.logicNameList.splice(i, 1)
              break
            }
          }
        }
        if (item.children && item.children.length > 0) {
          this.delLogicNameList(item.children)
        }
      })
    },
    // contentType内容类型 logics  details
    addnewNode: function(contentType) {
      this.$refs.addNewNodeRef.validate((valid) => {
        if (valid) {
          this.addnewLogicVisible = false
          this.iterateTreeAddNode([this.tree], contentType)
        }
      })
    },
    addOutput() {
      this.output.push({
        'logicNameId': null,
        'field': null,
        'alarmField': null,
        'logicName': null
      })
    },
    removeOutput(index) {
      if (this.output.length === 1) {
        this.output = [
          {
            'logicNameId': null,
            'field': null,
            'alarmField': null,
            'logicName': null
          }
        ]
        return
      }
      this.output.splice(index, 1)
    },
    backFill(id) {
      queryBigdataAssociationRules(id)
        .then(resp => {
          if (resp.data.returnCode == '0') {
            this.addNewRuleForm = resp.data.data
            this.addNewRuleForm.componentId = resp.data.data.componentId.split(',').map(Number)
            console.log(this.addNewRuleForm.componentId)
            this.maxLogicNum = resp.data.data.maxLogicNum
            this.statics.logicNameList = resp.data.data.logicNameList
            this.tree = resp.data.data.logics
            if (resp.data.data.output && resp.data.data.output.length > 0) {
              this.output = resp.data.data.output
            }
          } else {
            this.$message.error(resp.data.returnMsg)
          }
        })
        .catch(error => {
          if (error.response) {
            this.$message.error(error.response.data.detail)
          }
        })
    }
  }
}
</script>
<style>
  .org-tree-node .ivu-form-item{
    margin-top: 3px;
    margin-bottom: 2px;
  }
  .alarm-rule-matchType,
  .alarm-rule-operation,
  .alarm-rule-key,
  .alarm-rule-rangekey{
    width: 100px
  }
  .alarm-rule-field{
    width: 100px;
    margin-left: 10px;
  }
  .alarm-rule-arrow{
    width: 30px
  }
  .alarm-rule-selectKey .el-select__tags {
    flex-wrap: unset;
    overflow: auto;
  }
  .alarm-rule-selectKey .el-select__tags::-webkit-scrollbar {
    height: 5px;
  }
  .alarm-rule-selectKey .el-select__tags::-webkit-scrollbar-thumb {
    border-radius: 10px;
    background: rgba(0,0,0,0.2);
  }
</style>
<style scoped>
  /* @import url(../../css/layoutStyle.css); */

  .sub-title{
    height: 20px;
    line-height: 30px;
    padding-left: 10px;
    color: #000;
  }
  .rule-rename{
    height: 30px;
    text-align: center;
    line-height: 30px;
  }
  .rowBorder .colBorder {
    line-height: 50px;
    border: 1px solid #cbced4;
  }

  .margin-top-20 {
    margin-top: 20px;
  }

  .logicClass {
    padding-left: 50px;
    width: 100%;
    line-height: 50px;
  }
</style>
