<template>
  <div class="threatAlarms">
    <YaPageContent @selectionChange="handleSelectionChange" @tableBtnClick="tableBtnClick" :stripe="true"
      :tableData="tableData" :tableColumns="column" @init="initData" :total="total" ref="multipleTableRef">
      <template #pageContentTop>
        <div class="nav-top">
          <YaTabs :tabs="tabs" v-model="currentName" @tabChange="tabChange" @tabClick="tabClick"></YaTabs>
        </div>
      </template>
      <template #pageContentCenter>
        <Header :headerObj="searchData" ref="headerRef"></Header>
        <div class="flex-bt">
          <div>
            <YaDropDown v-if="butomData.has(220100) && origin === 'situation'" :data="customData" title="导出"
              @select="handleDropDownSelect">
            </YaDropDown>
            <!-- 这行暂时放开，后期探针集成全部导出后删除,上面的origin === 'situation'这个条件移除 -->
            <ya-button :plain="true" @click="operationBtn('export')" v-else-if="butomData.has(220100)">批量导出</ya-button>
            <ya-button :plain="true" @click="operationBtn('study')"
              v-if="currentName == 0 && butomData.has(220101)">批量研判</ya-button>
            <ya-button :plain="true" @click="operationBtn('issure')"
              v-if="currentName == 1 && butomData.has(220102)">批量下发</ya-button>
          </div>
          <div class="flex-st">
            <span class="refresh-span">刷新间隔</span>
            <YaDropDown :title="timeTitle" :data="dropData" @select="handleSelect"></YaDropDown>
            <span class="refresh-icon" @click="resetInitData">
              <svg t="1679908489518" class="icon refresh" viewBox="0 0 1024 1024" version="1.1"
                xmlns="http://www.w3.org/2000/svg" p-id="4951" xmlns:xlink="http://www.w3.org/1999/xlink" width="200"
                height="200">
                <path
                  d="M605.013333 644.736a161.28 161.28 0 0 1-94.976 29.226667c-4.48-0.042667-8.874667-0.384-13.269333-0.725334-1.792-0.170667-3.584-0.426667-5.376-0.725333a133.888 133.888 0 0 1-10.24-1.536c-2.090667-0.384-4.138667-0.938667-6.144-1.450667a148.650667 148.650667 0 0 1-9.813333-2.389333l-4.522667-1.664a123.818667 123.818667 0 0 1-11.008-3.968l-2.389333-0.981333a277.333333 277.333333 0 0 1-12.373334-5.973334l-0.512-0.298666a161.834667 161.834667 0 0 1-36.949333-27.690667c-0.170667-0.170667-0.298667-0.426667-0.512-0.597333a135.168 135.168 0 0 1-9.685333-10.666667 161.237333 161.237333 0 0 1-37.376-103.381333h42.666666l-68.266666-102.4-68.266667 102.4h42.666667c0 44.842667 13.994667 86.442667 37.76 120.917333 0.298667 0.512 0.469333 1.024 0.810666 1.493333 2.432 3.541333 5.205333 6.784 7.808 10.069334 1.024 1.194667 1.877333 2.432 2.944 3.754666a237.653333 237.653333 0 0 0 13.44 14.677334c14.293333 14.336 30.378667 26.325333 47.957334 36.010666l1.408 0.768c5.077333 2.688 10.24 5.205333 15.488 7.509334l3.925333 1.706666a352.938667 352.938667 0 0 0 20.48 7.338667c4.010667 1.152 8.149333 2.218667 12.373333 3.157333 2.816 0.682667 5.546667 1.408 8.362667 1.92 1.194667 0.298667 2.261333 0.64 3.413333 0.768 4.010667 0.725333 7.978667 1.066667 11.946667 1.536 1.408 0.256 2.858667 0.512 4.266667 0.682667a211.754667 211.754667 0 0 0 143.274666-37.546667 25.6 25.6 0 0 0-29.312-41.941333m120.234667-132.821333a211.626667 211.626667 0 0 0-37.504-120.533334l-0.853333-1.706666a261.76 261.76 0 0 0-9.386667-12.117334 14.933333 14.933333 0 0 1-1.109333-1.450666 213.333333 213.333333 0 0 0-79.658667-59.818667c-0.896-0.341333-1.664-0.768-2.56-1.109333a256.64 256.64 0 0 0-15.104-5.546667c-1.706667-0.554667-3.584-1.237333-5.418667-1.749333a212.778667 212.778667 0 0 0-13.397333-3.498667c-2.517333-0.554667-5.034667-1.194667-7.552-1.706667-1.237333-0.213333-2.346667-0.597333-3.669333-0.853333-3.413333-0.554667-6.698667-0.853333-10.069334-1.28l-6.997333-0.853333a221.354667 221.354667 0 0 0-16.938667-0.853334c-1.024 0-2.048-0.170667-3.072-0.170666-0.170667 0-0.341333 0-0.554666 0.085333a211.456 211.456 0 0 0-121.770667 38.485333 25.6 25.6 0 1 0 29.44 41.898667 160.768 160.768 0 0 1 108.373333-28.458667c1.450667 0.085333 2.858667 0.341333 4.266667 0.554667 3.882667 0.426667 7.68 0.981333 11.52 1.749333 1.621333 0.298667 3.285333 0.725333 4.864 1.109334 3.754667 0.853333 7.381333 1.706667 10.965333 2.816a30.762667 30.762667 0 0 1 3.413334 1.152c4.138667 1.322667 8.234667 2.773333 12.16 4.437333 0.426667 0.085333 0.853333 0.426667 1.237333 0.597333a162.688 162.688 0 0 1 61.44 46.122667c22.997333 28.032 36.821333 63.744 36.864 102.698667h-42.752l68.394667 102.4 68.181333-102.4h-42.752z"
                  p-id="4952"></path>
              </svg>
            </span>
          </div>
        </div>
      </template>
      <template #srcIp="{ item }">
        <div v-if="item.srcIp">
          <div>{{ item.srcIp }}</div>
          <div>{{ item.srcLocation }}</div>
        </div>
        <div v-else>-</div>
      </template>
      <template #distIp="{ item }">
        <div v-if="item.destIp">
          <div>{{ item.destIp }}</div>
          <div>{{ item.destLocation }}</div>
        </div>
        <div v-else>-</div>
      </template>
      <!-- <template #name="{ item }">
        <div class="name text-decoration" @click="toDetail(item)">
            {{ item.eventName }}
          </div>
      </template> -->
      <template #level="{ item }">
        <div class="level-content" :class="item.threatLevel == '高危'
          ? 'level-heigh'
          : item.threatLevel == '中危'
            ? 'level-center'
            : 'level-low'
          ">
          <svg t="1679909150644" class="icon level level-svg" viewBox="0 0 1110 1024" version="1.1"
            xmlns="http://www.w3.org/2000/svg" p-id="5101" xmlns:xlink="http://www.w3.org/1999/xlink" width="216.796875"
            height="200">
            <path
              d="M377.186816 739.199128L546.728412 446.029965a11.157723 11.157723 0 0 1 19.470226 0l169.262653 293.169163a11.157723 11.157723 0 0 1-9.707219 16.736584H386.949823a11.157723 11.157723 0 0 1-9.763007-16.736584zM882.743231 432.640697l2.845219 62.204304a16.011332 16.011332 0 0 0 7.419886 12.719804l51.437101 32.301607a11.157723 11.157723 0 0 1-3.570471 20.362844l-235.762681 51.325525a5.578861 5.578861 0 0 1-5.578861-9.205122l163.906946-176.682538a11.157723 11.157723 0 0 1 19.302861 6.973576zM615.459984 1022.661073l-54.393898-29.567965a15.843966 15.843966 0 0 0-14.672406 0l-54.282321 27.336421a11.157723 11.157723 0 0 1-15.565023-13.556633l78.104059-228.398584a5.578861 5.578861 0 0 1 10.599837 0L631.415527 1009.773904a11.157723 11.157723 0 0 1-15.955543 12.887169zM407.256878 614.4l-238.496322-51.939199a10.04195 10.04195 0 0 1-3.23574-18.298665l53.836012-33.8079a15.6766 15.6766 0 0 0 7.308308-12.775593l2.84522-61.367474a11.157723 11.157723 0 0 1 19.414437-7.085154l163.572215 176.23623a5.578861 5.578861 0 0 1-5.24413 9.037755z"
              p-id="5102"></path>
            <path
              d="M1043.247072 1016.412749h-334.731681a66.946336 66.946336 0 1 1 0-133.892673h210.82517l-113.808771-173.725742a66.951915 66.951915 0 0 1 112.023536-73.362027L1099.035685 912.924871a66.946336 66.946336 0 0 1-55.788613 103.487878zM401.678017 1016.412749H66.946336a66.946336 66.946336 0 0 1-55.788613-103.487878l181.703514-277.325198a66.951915 66.951915 0 0 1 112.023536 73.362027l-114.031926 173.558376H401.678017a66.946336 66.946336 0 0 1 0 133.892673zM722.016235 428.177608a66.946336 66.946336 0 0 1-59.414873-36.095233l-95.789049-184.102424-103.208935 183.600327a66.946336 66.946336 0 0 1-116.765568-65.495832L510.744756 34.19842A66.946336 66.946336 0 0 1 569.043857 0h1.115773a66.946336 66.946336 0 0 1 58.299101 36.039444l152.916589 294.173359a66.946336 66.946336 0 0 1-59.359085 97.853228z"
              p-id="5103"></path>
          </svg>
          <span>{{ item.threatLevel }}</span>
        </div>
      </template>
      <template #result="{ item }">
        <div v-if="item.attackResult" class="attackResult" :class="item.attackResult == '企图'
          ? 'attackResult-warning'
          : item.attackResult == '成功'
            ? 'attackResult-success'
            : 'attackResult-error'
          ">
          {{ item.attackResult }}
        </div>
        <div v-else>-</div>
      </template>
    </YaPageContent>
    <ya-drawer :loading="isLoadingBtn" v-if="drawerProps.showDrawer" :drawerProps="drawerProps" @handleEvent="handleEvent"
      destroy-on-close :size="drawerProps.title == '事件详情' ? 'calc(100vw - 200px)' : '450px'"
      :before-close="handleCloseDrawer" :hiddenFooter="drawerProps.title == '事件详情' ? true : false">
      <template #content>
        <DetailTab @closeF="resetInitData" :origin="origin" :info="detailInfo" :searchObj="searchObj"
          v-if="drawerProps.title == '事件详情'"></DetailTab>
        <div v-else style="margin-top: 16px">
          <OperateDialog ref="operateDialogRef" :info="operateInfo" :type="drawerProps.title == '批量研判' ? 1 : 2"
            @closeF="closeF" @resetLoading="resetLoading"></OperateDialog>
        </div>
      </template>
    </ya-drawer>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted, reactive, unref, onUnmounted, nextTick } from "vue";
import { usePermissions } from "../../composables/usePermissions";
import { ElMessageBox, ElMessage, FormRules } from "element-plus";
import { useRouter } from "vue-router";
import Header from "./componets/header.vue";
import DetailTab from "./detailTab.vue";
import OperateDialog from "./componets/operateDialog.vue";
import {
  getPage,
  postExport,
  postAllExport
} from "../../api/threatAlarms/threatAlarms";
import dayjs from "dayjs/esm";
import { getDictTypeList } from "../../api/common";
import { downLoadAllFile } from "../../utils/utils"
import { yaMessage } from "@/utils/message";
let newDate = dayjs(Date.now()).format('YYYY-MM-DD');
let endDate = dayjs().subtract(0, 'day').format('YYYY-MM-DD');
// flow--探针  situation--感知平台
const { origin = "situation" } = defineProps({
  origin: String,
});
const router = useRouter();
const tabs = ref([
  { title: "待研判", value: 0 },
  { title: "待下发", value: 1 },
  { title: "已处置", value: 2 },
]);
const currentName = ref(0);
const tabChange = () => {
  clearSelect();
  nextTick(() => {
    multipleTableRef.value.reset();
  })
};
const tabClick = (name) => {
  console.log("tabClick", name);
};
const dropData = [
  {
    name: "不自动刷新",
  },
  {
    name: "30秒",
  },
  {
    name: "1分钟",
  },
  {
    name: "5分钟",
  },
  {
    name: "30分钟",
  },
];
const timeTitle = ref('');
const timer = ref(null);
/**
 * @description: 刷新间隔选择
 */
const handleSelect = (item, e) => {
  timeTitle.value = item.name;
  clearInterval(timer.value)
  if (item.name == '30秒') {
    timer.value = setInterval(() => {
      resetInitData()
    }, 30000)
  }
  if (item.name == '1分钟') {
    timer.value = setInterval(() => {
      resetInitData()
    }, 60000)
  }
  if (item.name == '5分钟') {
    timer.value = setInterval(() => {
      resetInitData()
    }, 300000)
  }
  if (item.name == '30分钟') {
    timer.value = setInterval(() => {
      resetInitData()
    }, 1800000)
  }
};
const { permissionsButtons } = usePermissions();
const butomData: any = ref(new Map());
const leftButtons = ref([]);
const rightButtons = ref([]);
const selectData = ref([]);
const serchformData = reactive({
  time: [endDate, newDate],
  eventStatus: currentName.value,
});
//导出下拉框
const customData = [
  {
    name: '批量导出',
    eventName: 'export',
  },
  {
    name: '全部导出',
    eventName: 'allExport',
  },
]

const tableData = ref([]);
// 表格数据定义
const column = ref([
  {
    type: "selection",
    width: "65px",
    fixed: "left",
  },
  {
    prop: "alarmTime",
    label: "生成时间",
    minWidth: "180px",
    search: true,
    type: "daterange",
    valueFormat: "YYYY-MM-DD",
    value: [endDate, newDate]
  },
  {
    prop: "srcIp",
    type: "input",
    label: "源IP",
    search: true,
    tableHide: true,
  },
  {
    prop: "destIp",
    type: "input",
    label: "目的IP",
    search: true,
    tableHide: true,
  },
  {
    label: "源IP/归属地",
    minWidth: "150px",
    slotName: "srcIp",
  },
  {
    prop: "srcPort",
    label: "源端口",
    minWidth: "120px",
  },
  {
    label: "目的IP/归属地",
    slotName: "distIp",
    minWidth: "180px",
  },
  {
    prop: "destPort",
    label: "目的端口",
    minWidth: "120px",
  },
  {
    prop: "eventName",
    type: "input",
    label: "事件名称",
    width: "180px",
    search: true,
    eventName: 'eventName'
  },
  {
    prop: "eventType",
    label: "事件类型",
    search: true,
    type: "select",
    options: [],
    minWidth: "150px",
    filterable: true
  },
  {
    prop: "threatLevel",
    label: "威胁等级",
    search: true,
    type: "select",
    options: [],
    minWidth: "120px",
    slotName: "level",
  },
  {
    prop: "attackResult",
    label: "攻击结果",
    minWidth: "120px",
    slotName: "result",
    search: true,
    type: "select",
    options: [],
  },
  {
    prop: "killChain",
    label: "攻击链阶段",
    minWidth: "120px",
    search: true,
    type: "select",
    options: [],
  },
]);
const searchData = ref({});
// 列表数据获取
const initData = async (type) => {
  let _data = JSON.parse(JSON.stringify(type))._value;
  if (type) {
    let pageInfo = JSON.parse(JSON.stringify(type))._value;
    page.value = pageInfo.pageIndex;
    pageSize.value = pageInfo.pageSize;
  }
  if (_data.alarmTime) {
    _data.startTime = _data.alarmTime[0];
    _data.endTime = _data.alarmTime[1];
    delete _data.alarmTime;
  }
  let prams = {
    ..._data,
    pageIndex: page.value,
    pageSize: pageSize.value,
    eventStatus: currentName.value,
  };
  searchData.value = prams;
  nextTick(() => {
    headerRef.value.init();
  })
  let res = await getPage(prams);
  if (res.code == 200) {
    tableData.value = res.data.records;
    total.value = res.data.total;
  }
};
const page = ref(1);
const total = ref(1);
const pageSize = ref(20);
// 重置
const reset = () => {
  page.value = 1;
  resetInitData()
};

// 获取按钮权限
const getButton = () => {
  permissionsButtons.map((item) => {
    butomData.value.set(item.menuId, item);
  });
};
/**
 * @description: 详情
 */
const detailInfo = ref({});
const searchObj = ref({})
const toDetail = (e) => {
  drawerProps.title == '事件详情';
  drawerProps.showDrawer = true;
  detailInfo.value = e;
  searchObj.value = {
    id: e.id,
    ...searchData.value
  }
};
const operateDialogRef = ref();
// 弹窗
const drawerProps = reactive({
  showDrawer: false,
  title: "事件详情",
  size: "small",
});
// 关闭抽屉
const handleCloseDrawer = async () => {
  drawerProps.title = "事件详情";
  drawerProps.showDrawer = false;
};
/**
 * @description 研判成功时回调方法
 */
const closeF = () => {
  drawerProps.showDrawer = false;
  resetInitData()
  clearSelect();
}
const isLoadingBtn = ref(false);
const resetLoading = () => {
  isLoadingBtn.value = !isLoadingBtn.value;
}
// 抽屉事件
const handleEvent = function (data) {
  if (drawerProps.title == "批量研判" || drawerProps.title == "批量下发") {
    operateDialogRef.value.handleEvent(data);
  } else {
    if (data.eventName == "errorSubmit") {
      return;
    } else if (data.eventName == "success") {
      return;
    } else if (data.eventName == "successSubmit") {
      return;
    }
  }
};
const operateInfo = ref({
  ids: [],
  dates: []
})
/**
 * @description 操作
 */
const operationBtn = (e) => {
  if (selectData.value.length == 0)
    return ElMessage.warning(
      e == "study"
        ? "请选择批量研判数据!"
        : e == "export"
          ? "请选择批量导出数据!"
          : "请选择批量下发数据"
    );
  switch (e) {
    case "study":
      drawerProps.title = "批量研判";
      drawerProps.showDrawer = true;
      operateInfo.value.ids = selectData.value.map((item) => {
        return item.id
      })
      operateInfo.value.dates = selectData.value.map((item) => {
        return item.alarmTime
      })
      break;
    case "issure":
      drawerProps.title = "批量下发";
      drawerProps.showDrawer = true;
      operateInfo.value.ids = selectData.value.map((item) => {
        return item.id
      })
      operateInfo.value.dates = selectData.value.map((item) => {
        return item.alarmTime
      });
      break;
    case "export":
      let ids = selectData.value.map((item) => {
        return item.id
      })
      let dates = selectData.value.map((item) => {
        return item.alarmTime
      })
      postExport({ ids: ids, dates: dates }).then(res => {
        const fileReader = new FileReader()
        fileReader.readAsText(res, 'utf-8');
        fileReader.onload = function (result) {
          try {
            let target = JSON.parse(result.target.result);
            if (target.code == 200) {
              if (unref(origin) == 'situation') {
                downLoadAllFile(res, "告警中心列表.xlsx");
              } else {
                downLoadAllFile(res, "威胁告警列表.xlsx");
              }
              clearSelect()
            } else {
              ElMessage.error(target.message)
            }
          } catch (err) {
            if (unref(origin) == 'situation') {
              downLoadAllFile(res, "告警中心列表.xlsx");
            } else {
              downLoadAllFile(res, "威胁告警列表.xlsx");
            }
          }
        }
      })
      break;
  }
};
const multipleTableRef = ref<InstanceType<typeof ElTable>>();
// 清空选择的值
const clearSelect = () => {
  multipleTableRef.value?.getTableMethods()?.clearSelection()
}
/**
 * @descritpion 初始化
 */
const init = () => {
  // 事件类型数据获取
}
// 全选
const handleSelectionChange = function (val) {
  selectData.value = val;
};
/**
 * @description 字典列表
 */
const getDict = () => {
  getDictTypeList("threatLevel").then((res) => {
    column.value.forEach((item) => {
      if (item.prop == 'threatLevel') {
        item.options = res
      }
    })
  });
  getDictTypeList("eventType").then((res) => {
    column.value.forEach((item) => {
      if (item.prop == 'eventType') {
        item.options = res
      }
    })
  });
  getDictTypeList("attackResultType").then((res) => {
    column.value.forEach((item) => {
      if (item.prop == 'attackResult') {
        item.options = res
      }
    })
  });
  getDictTypeList("killChain").then((res) => {
    column.value.forEach((item) => {
      if (item.prop == 'killChain') {
        item.options = res
      }
    })
  });
};

// 表格点击事件
const tableBtnClick = (btn, row) => {
  const { eventName } = btn;
  switch (eventName) {
    case "eventName":
      drawerProps.title = '事件详情'
      toDetail(row)
      break;
  }
}
//导出按钮的事件
const handleDropDownSelect = (btn) => {
  const { eventName } = btn || {}
  if (eventName == 'export') {
    operationBtn('export')
  } else {
    postAllExport(searchData.value).then(res => {
      const { code, message } = res || {}
      code == 200 && yaMessage(message, 'success')
    })
  }
}
/**
 * @description 调用列表初始化方法
 */
const resetInitData = () => {
  multipleTableRef.value.initData()
}
const headerRef = ref(null);
onMounted(() => {
  getButton();
  init();
  getDict();
  if (unref(origin) == 'situation') {
    column.value.push({
      prop: "devIp",
      type: "input",
      width: "120px",
      label: "探针IP",
      search: true,
    });
  }
});
onUnmounted(() => {
  clearTimeout(timer.value)
  timer.value = null
})
</script>
<style lang="scss" scoped>
::v-deep .ya-page-content-top {
  position: sticky;
  top: 0;
  background: #fff;
  z-index: 111;
}

.threatAlarms {
  color: var(--el-text-color-primary);

  .nav-top {
    padding: 14px 0 10px 0;

  }
}

.flex-bt {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.flex-st {
  display: flex;
  align-items: center;

  .refresh-span {
    display: inline-block;
    margin-right: 8px;
  }
}

.refresh-icon {
  border: 1px solid var(--el-border-color);
  display: inline-block;
  height: 30px;
  width: 30px;
  border-radius: 2px;
  cursor: pointer;

  .refresh {
    fill: var(--el-border-color);
    width: 30px;
    height: 30px;
  }
}

.name {
  display: block;
  word-break: break-all;
  word-wrap: break-word;
  white-space: pre-wrap;
  text-overflow: -o-ellipsis-lastline;
  overflow: hidden; //溢出内容隐藏
  text-overflow: ellipsis; //文本溢出部分用省略号表示
  display: -webkit-box; //特别显示模式
  -webkit-line-clamp: 2; //行数
  line-clamp: 2;
  -webkit-box-orient: vertical; //盒子中内容竖直排列
  font-size: 14px;
  font-weight: 400;
  cursor: pointer;
}

.text-decoration {
  text-decoration: underline;
  color: var(--el-color-primary);
}

.level-content {
  font-weight: 400;
  display: flex;
  align-items: center;
}

.level-svg {
  width: 15px;
  height: 15px;
  margin-right: 5px;
}

.level-heigh {
  color: var(--el-color-danger);

  svg {
    fill: var(--el-color-danger);
  }
}

.level-center {
  color: var(--el-color-warning);

  svg {
    fill: var(--el-color-warning);
  }
}

.level-low {
  color: var(--el-color-primary);

  svg {
    fill: var(--el-color-primary);
  }
}

::v-deep .el-drawer__body {
  padding-top: 0;
}

::v-deep .ya-layout-content-container-right {
  padding-top: 0;
}

.attackResult {
  width: 44px;
  height: 20px;
  line-height: 20px;
  text-align: center;
  font-weight: 400;
  font-size: 14px;
  color: #ffffff;
}

.attackResult-warning {
  background: var(--attack-attempt);
}

.attackResult-error {
  background: var(--attack-attempt);
}

.attackResult-success {
  background: var(--attack-success);
}

.ya-bg {
  padding: 0;
}
</style>
