<template>
  <el-row>
    <manager-dialog
      :visible.sync="assignVisible"
      width="500"
      title="任务指派"
      :destroy-on-close="true"
    >
      <el-row>
        <el-form
          ref="taskForm"
          :model="alarmTask"
          label-width="120px"
        >
          <el-row>
            <el-form-item
              label="任务标题:"
              :rules="[{ required: true, message: '任务标题不能为空', trigger: 'blur' }]"
              prop="taskTitle"
            >
              <el-input v-model="alarmTask.taskTitle" />
            </el-form-item>
            <el-form-item
              label="指派用户:"
              :rules="[{ required: true,type:'number', message: '指派用户不能为空', trigger: 'blur' }]"
              prop="assignUser"
            >
              <el-select
                v-model="alarmTask.assignUser"
                filterable
                placeholder="请输入用户名查找"
                style="width:100%"
              >
                <el-option
                  v-for="item in AllUser"
                  :key="item.dataId"
                  :label="item.dataName"
                  :value="item.dataId"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              label="抄送用户:"
              prop="notifyUser"
            >
              <el-select
                v-model="alarmTask.notifyUser"
                multiple
                filterable
                placeholder="请输入用户名查找"
                style="width:100%"
              >
                <el-option
                  v-for="item in AllUser"
                  :key="item.dataId"
                  :label="item.dataName"
                  :value="item.dataId"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              label="整改建议:"
              prop="rectification"
            >
              <el-input
                v-model="alarmTask.rectification"
                type="textarea"
                :autosize="{minRows: 1,maxRows: 5}"
                placeholder="如不填写则默认填充告警中的整改建议"
              />
            </el-form-item>
            <el-form-item
              label="备注:"
              prop="remark"
            >
              <el-input
                v-model="alarmTask.remark"
                type="textarea"
                :autosize="{minRows: 1,maxRows: 5}"
                placeholder="请输入..."
              />
            </el-form-item>
          </el-row>
        </el-form>
      </el-row>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="assignVisible=false">关闭</el-button>
        <el-button
          type="primary"
          @click="addTask"
        >确认</el-button>
      </span>
    </manager-dialog>
    <manager-dialog
      :visible.sync="addFilterFormVisible"
      title="误报"
      width="80%"
      :styles="{top: '20px'}"
    >
      <el-form
        ref="filterForm"
        :model="filterForm.correlationFilterRuleDTO"
        label-width="120px"
      >
        <el-row style="color:red;margin:10px 10px">注：地址支持格式:①单个ip②192.168.0.1-192.168.0.100③192.168.9.1/24多个IP用英文,分割④多个端口用英文,分割</el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item
              label="规则名称:"
              :rules="[{ required: true, message: '规则名称不能为空', trigger: 'blur' }]"
              prop="ruleName"
            >
              <el-input
                v-model="filterForm.correlationFilterRuleDTO.ruleName"
                placeholder="请输入..."
              />
            </el-form-item>
            <el-form-item
              label="告警等级:"
              :rules="[{ required: true,type:'number', message: '告警等级不能为空', trigger: 'blur' }]"
              prop="alertLevel"
            >
              <el-select
                v-model="filterForm.correlationFilterRuleDTO.alertLevel"
                @change="alertLevelChange"
              >
                <el-option
                  v-for="item in statics.alertLevel"
                  :key="item.value"
                  :value="item.value"
                >{{ item.label }}</el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              label="开始时间:"
              prop="startTime"
            >
              <el-date-picker
                v-model="filterForm.correlationFilterRuleDTO.startTime"
                type="datetime"
                placeholder="选择时间"
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item
              label="结束时间:"
              prop="endTime"
            >
              <el-date-picker
                v-model="filterForm.correlationFilterRuleDTO.endTime"
                type="datetime"
                placeholder="选择时间"
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item
              label="源端口:"
              prop="srcPort"
            >
              <el-input
                v-model="filterForm.correlationFilterRuleDTO.srcPort"
                placeholder="请输入..."
              />
            </el-form-item>
            <el-form-item
              label="源地址:"
              prop="srcIp"
            >
              <el-input
                v-model="filterForm.correlationFilterRuleDTO.srcIp"
                placeholder="请输入..."
              />
            </el-form-item>
            <el-form-item
              label="目的端口:"
              prop="destPort"
            >
              <el-input
                v-model="filterForm.correlationFilterRuleDTO.destPort"
                placeholder="请输入..."
              />
            </el-form-item>
            <el-form-item
              label="目的地址:"
              prop="dIp"
            >
              <el-input
                v-model="filterForm.correlationFilterRuleDTO.dIp"
                placeholder="请输入..."
              />
            </el-form-item>
          </el-col>
          <el-col
            :span="13"
            :offset="1"
          >
            <el-transfer
              v-model="filterForm.correlationFilterRuleDTO.ruleIds"
              :data="ruleDataList"
              :titles="['待选告警规则', '已选告警规则']"
              filterable
              @change="transferChange"
            />
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button @click="addFilterFormVisible=false">取消</el-button>
        <el-button
          type="primary"
          @click="addFilterRule"
        >确认</el-button>
      </div>
    </manager-dialog>
    <manager-dialog
      :visible.sync="dealAskVisible"
      title="处理告警"
    >
      <el-row>
        请选择告警处理方式：
        <el-row>
          <el-radio-group
            v-model="dealWay"
            vertical
          >
            <div>
              <el-radio label="ins">
                <el-tag>误报</el-tag><span style="color: #c6cccc;">&nbsp;确认告警为误报并可创建告警过滤规则</span>
              </el-radio>
            </div>
            <div>
              <el-radio label="del">
                <el-tag type="danger">清除</el-tag><span style="color: #c6cccc;">&nbsp;直接清除告警，仅针对本次告警生效</span>
              </el-radio>
            </div>
            <div>
              <el-radio label="deal">
                <el-tag type="success">处理</el-tag><span style="color: #c6cccc;">&nbsp;确认已处理告警</span>
              </el-radio>
            </div>
            <div>
              <el-radio
                v-if="statusTag==='1' || statusTag==='2' "
                label="back"
              >
                <el-tag type="warning">回退</el-tag><span style="color: #c6cccc;">&nbsp;将当前指派回退到上一级</span>
              </el-radio>
            </div>
          </el-radio-group>
        </el-row>
        <el-row>
          <span>备注</span>
          <el-input
            v-model="dealRemark"
            type="textarea"
            :autosize="{minRows: 2,maxRows: 5}"
            placeholder="请简略描述选择上述处理方式的原因或者处理过程"
          />
        </el-row>
      </el-row>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dealAskVisible=false">关闭</el-button>
        <el-button
          type="primary"
          @click="deal()"
        >处理</el-button>
      </span>
    </manager-dialog>
  </el-row>
</template>

<script>
import { addCorrelationFilterRule, alarmDeal, getAlarmResultInfo, addAlarmTask, queryAllBigdataAssociationRules } from '../api/alarm-result'

export default {
  name: 'AlarmResultsDeal',
  props: {
    type: {
      type: String,
      default: ''
    },
    value: {
      type: Object,
      default: function() {
        return {}
      }
    }
  },
  data() {
    return {
      assignVisible: false,
      dealAskVisible: false,
      addFilterFormVisible: false,
      AllUser: [],
      alarmTask: {
        alarmId: null,
        taskType: '1',
        taskStatus: '1',
        oldStatusTag: null,
        assignUser: null,
        taskTitle: null,
        rectification: null,
        remark: null,
        notifyUser: []
      },
      alertId: null,
      dealWay: 'deal',
      dealRemark: '',
      statusTag: '',
      ruleDataList: [],
      // 新增过滤form
      filterForm: {
        correlationFilterRuleDTO: {
          ruleName: '', // 规则名称
          alertLevel: null, // 告警等级
          startTime: null, // 开始时间
          endTime: null, // 结束时间
          dIp: null,
          srcIp: null,
          ruleIds: [],
          destPort: null,
          srcPort: null
        }
      },
      statics: {
        listStyle: {
          width: '200px',
          height: '455px'
        },
        alertLevel: [
          {
            value: 1,
            label: '轻微'
          },
          {
            value: 2,
            label: '低级'
          },
          {
            value: 3,
            label: '中级'
          },
          {
            value: 4,
            label: '高级'
          },
          {
            value: 5,
            label: '严重'
          }
        ]
      }
    }
  },
  watch: {
    assignVisible: function(newValue, oldValue) {
      if (newValue == false) {
        // 关闭窗口
        this.alarmTask = {
          alarmId: null,
          taskType: '1',
          taskStatus: '1',
          oldStatusTag: null,
          assignUser: null,
          taskTitle: null,
          rectification: null,
          remark: null,
          notifyUser: []
        }
        this.$emit('change', '')
      }
    },
    dealAskVisible: function(newValue, oldValue) {
      if (newValue == false) {
        this.$emit('change', '')
      }
    },
    value: function(newValue, oldValue) {
      if (newValue) {
        if (this.type === 'assign') {
          this.alarmTask.alarmId = newValue.alertId
          this.alarmTask.taskTitle =
            '请及时处理' +
            newValue.srcIp +
            '上的' +
            newValue.alertName +
            '告警'
          this.alarmTask.oldStatusTag = newValue.statusTag
          this.alarmTask.rectification = newValue.rectification
          if (this.AllUser.length == 0) {
          }
          this.assignVisible = true
        } else if (this.type === 'dealAsk') {
          this.alertId = newValue.alertId
          this.statusTag = newValue.statusTag
          this.dealRemark = ''
          this.dealAskVisible = true
        }
      }
    }
  },
  created() {
  },
  methods: {
    addTask() {
      const rMsg = '派单成功'

      this.$refs.taskForm.validate(valid => {
        if (valid) {
          const temp = JSON.parse(JSON.stringify(this.alarmTask))
          temp.notifyUsers = temp.notifyUser.join()
          addAlarmTask(temp)
            .then(resp => {
              if (resp.data.returnCode == '0') {
                this.assignVisible = false
                this.$emit('refresh', '')
                this.$message.success(rMsg)
              } else {
                this.$message.error(resp.data.returnMsg)
              }
            })
            .catch(error => {
              if (error.resp) {
                this.$message.error(error.resp.data.detail)
              }
            })
        } else {
          return false
        }
      })
    },
    alertLevelChange(value) {
      if (value) {
        this.getAllRules(value)
        this.filterForm.correlationFilterRuleDTO.ruleIds = []
      }
    },
    updateDealStatus(temp) {
      alarmDeal(temp)
        .then(resp => {
          console.info(resp.data.returnCode == '0')
          if (resp.data.returnCode == '0') {
            this.$message.success('处理成功')
            this.dealAskVisible = false
            this.$emit('refresh', '')
          } else {
            this.$message.error(resp.data.returnMsg)
          }
        })
        .catch(error => {
          if (error.response) {
            this.$message.error(error.response.data.detail)
          }
        })
    },
    deal(value) {
      if (!value) {
        value = this.dealWay
      }
      if (value == 'ins') {
        // 查询详细信息和威胁信息  忽略
        getAlarmResultInfo(this.alertId)
          .then(resp => {
            if (resp.data.returnCode == '0') {
              const temp = resp.data.data
              this.filterForm.correlationFilterRuleDTO.ruleName = '忽略' + temp.srcIp + '的' +
                temp.alertName
              this.filterForm.correlationFilterRuleDTO.dIp = temp.dstIp
              this.filterForm.correlationFilterRuleDTO.destPort =
                temp.dstPort
              this.filterForm.correlationFilterRuleDTO.alertLevel =
                temp.alertLevel
              this.filterForm.correlationFilterRuleDTO.srcIp = temp.srcIp
              this.filterForm.correlationFilterRuleDTO.srcPort = temp.srcPort
              this.filterForm.correlationFilterRuleDTO.ruleIds = [temp.ruleId]
              this.getAllRules(0)
            } else {
              this.$message.error(resp.data.returnMsg)
            }
          })
          .catch(error => {
            if (error.response) {
              this.$message.error(error.response.data.detail)
            }
          })
        this.addFilterFormVisible = true
      } else {
        const temp = { ids: [], info: {}}
        temp.ids.push(this.alertId)
        temp.info.status = value
        if (this.dealRemark) {
          temp.info.remark = this.dealRemark
        }
        this.updateDealStatus(temp)
      }
    },
    getAllRules: function(alertLevel) {
      // this.ruleForm.alarmRuleCorrelationMap.filterId = null;
      queryAllBigdataAssociationRules(alertLevel)
        .then(resp => {
          // console.log(resp)
          if (resp.data.returnCode == '0') {
            this.ruleDataList = resp.data.data
          } else {
            this.$message.error(resp.data.returnMsg)
          }
        })
        .catch(error => {
          if (error.response) {
            this.$message.error(error.response.data.detail)
          }
        })
    },
    transferChange(newTargetKeys) {
      this.filterForm.correlationFilterRuleDTO.ruleIds = newTargetKeys
    },
    addFilterRule() {
      const rMsg = '新增成功'

      this.$refs.filterForm.validate(valid => {
        if (valid) {
          if (this.validateC(this.filterForm)) {
            if (this.openMode == 'add') {
              this.filterForm.correlationFilterRuleDTO.filterId = null
            }
            addCorrelationFilterRule(this.filterForm)
              .then(resp => {
                if (resp.data.returnCode == '0') {
                  this.addFilterFormVisible = false
                  this.dealAskVisible = false
                  this.$message.success(rMsg)
                  this.$emit('refresh', '')
                  this.deal('insIgnore')
                } else {
                  this.$message.error(resp.data.returnMsg)
                }
              })
              .catch(error => {
                if (error.resp) {
                  this.$message.error(error.resp.data.detail)
                }
              })
          } else {
            return false
          }
        } else {
          return false
        }
      })
    },
    validateC(val) {
      if (val.correlationFilterRuleDTO.dIp) {
        const temp = val.correlationFilterRuleDTO.dIp.split(',')
        for (const i in temp) {
          if (!this.isIPAddress(temp[i])) {
            this.$message.error('目的地址填写不正确')
            return false
          }
        }
      }
      if (val.correlationFilterRuleDTO.srcIp) {
        const temp = val.correlationFilterRuleDTO.srcIp.split(',')
        for (const i in temp) {
          if (!this.isIPAddress(temp[i])) {
            this.$message.error('源地址填写不正确')
            return false
          }
        }
      }
      return true
    },
    isIPAddress: function(obj) {
      var regex = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/
      var matches = regex.exec(obj)
      if (matches == null) {
        return false
      }
      for (var i = 1; i < matches.length; i++) {
        if (matches[i] > 255 || matches[i] < 0) {
          return false
        }
      }
      return true
    }
  }
}
</script>
