<template>
  <div v-loading="loading" class="layout alarm">
    <el-row v-if="!isFlowAlarm" style="padding: 12px 0; background-color: #e6e9f0">
      <el-col :span="3">
        <el-row class="headCardBegin headCard">
          <el-col>
            <img class="cardIcon today" src="./imgs/alarm/newToday.png" />
            <el-row type="flex" class="cardMain">
              <span @click="searchTodayTags">
                {{ countInfo.todayNewNum > 99999 ? '99999+' : countInfo.todayNewNum }}
              </span>
              <span>今日新增</span>
            </el-row>
          </el-col>
        </el-row>
      </el-col>
      <el-col :span="6">
        <el-row class="headCard">
          <el-col>
            <img class="cardIcon success" src="./imgs/alarm/attackSuccess.png" />
            <el-row type="flex" class="cardMain">
              <span @click="searchSuccessTags('1')">
                {{ countInfo.successNum > 99999 ? '99999+' : countInfo.successNum }}
              </span>
              <span>攻击成功</span>
            </el-row>
          </el-col>
          <el-col>
            <img class="cardIcon success" src="./imgs/alarm/suspectedSuccess.png" />
            <el-row type="flex" class="cardMain">
              <span @click="searchSuccessTags('2')">
                {{ countInfo.suspectedNum > 99999 ? '99999+' : countInfo.suspectedNum }}
              </span>
              <span>疑似成功</span>
            </el-row>
          </el-col>
          <el-col>
            <img class="cardIcon success" src="./imgs/alarm/unsuccess.png" />
            <el-row type="flex" class="cardMain">
              <span @click="searchSuccessTags('0')">
                {{ countInfo.unSuccessNum > 99999 ? '99999+' : countInfo.unSuccessNum }}
              </span>
              <span>未成功</span>
            </el-row>
          </el-col>
        </el-row>
      </el-col>

      <el-col :span="9">
        <el-row class="headCard">
          <el-col>
            <img class="cardIcon level" src="./imgs/alarm/danager.png" />
            <el-row type="flex" class="cardMain">
              <span @click="searchAlertLevel('5')">
                {{ countInfo.severeNum > 99999 ? '99999+' : countInfo.severeNum }}
              </span>
              <span>严重</span>
            </el-row>
          </el-col>
          <el-col>
            <img class="cardIcon level" src="./imgs/alarm/high.png" />
            <el-row type="flex" class="cardMain">
              <span @click="searchAlertLevel('4')">
                {{ countInfo.highNum > 99999 ? '99999+' : countInfo.highNum }}
              </span>
              <span>高级</span>
            </el-row>
          </el-col>
          <el-col>
            <img class="cardIcon level" src="./imgs/alarm/middle.png" />
            <el-row type="flex" class="cardMain">
              <span @click="searchAlertLevel('3')">
                {{ countInfo.intermediateNum > 99999 ? '99999+' : countInfo.intermediateNum }}
              </span>
              <span>中级</span>
            </el-row>
          </el-col>
          <el-col>
            <img class="cardIcon level" src="./imgs/alarm/low.png" />
            <el-row type="flex" class="cardMain">
              <span @click="searchAlertLevel('2')">
                {{ countInfo.lowNum > 99999 ? '99999+' : countInfo.lowNum }}
              </span>
              <span>低级</span>
            </el-row>
          </el-col>
          <el-col>
            <img class="cardIcon level" src="./imgs/alarm/slight.png" />
            <el-row type="flex" class="cardMain">
              <span @click="searchAlertLevel('1')">
                {{ countInfo.mildNum > 99999 ? '99999+' : countInfo.mildNum }}
              </span>
              <span>轻微</span>
            </el-row>
          </el-col>
        </el-row>
      </el-col>
      <el-col :span="6">
        <el-row class="headCard headCardEnd">
          <el-col>
            <img stlye="width: 27px; height: 33px;" class="cardIcon" src="./imgs/alarm/pending.png" />
            <el-row type="flex" class="cardMain">
              <span @click="searchAlertStatus(isRealTime ? '0' : '5')">
                {{ countInfo[isRealTime ? 'pendingNum' : 'ignoredNum'] > 99999 ? '99999+' : countInfo[isRealTime ? 'pendingNum' : 'ignoredNum'] }}
              </span>
              <el-tooltip placement="bottom">
                <span>{{ isRealTime ? '待处理' : '误报' }}</span>
                <div slot="content">
                  <p>{{ isRealTime ? '新发现的告警需要处理' : '已确认告警为误报并可创建告警过滤规则' }}</p>
                </div>
                </el-tooltip>
            </el-row>
          </el-col>
          <el-col>
            <img stlye="width: 26px; height: 29px;" class="cardIcon" src="./imgs/alarm/audit.png" />
            <el-row type="flex" class="cardMain">
              <span @click="searchAlertStatus(isRealTime ? '6' : '4')">
                {{ countInfo[isRealTime ? 'checkNum' : 'clearedNum'] > 99999 ? '99999+' : countInfo[isRealTime ? 'checkNum' : 'clearedNum'] }}
              </span>
              <el-tooltip placement="bottom">
                <span>{{ isRealTime ? '待审核' : '已清除' }}</span>
                <div slot="content">
                  <p>{{ isRealTime ? '等待管理员审核告警是否处理' : '已清除告警' }}</p>
                </div>
              </el-tooltip>
            </el-row>
          </el-col>
          <el-col>
            <img stlye="width: 27px; height: 30px;" class="cardIcon" src="./imgs/alarm/confirmed.png" />
            <el-row type="flex" class="cardMain">
              <span @click="searchAlertStatus(isRealTime ? '2' : '3')">
                {{ countInfo[isRealTime ? 'confirmedNum' : 'processedNum'] > 99999 ? '99999+' : countInfo[isRealTime ? 'confirmedNum' : 'processedNum'] }}
              </span>
              <el-tooltip placement="bottom">
                <span>{{ isRealTime ? '已确认' : '已处理' }}</span>
                <div slot="content">
                  <p>{{ isRealTime ? '被指派人已查看该告警' : '已处理告警' }}</p>
                </div>
              </el-tooltip>
            </el-row>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
    <manager-ui
      v-if="this.tabLabel == '实时告警'"
      :query-model="form.alarmResultMap"
      :query-items="queryItemsReal"
      :static-data="statics"
      :column-items="columnItems"
      :table-data="tableData"
      :pagination="page"
      :spread-threshold="1"
      :show-add-btn="false"
      show-table-tools
      @searchClick="searchClick"
      @allDownload="exportClick()"
      @selection-change="mainTableChoose"
      @search="search"
      @resetForm="resetForm('real')"
    >
      <template #dstIp="{scope}">
        <assetAssociate :asset-ip="scope.row.dstIp" :business-id="String(scope.row.businessId)"/>
      </template>

      <template #alertSource="{scope}">
        {{ scope.row.alertSource| toCase(
          statics.datasourceType,
          "dataId",
          "dataName"
        ) }}
      </template>
      <template #deviceName="{scope}">
        <deviceAssociate :asset-id="scope.row.collectDevAssetId+''" :device-name="scope.row.deviceName" />
      </template>
      <template #alertType="{scope}">
        {{ scope.row.alertType | toCase(

          statics.bigdataAlarmType,
          "dataId",
          "dataName"
        ) }}
      </template>
      <template #alertTypeSub="{scope}">
        {{ scope.row.alertTypeSub | toCase(

          statics.bigdataAlarmType,
          "dataId",
          "dataName"
        ) }}
      </template>
      <template #alertLevel="{scope}">
        {{ scope.row.alertLevel | toCase(

          statics.alertLevel,
          "dataId",
          "dataName"
        ) }}
      </template>
      <template #statusTag="{scope}">
        {{ scope.row.statusTag | toCase(

          statics.realTimeStatusTag,
          "dataId",
          "dataName"
        ) }}
      </template>
      <template #operate="{scope}">
        <el-context-menu :menus="realMenus" :scope="scope" :default="3" @oper="clickRow" />
      </template>
      <template slot="tableTools">
        <el-button type="text">
          <span @click="exportClick">
            <i class="el-icon-download" />导出
          </span>
        </el-button>
      </template>
    </manager-ui>
    <manager-ui
      v-if="this.tabLabel == '历史告警'"
      :query-model="form.alarmResultMap"
      :query-items="queryItemsHis"
      :static-data="statics"
      :column-items="columnItems"
      :table-data="tableData"
      :pagination="page"
      :spread-threshold="1"
      :show-add-btn="false"
      show-table-tools
      @searchClick="searchClick"
      @allDownload="exportClick()"
      @selection-change="mainTableChoose"
      @search="search"
      @resetForm="resetForm('his')"
    >
      <template #dstIp="{scope}">
        <assetAssociate :asset-ip="scope.row.dstIp"  :business-id="String(scope.row.businessId)"/>
      </template>

      <template #alertSource="{scope}">
        {{ scope.row.alertSource| toCase(
          statics.datasourceType,
          "dataId",
          "dataName"
        ) }}
      </template>
      <template #deviceName="{scope}">
        <deviceAssociate :asset-id="scope.row.collectDevAssetId+''" :device-name="scope.row.deviceName" />
      </template>
      <template #alertType="{scope}">
        {{ scope.row.alertType | toCase(

          statics.bigdataAlarmType,
          "dataId",
          "dataName"
        ) }}
      </template>
      <template #alertTypeSub="{scope}">
        {{ scope.row.alertTypeSub | toCase(

        statics.bigdataAlarmType,
        "dataId",
        "dataName"
        ) }}
      </template>
      <template #alertLevel="{scope}">
        {{ scope.row.alertLevel | toCase(

          statics.alertLevel,
          "dataId",
          "dataName"
        ) }}
      </template>
      <template #statusTag="{scope}">
        {{ scope.row.statusTag | toCase(

          statics.hisStatusTag,
          "dataId",
          "dataName"
        ) }}
      </template>
      <template #operate="{scope}">
        <el-context-menu :menus="historyMenus" :scope="scope" :default="3" @oper="clickRow" />
      </template>
      <template slot="tableTools">
        <el-button type="text">
          <span @click="exportClick">
            <i class="el-icon-download" />导出
          </span>
        </el-button>
      </template>
    </manager-ui>

    <alarmResultDeal
      :type="dealType"
      :value="dealValue"
      @change="handleDealType"
      @refresh="handleDealRefresh"
    />
    <manager-dialog :visible.sync="reportVisible" title="告警分析报告下载" @close="closeExportReportDialog()">
      <el-form ref="reportParams" label-width="110px" :model="reportParams.analysisReportMap">
        <el-form-item label="报表名称：" prop="reportName" :rules="[{required: true, message: '请输入报表名称', trigger: 'blur'}]">
          <el-input v-model.trim="reportParams.analysisReportMap.reportName" placeholder="请输入报表名称" />
        </el-form-item>
        <el-form-item label="统计时间：" prop="reportTime" :rules="[{required: true, message: '请选择统计时间', trigger: 'blur'}]">
          <ak-date-picker
            v-model="reportParams.analysisReportMap.reportTime"
            :picker-options="pickerOptions0"
            size="small"
            :clearable="false"
            type="datetimerange"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm:ss"
            @change="reportTimeChangeHandle"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeExportReportDialog()">关闭</el-button>
        <b v-loading="reportLoading" class="importLoading">
          <el-button type="primary" @click="submitReport">提交</el-button>
        </b>
      </span>
    </manager-dialog>
    <router-view />
  </div>
</template>

<script>
import alarmResultDeal from './alarmResultDeal'
import assetAssociate from './assetAssociate'
import deviceAssociate from './deviceAssociate'
import { getAlarmResultList, exportAlarmResultList, countAlarmResult, analysisReport } from './api/alarm-result'

export default {
  name: 'AlarmResults',
  components: {
    // "el-button": ctsiButton
    alarmResultDeal: alarmResultDeal,
    assetAssociate: assetAssociate,
    deviceAssociate: deviceAssociate
  },
  props: ['_ids'],
  data() {
    return {
      /* 操作菜单 */
      defaultV: 3, // 按钮数量
      // 实时告警
      realMenus: [
        {
          text: '查看',
          visible: true,
          command: 'detail',
          icon: 'el-icon-s-order'
        },
        // {
        //   text: '指派',
        //   visible: true,
        //   command: 'assign',
        //   //ruleCode: 'safetyAssessmentReport_check'
        // },
        {
          text: '处理',
          visible: true,
          command: 'handle',
          icon: 'el-icon-edit'
          // ruleCode: 'alarmManagement_deal'
        }
      ],
      // 历史告警
      historyMenus: [
        {
          text: '查看',
          visible: true,
          command: 'detail',
          icon: 'el-icon-s-order'
        }
      ],
      /* 业务选择树*/
      filterText: '',
      filterTextHis: '',
      selectBusinessList: [],
      selectBusinessListHis: [],

      filterTag: false,
      businessLs: [], // 业务系统列表
      orCollapseHis: false,
      orCollapseReal: false,
      pageParTag: false,
      dealType: '',
      dealValue: {},
      tabLabel: '实时告警',
      // 自动刷新相关
      refreshTag: false,
      refreshVisible: false,
      refreshTime: 1,
      refreshInterval: null,
      soundTag: false,
      countInfo: {
        assignedNum: 0,
        checkNum: 0,
        clearedNum: 0,
        confirmedNum: 0,
        highNum: 0,
        ignoredNum: 0,
        intermediateNum: 0,
        lowNum: 0,
        mildNum: 0,
        pendingNum: 0,
        processedNum: 0,
        severeNum: 0,
        successNum: 0,
        suspectedNum: 0,
        todayNewNum: 0,
        unSuccessNum: 0
      },
      dataTotal: 0, // page组件：总数
      currentPageIndex: 1, // page组件：当前页
      pageSize: 10, // page组件：页面大小

      statics: {
        attackType: [],
        datasourceType: [],
        bigdataAlarmType: [],
        bigdataAlarmTypeParent: [],
        bigdataAlarmTypeSub: [],
        bigdataAlarmTypeTree: [],
        alertSource: [],
        sourceTag: [
          {
            dataId: '0',
            dataName: '外部告警'
          },
          {
            dataId: '1',
            dataName: '内部告警'
          }
        ],
        alertLevel: [],
        realTimeStatusTag: [
          {
            dataId: '0',
            dataName: '待处理'
          },
          // {
          //   dataId: "1",
          //   dataName: "已指派"
          // },
          {
            dataId: '2',
            dataName: '已确认'
          },
          {
            dataId: '6',
            dataName: '待审核'
          }
        ],
        hisStatusTag: [
          {
            dataId: '3',
            dataName: '已处理'
          },
          {
            dataId: '4',
            dataName: '已清除'
          },
          {
            dataId: '5',
            dataName: '误报'
          }
        ],
        statusTag: [],
        successTagList: [
          {
            dataId: '0',
            dataName: '失败'
          },
          {
            dataId: '1',
            dataName: '成功'
          },
          {
            dataId: '2',
            dataName: '未知'
          }
        ]
      },
      exportForm: {
        templateFileTag: ''
      },
      alarmCorrelationResult: {
        alertId: null,
        alertName: null,
        alertSource: null,
        sourceTag: null,
        assetName: null,
        srcIp: null,
        businessName: null,
        occurTime: null,
        alarmLevel: null,
        statusTag: null,
        opUser: null,
        opTime: null,
        description: null
      },
      riskAssetThreatResult: {
        threatName: null,
        reliabilityTag: null,
        availabilityChange: null,
        confidentialChange: null,
        integrityChange: null,
        startTime: null,
        endTime: null,
        descriptionInfo: null
      },
      eventTableData: [],
      mergerTableData: [],
      mergereventTableData: [],
      eventCommonLatest: {},
      form: {
        alarmResultMap: {
          alertName: null,
          alertLevels: [],
          alertSources: [],
          alertTypes: [],
          alertTypeSubs: [],
          alertTypeList: [],
          attackStages: [],
          successTags: [],
          srcIp: null,
          srcPort: null,
          dstIp: null,
          dstPort: null,
          statusTags: [],
          reliability: null,
          successTag: null,
          probeNos: [],
          alarmResultMap: [],
          applyTime: [],
          businessIds: [],
          deviceName: null
        },
        page: {
          current: 1,
          size: 10
        }
      },
      page: {
        current: 1,
        size: 10,
        total: 0
      },
      importModal: false,
      loading: false,
      exportModal: false,
      tableData: [],
      // 查询条件
      queryItemsReal: [
        {
          type: 'treeSelect',
          span: 12,
          key: 'alertTypeSubs',
          placeholder: '请选择告警类型',
          label: '告警类型',
          dataTree: 'bigdataAlarmTypeTree'
        },
        {
          type: 'input',
          span: 12,
          key: 'alertName',
          label: '告警名称'
        },
        {
          type: 'select',
          span: 12,
          key: 'alertSources',
          placeholder: '请选择告警来源',
          label: '告警来源',
          multiple: true,
          option: 'datasourceType',
          optionLabel: 'dataName',
          optionValue: 'dataId'
        },
        {
          type: 'select',
          span: 12,
          key: 'statusTags',
          placeholder: '请选择状态',
          label: '状态',
          multiple: true,
          option: 'realTimeStatusTag',
          optionLabel: 'dataName',
          optionValue: 'dataId'
        },
        {
          type: 'treeSelect',
          span: 12,
          key: 'businessIds',
          placeholder: '请选择归属业务系统',
          label: '归属业务系统',
          dataTree: 'businessTree'
        },
        {
          type: 'select',
          span: 12,
          key: 'attackStages',
          placeholder: '请选择攻击阶段',
          label: '攻击阶段',
          multiple: true,
          option: 'attackType',
          optionLabel: 'dataName',
          optionValue: 'dataId'
        },
        {
          type: 'select',
          span: 12,
          key: 'alertLevels',
          placeholder: '请选择级别',
          label: '级别',
          multiple: true,
          option: 'alertLevel',
          optionLabel: 'dataName',
          optionValue: 'dataId'
        }, {
          type: 'input',
          span: 12,
          key: 'reliability',
          label: '可信度'
        }, {
          type: 'input',
          span: 12,
          key: 'srcIp',
          label: '源IP'
        }, {
          type: 'input',
          span: 12,
          key: 'srcPort',
          label: '源端口'
        }, {
          type: 'input',
          span: 12,
          key: 'dstIp',
          label: '目的IP'
        }, {
          type: 'input',
          span: 12,
          key: 'dstPort',
          label: '目的端口'
        },
        {
          type: 'select',
          span: 12,
          key: 'successTags',
          placeholder: '请选择攻击结果',
          label: '攻击结果',
          multiple: true,
          option: 'successTagList',
          optionLabel: 'dataName',
          optionValue: 'dataId'
        },
        {
          dataType: 'datetimerange',
          type: 'datetime',
          key: 'applyTime',
          span: 12,
          label: '时间范围',
          change: 'timeDeal',
          format: 'yyyy-MM-dd HH:mm:ss',
          valueFormat: 'yyyy-MM-dd HH:mm:ss'
        }
      ],
      queryItemsHis: [
        {
          type: 'treeSelect',
          span: 12,
          key: 'alertTypeSubs',
          placeholder: '请选择告警类型',
          label: '告警类型',
          dataTree: 'bigdataAlarmTypeTree'
        },
        {
          type: 'input',
          span: 12,
          key: 'alertName',
          label: '告警名称'
        },
        {
          type: 'select',
          span: 12,
          key: 'alertSources',
          placeholder: '请选择告警来源',
          label: '告警来源',
          multiple: true,
          option: 'datasourceType',
          optionLabel: 'dataName',
          optionValue: 'dataId'
        },
        {
          type: 'select',
          span: 12,
          key: 'statusTags',
          placeholder: '请选择状态',
          label: '状态',
          multiple: true,
          option: 'hisStatusTag',
          optionLabel: 'dataName',
          optionValue: 'dataId'
        },
        // {
        //   type: 'treeSelect',
        //   span: 12,
        //   key: 'businessIds',
        //   placeholder: '请选择归属业务系统',
        //   label: '归属业务系统',
        //   dataTree: 'businessTree'
        // },
        {
          type: 'select',
          span: 12,
          key: 'attackStages',
          placeholder: '请选择攻击阶段',
          label: '攻击阶段',
          multiple: true,
          option: 'attackType',
          optionLabel: 'dataName',
          optionValue: 'dataId'
        },
        {
          type: 'select',
          span: 12,
          key: 'alertLevels',
          placeholder: '请选择级别',
          label: '级别',
          multiple: true,
          option: 'alertLevel',
          optionLabel: 'dataName',
          optionValue: 'dataId'
        }, {
          type: 'input',
          span: 12,
          key: 'reliability',
          label: '可信度'
        }, {
          type: 'input',
          span: 12,
          key: 'srcIp',
          label: '源IP'
        }, {
          type: 'input',
          span: 12,
          key: 'srcPort',
          label: '源端口'
        }, {
          type: 'input',
          span: 12,
          key: 'dstIp',
          label: '目的IP'
        }, {
          type: 'input',
          span: 12,
          key: 'dstPort',
          label: '目的端口'
        },
        {
          type: 'select',
          span: 12,
          key: 'successTags',
          placeholder: '请选择攻击结果',
          label: '攻击结果',
          multiple: true,
          option: 'successTagList',
          optionLabel: 'dataName',
          optionValue: 'dataId'
        },
        {
          dataType: 'datetimerange',
          type: 'datetime',
          key: 'applyTime',
          span: 12,
          label: '时间范围',
          change: 'timeDeal',
          format: 'yyyy-MM-dd HH:mm:ss',
          valueFormat: 'yyyy-MM-dd HH:mm:ss'
        }
      ],
      columnItems: [
        {
          type: 'selection',
          width: 50
        },
        {
          _key: 'alertName',
          prop: 'alertName',
          label: '告警名称',
          width: 140,
          showOverflowTooltip: true
        },
        {
          _key: 'businessName',
          prop: 'businessName',
          label: '业务系统',
          showOverflowTooltip: true
        },
        {
          _key: 'dstIp',
          prop: 'dstIp',
          label: '目的IP',
          render: true,
          width: 120,
          showOverflowTooltip: true
        },
        {
          _key: 'dstPort',
          prop: 'dstPort',
          label: '目的端口',
          width: 80,
          showOverflowTooltip: true
        },
        {
          _key: 'alertSource',
          prop: 'alertSource',
          label: '告警来源',
          render: true,
          width: 100,
          showOverflowTooltip: true
        },
        {
          _key: 'deviceName',
          prop: 'deviceName',
          label: '来源设备',
          render: true,
          showOverflowTooltip: true
        },
        {
          _key: 'alertType',
          prop: 'alertType',
          label: '告警大类',
          width: 150,
          render: true,
          showOverflowTooltip: true
        },
        {
          _key: 'alertTypeSub',
          prop: 'alertTypeSub',
          label: '告警小类',
          width: 150,
          render: true,
          showOverflowTooltip: true
        },
        {
          _key: 'alertLevel',
          prop: 'alertLevel',
          label: '级别',
          width: 60,
          render: true,
          showOverflowTooltip: true
        },
        {
          _key: 'description',
          prop: 'description',
          label: '描述',
          showOverflowTooltip: true
        },
        {
          _key: 'updateTime',
          prop: 'updateTime',
          label: '最近发生时间',
          width: 150,
          showOverflowTooltip: true
        },
        {
          _key: 'alertCount',
          prop: 'alertCount',
          label: '告警次数',
          width: 80,
          showOverflowTooltip: true
        },
        {
          _key: 'statusTag',
          prop: 'statusTag',
          label: '状态',
          width: 90,
          render: true,
          showOverflowTooltip: true
        },
        {
          _key: 'operate',
          prop: 'operate',
          label: '操作',
          fixed: 'right',
          render: true,
          width: 70
        }
      ],
      queryEventForm: {
        type: '',
        id: null,
        page: {
          current: 1,
          size: 10
        }
      },
      multipleSelection: [],
      reportVisible: false,
      reportLoading: false,
      reportParams: {
        analysisReportMap: {
          reportName: null,
          reportTime: '',
          startTime: null,
          endTime: null
        }
      },
      pickerOptions0: {
        disabledDate(time) {
          return time.getTime() > Date.now() - 8.64e6
        }

      }
    }
  },
  computed: {
    isRealTime() {
      return this.$route.name == 'alarmResults'
    },
    businessTree: function() {
      return this.$store.getters.businessTree
    },
    // 判断是否是流量监测中心下路由
    isFlowAlarm: function() {
      // console.log(this.$route.name);
      if (this.$route.name == 'flowAlarmResults') {
        return true
      } else {
        return false
      }
    },
    refreshClass: function() {
      if (this.refreshTag) {
        return 'actived'
      } else {
        return ''
      }
    },
    soundClass: function() {
      if (this.soundTag) {
        return 'actived'
      } else {
        return ''
      }
    },
    attackType() {
      return this.$store.state.alarm.attackType
    },
    bigdataAlarmType() {
      return this.$store.state.alarm.newAlarmType
    },
    bigdataAlarmTypeParent() {
      return this.$store.state.alarm.newAlarmTypeParent
    },
    bigdataAlarmTypeSub() {
      return this.$store.state.alarm.newAlarmTypeSub
    },
    bigdataAlarmTypeTree() {
      return this.$store.state.alarm.newAlarmTypeTree
    },
    datasourceType() {
      return this.$store.state.alarm.datasourceType
    },
    ruleLevel() {
      return this.$store.state.alarm.ruleLevel
    },
    probeNoList() {
      return this.$store.state.alarm.probeNos
    },
    hebeiTag() {
      return this.$store.getters.hebeiTag
    }
  },
  watch: {
    bigdataAlarmType(val) {
      this.statics.bigdataAlarmType = val
    },
    bigdataAlarmTypeTree(val) {
      this.statics.bigdataAlarmTypeTree = val
    },
    attackType(val) {
      this.statics.attackType = val
    },
    ruleLevel(val) {
      this.statics.alertLevel = val
    },
    datasourceType(val) {
      this.statics.datasourceType = val
    },
    filterText(val) {
      this.$refs.businessTree.filter(val)
    },
    filterTextHis(val) {
      this.$refs.businessTreeHis.filter(val)
    },
    refreshTag: function(value, oldvalue) {
      if (value) {
        window.clearInterval(this.refreshInterval)
        var that = this
        this.refreshInterval = window.setInterval(function() {
          that.search()
          that.$message.info('自动刷新成功')
        }, that.refreshTime * 1000 * 60)
      } else {
        window.clearInterval(this.refreshInterval)
      }
    },
    isFlowAlarm: function(value, oldvalue) {
      this.resetForm('real')
      this.getCount()
      this.search()
    }
  },
  created: function() {    
    this.tabLabel = this.$route.name == 'alarmResults' ? '实时告警' : '历史告警'
    this.$store.dispatch('alarm/getAllAlarmStaticList')
    this.getNewAlarmType()
    this.getSourceType()
    // this.toYpWebsite()
  },
  mounted() {
    // this.form = JSON.parse(sessionStorage.getItem("alarmResultsQueryParam"));
    // let bnList = this.form.alarmResultMap.businessIds || [];
    // this.tabLabel = sessionStorage.getItem("alarmResultsTabLabel");
    // if(this.tabLabel=='实时告警'){
    //   this.$refs.businessTree.setCheckedKeys(bnList);
    // }else {
    //   this.$refs.businessTreeHis.setCheckedKeys(bnList);
    // }

    var agentid = []
    agentid = this.$route.params.agentid
    this.form.alarmResultMap.probeNos = agentid
    if (this.$route.params.srcIp) {
      this.form.alarmResultMap.srcIp = this.$route.params.srcIp
      this.filterTag = true
    }
    if (this.$route.params.dstIp) {
      this.form.alarmResultMap.dstIp = this.$route.params.dstIp
      this.filterTag = true
    }
    if (this.$route.params.alertLevels) {
      switch (this.$route.params.alertLevels) {
        case '轻微':
          this.form.alarmResultMap.alertLevels = [1]
          break
        case '低级':
          this.form.alarmResultMap.alertLevels = [2]
          break
        case '中级':
          this.form.alarmResultMap.alertLevels = [3]
          break
        case '高级':
          this.form.alarmResultMap.alertLevels = [4]
          break
        default:
          this.form.alarmResultMap.alertLevels = [5]
      }

      this.filterTag = true
    }

    if (this.$route.params.alertSources && this.$route.params.alertName) {
      this.form.alarmResultMap.alertSources = [this.$route.params.alertSources]
      this.form.alarmResultMap.alertName = this.$route.params.alertName
      this.filterTag = true
    } else if (this.$route.params.alertName) {
      this.form.alarmResultMap.alertName = this.$route.params.alertName
      this.filterTag = true
    }
    if (this.$route.params.businessId) {
      this.form.alarmResultMap.businessIds = [this.$route.params.businessId]
      this.filterTag = true
    }
    if (this.$route.params.beginTime && this.$route.params.endTime) {
      this.filterTag = true
      this.form.alarmResultMap.beginTime = this.$route.params.beginTime
      this.form.alarmResultMap.endTime = this.$route.params.endTime
      this.form.alarmResultMap.applyTime = [this.form.alarmResultMap.beginTime, this.form.alarmResultMap.endTime]
    }
    if (this.$route.params.alertTypes) {
      this.filterTag = true
      this.form.alarmResultMap.alertTypes = [this.$route.params.alertTypes]
    }
    if (this.$route.params.statusTags) {
      this.filterTag = true
      this.form.alarmResultMap.statusTags = this.$route.params.statusTags
    }
    if (this.$route.params.tabLabel) {
      this.filterTag = true
      this.tabLabel = this.$route.params.tabLabel
    }

    // this.getBusinessType();

    // if (!this.filterTag)
    // {
    //   this.form.alarmResultMap.alertLevels = [4, 5, 3];
    //   this.form.alarmResultMap.reliability = "";
    // }

    this.tabClick()
  },
  methods: {
    getSourceType() {
      this.statics.datasourceType = this.datasourceType
    },
    getNewAlarmType() {
      this.statics.bigdataAlarmType = this.bigdataAlarmType
      this.statics.bigdataAlarmTypeParent = this.bigdataAlarmTypeParent
      this.statics.bigdataAlarmTypeSub = this.bigdataAlarmTypeSub
      this.statics.bigdataAlarmTypeTree = this.bigdataAlarmTypeTree
      this.statics.attackType = this.attackType
      this.statics.alertLevel = this.ruleLevel
    },
    clickRow(command, scope, index, rows) {
      if (command === 'detail') {
        const path = scope.row.alertSource != '2'
          ? '#/asp/alarmResultsDetail?id=' + scope.row.alertId
          : `#/asp/threatAlert/detail/${scope.row.alertId}`
        window.open(path, '_blank')
      }
      if (command === 'assign') {
        this.handleAssign(scope.row)
      }
      if (command === 'handle') {
        this.handleDeal(scope.row)
      }
    },
    // businessClear() {
    //   this.filterText = ''
    //   this.selectBusinessList = []
    //   this.form.alarmResultMap.businessIds = []
    //   this.$refs.businessTree.setCheckedKeys([])
    // },
    // businessClearHis() {
    //   this.filterTextHis = ''
    //   this.selectBusinessListHis = []
    //   this.form.alarmResultMap.businessIds = []
    //   this.$refs.businessTreeHis.setCheckedKeys([])
    // },
    // businessChange() {
    //   // 获取选中节点
    //   //      if (this.changeTimer) {
    //   //        clearTimeout(this.changeTimer)
    //   //      }
    //   var that = this
    //   //      this.changeTimer = setTimeout(function () {
    //   that.selectBusinessList = that.$refs['businessTree'].getCheckedNodes(
    //     true
    //   )
    //   //      }, 200)
    // },
    // businessChangeHis() {
    //   // 获取选中节点
    //   //      if (this.changeTimer) {
    //   //        clearTimeout(this.changeTimer)
    //   //      }
    //   var that = this
    //   //      this.changeTimer = setTimeout(function () {
    //   that.selectBusinessListHis = that.$refs['businessTreeHis'].getCheckedNodes(
    //     true
    //   )
    //   //      }, 200)
    // },
    // filterNode(value, data, node) {
    //   if (!value) {
    //     node.expanded = false
    //     return true
    //   }
    //   return data.label.indexOf(value) !== -1
    // },
    handleDealType() {
      this.dealValue = null
    },
    handleDealRefresh() {
      this.getCount()
      this.search()
    },
    // 指派
    handleAssign(row) {
      this.dealValue = row
      this.dealType = 'assign'
    },
    // 处理
    handleDeal(row) {
      // this.dealValue = row;
      // this.dealType = "dealAsk";
      let routeData = this.$router.resolve({
        name: 'alarmBatch',
        query: { statusTag: row.statusTag, alertId: row.alertId, rectification: row.rectification }
      })
      window.open(routeData.href, "_blank");
    },
    toCase: function(input, source, keyName, valueName) {
      let str
      if (!(source instanceof Array) || !source.length) {
        str = input
      } else {
        for (const e of source) {
          if (e[keyName] == input) {
            str = e[valueName]
          }
        }
      }
      return str
    },
    mainTableChoose(val) {
      this.multipleSelection = val
    },
    handleMergerDetailPageChange(currentNum) {
      this.queryEventForm.page.current = currentNum
      this.queryEventList()
    },
    clearForm() {
      if (this.tabLabel == '实时告警') {
        this.form.alarmResultMap.statusTags = ['0', '2', '6']
      } else {
        this.form.alarmResultMap.statusTags = ['3', '4', '5']
      }
      this.form.alarmResultMap.alertName = ''
      this.form.alarmResultMap.alertLevels = []
      this.form.alarmResultMap.alertSources = []
      this.form.alarmResultMap.alertTypes = []
      this.form.alarmResultMap.alertTypeSubs = []
      this.form.alarmResultMap.attackStages = []
      this.form.alarmResultMap.srcIp = null
      this.form.alarmResultMap.srcPort = null
      this.form.alarmResultMap.dstIp = null
      this.form.alarmResultMap.dstPort = null
      this.form.alarmResultMap.reliability = null
      this.form.alarmResultMap.successTags = null
      this.form.alarmResultMap.probeNos = null
      this.form.alarmResultMap.applyTime = []
      this.form.alarmResultMap.beginTime = null
      this.form.alarmResultMap.endTime = null
      this.form.alarmResultMap.deviceName = null
      // this.businessClear()
      // this.businessClearHis()
    },
    searchTodayTags: function() {
      this.clearForm()
      var end = ' 23:59:59'
      var star = ' 00:00:00'
      var nowDate = new Date()
      var year = nowDate.getFullYear()
      var month = nowDate.getMonth() + 1 < 10 ? '0' + (nowDate.getMonth() + 1)
        : nowDate.getMonth() + 1
      var day = nowDate.getDate() < 10 ? '0' + nowDate.getDate() : nowDate
        .getDate()
      var dateStr = year + '-' + month + '-' + day
      var value = [dateStr + star, dateStr + end]
      this.form.alarmResultMap.applyTime = value
      this.form.alarmResultMap.beginTime = value[0]
      this.form.alarmResultMap.endTime = value[1]
      // sessionStorage.setItem("alarmResultsTabLabel",this.tabLabel);
      // sessionStorage.setItem("alarmResultsQueryParam",JSON.stringify(this.form));
      this.getCount()
      this.search()
    },
    // 实时告警 攻击结果
    searchSuccessTags: function(val) {
      this.clearForm()
      this.form.alarmResultMap.successTags = [val]
      // sessionStorage.setItem("alarmResultsTabLabel",this.tabLabel);
      // sessionStorage.setItem("alarmResultsQueryParam",JSON.stringify(this.form));
      this.getCount()
      this.search()
    },
    // 实时告警 级别
    searchAlertLevel: function(val) {
      this.clearForm()
      this.form.alarmResultMap.alertLevels = [val]
      // sessionStorage.setItem("alarmResultsTabLabel",this.tabLabel);
      // sessionStorage.setItem("alarmResultsQueryParam",JSON.stringify(this.form));
      this.getCount()
      this.search()
    },
    // 实时告警 状态
    searchAlertStatus: function(val) {
      this.clearForm()
      this.form.alarmResultMap.statusTags = [val]
      // sessionStorage.setItem("alarmResultsTabLabel",this.tabLabel);
      // sessionStorage.setItem("alarmResultsQueryParam",JSON.stringify(this.form));
      this.getCount()
      this.search()
    },
    searchClick: function() {
      this.page.current = 1
      this.form.alarmResultMap.businessIds = []
      if (this.tabLabel == '实时告警') {
        for (const i in this.selectBusinessList) {
          this.form.alarmResultMap.businessIds.push(this.selectBusinessList[i].dataId)
        }
      } else {
        for (const i in this.selectBusinessListHis) {
          this.form.alarmResultMap.businessIds.push(this.selectBusinessListHis[i].dataId)
        }
      }
      // sessionStorage.setItem("alarmResultsTabLabel",this.tabLabel);
      // sessionStorage.setItem("alarmResultsQueryParam",JSON.stringify(this.form));
      this.getCount()
      this.search()
    },
    search() {
      const self = this
      this.loading = true
      this.form.page = this.page
      const temp = JSON.parse(JSON.stringify(this.form))
      if (this.isFlowAlarm) {
        temp.alarmResultMap.alertSources = ['2']
      }
      getAlarmResultList(temp)
        .then(response => {
          if (response.data.returnCode == '0') {
            this.tableData = response.data.data.list
            const { current, size, total } = response.data.data.page
            this.page.current = current
            this.page.size = size
            this.page.total = total

            if (self.soundTag) {
              self.openPlayer()
            }
          } else {
            this.$message.error(response.data.returnMsg)
          }
          this.loading = false
        })
        .catch(error => {
          if (error.response) {
            this.$message.error(error.response.data.detail)
          }
          this.loading = false
        })
    },
    // 分页切换事件
    handlePageChange() {

      const pageNum = this.$refs.table.page
      this.form.page.current = pageNum
      // sessionStorage.setItem("alarmResultsTabLabel",this.tabLabel);
      // sessionStorage.setItem("alarmResultsQueryParam",JSON.stringify(this.form));
      this.getCount()
      this.search()
    },
    collapseForm(type) {
      if (type == 'his') {
        if (this.orCollapseHis == false) {
          this.orCollapseHis = true
        } else {
          this.orCollapseHis = false
        }
      } else {
        if (this.orCollapseReal == false) {
          this.orCollapseReal = true
        } else {
          this.orCollapseReal = false
        }
      }
    },
    // 重置查询条件
    resetForm(type) {
      this.page.current = 1
      if (type == 'his') {
        this.form.alarmResultMap.statusTags = ['3', '4', '5']
      } else {
        this.form.alarmResultMap.statusTags = ['0', '2', '6']
        // this.form.alarmResultMap.statusTags = ["0", "1", "2","6"];
      }
      this.form.alarmResultMap.alertName = ''
      this.form.alarmResultMap.alertLevels = []
      this.form.alarmResultMap.alertSources = []
      this.form.alarmResultMap.alertTypes = []
      this.form.alarmResultMap.alertTypeSubs = []
      this.form.alarmResultMap.attackStages = []
      this.form.alarmResultMap.srcIp = null
      this.form.alarmResultMap.srcPort = null
      this.form.alarmResultMap.dstIp = null
      this.form.alarmResultMap.dstPort = null
      this.form.alarmResultMap.reliability = null
      this.form.alarmResultMap.successTags = null
      this.form.alarmResultMap.probeNos = null
      this.form.alarmResultMap.applyTime = []
      this.form.alarmResultMap.beginTime = null
      this.form.alarmResultMap.endTime = null
      this.form.alarmResultMap.deviceName = null
      // this.businessClear()
      // this.businessClearHis()
      this.getCount()
      this.search()
      // sessionStorage.setItem("alarmResultsQueryParam",JSON.stringify(this.form));
    },
    handleDetail(val, show) {
      if (show === 'common') {
        this.$router.push({
          // scrollBehavior: () => ({ y: 0 }),
          // document.body.scrollTop = document.documentElement.scrollTop = 0,
          name: 'alarmResultsDetail',
          query: { id: val }
          // meta: {keepAlive:true},
          // meta: {keepAlive:true},
          // toYpWebsite()
          // scrollBehavior(to, from, savedPosition) {
          //   return {
          //     x: 0,
          //     y: 0
          //   }
          // }
        })
      }
    },
    toYpWebsite() {
      document.body.scrollTop = document.documentElement.scrollTop = 0
    },
    getMultipleSelection: function() {
      const list = []
      for (const i in this.multipleSelection) {
        list.push(this.multipleSelection[i].alertId)
      }
      return list
    },
    exportClick: function() {
      // this.$message("开始导出,请稍候...");
      const temp = {
        alarmResultMap: {}
      }
      temp.alarmResultMap = JSON.parse(JSON.stringify(this.form.alarmResultMap))
      temp.alarmResultMap.alertIds = this.getMultipleSelection()
      exportAlarmResultList(temp)
        .then(resp => {
          if (resp.data.returnCode == '0') {
            // var elemIF = document.createElement("iframe");
            // elemIF.src = "/analyze/" + resp.data.data.url;
            // elemIF.style.display = "none";
            // document.body.appendChild(elemIF);
            this.$message.success('已加入离线任务队列，请在离线任务栏进行查看')
          } else {
            this.$message.error(resp.data.returnMsg)
          }
        })
        .catch(error => {
          if (error.response) {
            this.$message.error(error.response.data.detail)
          }
        })
    },
    ok() {
      this.$message.info('点击了确定')
    },
    cancel() {
      this.$message.info('点击了取消')
    },
    // 停止自动刷新
    refreshStop: function() {
      this.refreshVisible = false
      this.refreshTag = false
    },
    // 开始自动刷新
    refreshBegin: function() {
      this.refreshVisible = false
      this.refreshTag = true
    },
    // 告警声音点击
    soundClick: function() {
      this.soundTag = !this.soundTag
    },
    // 播放告警音乐
    openPlayer: function() {
      var audio = document.getElementById('audio')
      audio.play()
    },
    tabClick() {
      // sessionStorage.setItem("alarmResultsTabLabel",this.tabLabel);
      if (this.tabLabel == '实时告警') {
        this.resetForm('real')
        // this.form.alarmResultMap.statusTags = ["0", "1", "2","6"];
        this.form.alarmResultMap.statusTags = ['0', '2', '6']
        this.form.page.current = 1
        this.statics.statusTag = this.statics.realTimeStatusTag
      } else {
        this.resetForm('his')
        this.form.alarmResultMap.statusTags = ['3', '4', '5']
        this.form.page.current = 1
        this.statics.statusTag = this.statics.hisStatusTag
      }
      this.multipleSelection = []
      this.soundTag = false
      this.refreshTag = false

      this.getCount()
      this.search()
      // sessionStorage.setItem("alarmResultsQueryParam",JSON.stringify(this.form));
    },
    timeDeal(value) {
      // 时间范围格式化
      // let dateArr = value.split("-"),
      //   beginD = dateArr.splice(0, 3),
      //   endD = dateArr;
      // this.queryParam.queryMap.beginTime = beginD.join("-").trim();
      // this.queryParam.queryMap.endTime = endD.join("-").trim();
      this.form.alarmResultMap.applyTime = value
      this.form.alarmResultMap.beginTime = value[0]
      this.form.alarmResultMap.endTime = value[1]
    },
    getCount: function() {
      let type = 'real'
      if (this.tabLabel != '实时告警') {
        type = 'his'
      }
      countAlarmResult(type)
        .then(response => {
          if (response.data.returnCode == '0') {
            if (response.data.data != null) {
              const { data } = response.data
              this.countInfo.todayNewNum = data.TODAYNEWNUM
              this.countInfo.assignedNum = data.ASSIGNEDNUM
              this.countInfo.checkNum = data.CHECKNUM
              this.countInfo.confirmedNum = data.CONFIRMEDNUM
              this.countInfo.highNum = data.HIGHNUM
              this.countInfo.intermediateNum = data.INTERMEDIATENUM
              this.countInfo.lowNum = data.LOWNUM
              this.countInfo.mildNum = data.MILDNUM
              this.countInfo.pendingNum = data.PENDINGNUM
              this.countInfo.severeNum = data.SEVERENUM
              this.countInfo.successNum = data.SUCCESSNUM
              this.countInfo.suspectedNum = data.SUSPECTEDNUM
              this.countInfo.unSuccessNum = data.UNSUCCESSNUM
              this.countInfo.ignoredNum = data.IGNOREDNUM
              this.countInfo.clearedNum = data.CLEAREDNUM
              this.countInfo.processedNum = data.PROCESSEDNUM
            } else {
              this.countInfo.todayNewNum = 0
              this.countInfo.assignedNum = 0
              this.countInfo.checkNum = 0
              this.countInfo.confirmedNum = 0
              this.countInfo.highNum = 0
              this.countInfo.intermediateNum = 0
              this.countInfo.lowNum = 0
              this.countInfo.mildNum = 0
              this.countInfo.pendingNum = 0
              this.countInfo.severeNum = 0
              this.countInfo.successNum = 0
              this.countInfo.suspectedNum = 0
              this.countInfo.unSuccessNum = 0
              this.countInfo.ignoredNum = 0
              this.countInfo.clearedNum = 0
              this.countInfo.processedNum = 0
            }
          } else {
            this.$message.error(response.data.statusString)
          }
        })
        .catch(error => {
          if (error.response) {
            this.$message.error(error.response.data.detail)
          }
        })
    },
    openExportReportDialog: function() {
      this.reportVisible = true
    },
    closeExportReportDialog: function() {
      this.reportVisible = false
      this.$refs.reportParams.resetFields()
      this.reportParams.analysisReportMap.reportName = null
      this.reportParams.analysisReportMap.reportTime = ''
      this.reportParams.analysisReportMap.startTime = null
      this.reportParams.analysisReportMap.endTime = null
    },
    reportTimeChangeHandle: function(value) {
      var dataArr = value.split('-')
      var before = dataArr.splice(0, 3)
      var after = dataArr
      this.reportParams.analysisReportMap.startTime = before.join('-')
      this.reportParams.analysisReportMap.endTime = after.join('-')
    },
    submitReport: function() {
      this.reportLoading = true
      this.$refs['reportParams'].validate(valid => {
        if (valid) {
          analysisReport(this.reportParams).then(resp => {
            if (resp.data.returnCode == '0') {
              this.$message.success(
                '已加入离线任务队列，请在离线任务栏进行查看'
              )
              this.closeExportReportDialog()
            }
            this.reportLoading = false
          }).catch(error => {
            if (error.response) {
              this.$message.error(error.response.data.returnMsg)
              this.reportLoading = false
            }
          })
        } else {
          this.reportLoading = false
        }
      })
    }
  },
  beforeRouteUpdate(to, from, next) {
    if (from.name == 'alarmResultsDetail' || from.name == 'flowAlarmResults' || from.name == 'alarmBatch') {
      this.getCount()
      this.search()
    }
    next()
  }
}
</script>
<style lang="scss" scoped>
  @import url(./layoutStyle.css);

  .actived {
    color: #fff !important;
    background-color: RGB(45, 140, 240) !important;
    border-color: #fff !important;
  }

  table {
    border-right: 1px solid #dcdee2;
    border-bottom: 1px solid #dcdee2;
    border-collapse: collapse;
  }

  table td {
    border-left: 1px solid #dcdee2;
    border-top: 1px solid #dcdee2;
  }

  .headCardBegin {
    margin: 0 5px 0 0 !important;
  }

  .headCardEnd {
    margin: 0 0 0 5px !important;
  }

  .headCard {
    margin: 0 5px 0 5px;
    background: #fff;
    // border-radius: 4px;
    font-size: 14px;
    // border: 1px solid #dcdee2;
    border-color: #e8eaec;
    text-align: center;
    height: 87px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    & > div {
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }

  .cardTitle {
    border-bottom: 1px solid #e8eaec;
    padding: 14px 0;
    background-color: #f8f8f9;
    font-weight: 700;
    color: #17233d;
    line-height: 20px;
    font-size: 14px;
  }

  .cardValue {
    padding: 14px 0px;
    font-size: 22px;
    line-height: 30px;
  }

  .cursor {
    cursor: pointer;
  }

  .cardRed {
    color: rgb(237, 64, 20);
  }

  .cardBule {
    color: rgb(92, 173, 255);
  }

  .cardBulePlus {
    color: rgb(45, 140, 240);
  }

  .cardLight {
    color: #58b7ff;
  }

  .cardLow {
    color: #20a0ff;
  }

  .cardMid {
    color: #1d8ce0;
  }

  .cardHigh {
    color: #f7ba2a;
  }

  .alarm {
    .cardIcon {
      margin-right: 10px;
      &.today {
        height: 35px;
        width: 32px;
      }
      &.success {
        height: 35px;
        width: 36px;
      }
      &.level {
        height: 31px;
        width: 36px;
      }
    }
    .cardMain {
      text-align: left;
      flex-direction: column;
      max-width: 48px;
      & > :first-child {
        display: inline-block;
        margin-bottom: 10px;
        color: #333333;
        font-size: 18px;
        font-weight: bold;
        cursor: pointer;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      & > :last-child {
        color: #666666;
        font-size: 12px;
        font-weight: 400;
      }
    }
  }
</style>
