<!--
 * @Author: 曹文丽 caowenli@yuan-info.com
 * @Date: 2022-11-01 19:29:17
 * @LastEditors: 曹文丽 caowenli@yuan-info.com
 * @LastEditTime: 2023-04-18 15:22:34
 * @FilePath: \yuan-huoling-browser\src\views\digitalAssets\assetRisk\hostVulnerability.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="yaBox">
    <YaPageContent
      ref="multipleTableRef"
      :formData="serchformData"
      :formColumns="serchColumns"
      :tableData="tableData"
      :tableColumns="column"
      :leftButtons="leftButtons"
      searchLabelWidth="90px"
      @search="initData('init')"
      @reset="reset"
      @tableBtnClick="tableBtnClick"
      @selectionChange="handleSelectionChange"
      :currentPage="serchformData.pageIndex"
      :pageSize="serchformData.pageSize"
      :total="total"
      @sizeChange="sizeChange"
      @currentChange="currentChange"
    >
      <template #pageContentTop>
        <div class="yaHeader">
          <div
            v-for="item in headerBlock"
            :key="item.id"
            :class="{
              'ya-risk1': item.id == 1,
              'ya-risk2': item.id == 2,
              'ya-risk3': item.id == 3,
              'ya-risk4': item.id == 4,
            }"
            @click="trangle(item.id)"
          >
            <div
              class="ya-trangle"
              :class="{
                'ya-trangle1': item.id == 1,
                'ya-trangle2': item.id == 2,
                'ya-trangle3': item.id == 3,
                'ya-trangle4': item.id == 4,
              }"
              v-show="num == item.id"
            ></div>
            <div class="ya-risk-left">
              <img :src="item.rightImg" alt="" />
            </div>
            <div class="ya-risk-center">
              <div>{{ item.riskName }}风险</div>
              <div>{{ item.riskNum["总数"] || "0" }}</div>
            </div>
            <div class="ya-risk-right">
              <div class="ya-risk-right-item">
                <img src="../../../assets/imgs/di.png" alt="" />低危({{
                  item.riskNum["低危"] || "0"
                }})
              </div>
              <div class="ya-risk-right-item">
                <img src="../../../assets/imgs/zhong.png" alt="" />中危({{
                  item.riskNum["中危"] || "0"
                }})
              </div>
              <div class="ya-risk-right-item">
                <img src="../../../assets/imgs/gao.png" alt="" />高危({{
                  item.riskNum["高危"] || "0"
                }})
              </div>
            </div>
          </div>
        </div></template
      >
      <template v-slot:level="{ item }">
        <div v-if="item.level == 3">
          <img src="../../../assets/imgs/diwei.png" alt="" /> <span>低危</span>
        </div>
        <div v-else-if="item.level == 2">
          <img src="../../../assets/imgs/middle.png" alt="" /> <span>中危</span>
        </div>
        <div v-else-if="item.level == 1">
          <img src="../../../assets/imgs/gaowei.png" alt="" /> <span>高危</span>
        </div>
        <div v-else>-</div>
      </template>
      <template v-slot:state="{ item }">
        <div class="ya-stateColor1" v-if="item.handleStatus == 1">
          {{ item.handleStatusStr }}
        </div>
        <div class="ya-stateColor2" v-else-if="item.handleStatus == 2">
          {{ item.handleStatusStr }}
        </div>
        <div class="ya-stateColor3" v-else-if="item.handleStatus == 3">
          {{ item.handleStatusStr }}
        </div>
        <div class="ya-stateColor4" v-else-if="item.handleStatus == 4">
          {{ item.handleStatusStr }}
        </div>
        <div class="ya-stateColor5" v-else-if="item.handleStatus == 5">
          {{ item.handleStatusStr }}
        </div>
        <div v-else>-</div>
      </template>
      <template v-if="bottomData.has(200021)" v-slot:done="{ item }">
        <span @click="goToDetail(item)">
          <TableBtns :title="bottomData.get(200021).label" type="8"></TableBtns>
        </span>
      </template>
    </YaPageContent>
    <ya-dialog
      v-if="dialogProps.showDialog"
      :dialogProps="dialogProps"
      @open="handleDialogOpen()"
      title="选择格式"
    >
      <template #content>
        <ya-form
          @handleEvent="handleDialogEvent"
          :formColumns="formColumns"
          labelWidth="100px"
          :formData="formData"
          :rules="rules"
          :ref="
            (el) => {
              if (el) dialogForm = el;
            }
          "
        >
        </ya-form>
      </template>
      <template #footer>
        <ya-button @click="handleCancel">取消</ya-button>
        <ya-button type="primary" @click="handleConfirm">确定</ya-button>
      </template>
    </ya-dialog>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from "vue";
import { useRouter } from "vue-router";
import {
  createVul,
  exportByIds,
  gapsStatistic,
} from "../../../api/digitalAssets/assetRisk/hostVulnerability";
import { usePermissions } from "../../../composables/usePermissions";
import { getDictList, downLoadFile } from "../../../utils/utils";
import { yaMessage } from "../../../utils/message";
import { ElTable } from "element-plus";
import beDeliveredImg from "../../../assets/imgs/daixiafa.png";
import beRepairedImg from "../../../assets/imgs/daixiufu.png";
import beenRepairedImg from "../../../assets/imgs/yixiufu.png";
import outSightImg from "../../../assets/imgs/yihulue.png";
const router = useRouter();
const { permissionsButtons } = usePermissions();
const headerBlock = ref([
  {
    id: 1,
    rightImg: beDeliveredImg,
    riskName: "待下发",
    riskNum: {},
  },
  {
    id: 2,
    rightImg: beRepairedImg,
    riskName: "待修复",
    riskNum: {},
  },
  {
    id: 3,
    rightImg: beenRepairedImg,
    riskName: "已修复",
    riskNum: {},
  },
  {
    id: 4,
    rightImg: outSightImg,
    riskName: "已忽略",
    riskNum: {},
  },
]);
let tableData = ref([]);
let leftButtons: any = ref([]);
let bottomData: any = new Map();
let num = ref(1);
const serchformData: any = ref({
  pageIndex: 1,
}); //搜索区域的内容
const column: any[] = [
  {
    type: "selection",
    width: "65px",
  },
  {
    prop: "ip",
    label: "资产IP",
    minWidth: "160px",
  },
  {
    prop: "networkArea",
    label: "网络域",
    minWidth: "110px",
  },
  {
    prop: "domain",
    label: "域名",
    minWidth: "130px",
  },
  {
    prop: "url",
    label: "URL地址",
    minWidth: "130px",
  },
  {
    prop: "port",
    label: "端口",
    minWidth: "80px",
  },
  {
    prop: "name",
    label: "风险名称",
    minWidth: "110px",
  },
  {
    prop: "deptName",
    label: "风险归属",
    minWidth: "120px",
  },
  {
    prop: "level",
    label: "风险等级",
    slotName: "level",
    width: "110px",
  },
  {
    prop: "风险编号",
    label: "风险编号",
    width: "120px",
  },
  {
    prop: "sourceStr",
    label: "漏洞来源",
    minWidth: "120px",
  },
  {
    prop: "handleStatusStr",
    label: "处理状态",
    width: "110px",
    slotName: "state",
  },
  {
    prop: "findTime",
    label: "发现时间",
    width: "190px",
  },
  {
    slotName: "done",
    label: "操作",
    width: "90px",
    fixed: "right",
  },
];
const flawLevelArr = ref([]);
const flawSourceArr = ref([]);
const networkAreaArr = ref([]);
// const flawHandleStatusArr = ref([]);
const fileTypeArr = ref([]);
const initDict = async () => {
  flawLevelArr.value = (await getDictList("flawLevel")) as [];
  flawSourceArr.value = (await getDictList("flawSource")) as [];
  networkAreaArr.value = (await getDictList("networkArea")) as [];
  // flawHandleStatusArr.value = (await getDictList("flawHandleStatus")) as [];
  fileTypeArr.value = (await getDictList("excelType")) as [];
};

//点击多选框选中的行的数据
let selectData = ref([]);
const serchColumns = reactive([
  {
    key: "level",
    type: "select",
    label: "风险等级",
    options: flawLevelArr,
  },
  {
    key: "ip",
    type: "text",
    label: "资产IP",
  },
  {
    key: "networkAreaCode",
    type: "select",
    label: "网络域",
    options: networkAreaArr,
  },
  {
    key: "port",
    type: "text",
    label: "端口",
  },
  {
    key: "name",
    type: "text",
    label: "风险名称",
  },
  {
    key: "source",
    type: "select",
    label: "漏洞来源",
    options: flawSourceArr,
  },
  // {
  //   key: "handleStatus",
  //   type: "select",
  //   label: "处理状态",
  //   options: flawHandleStatusArr,
  // },
  {
    key: "findTime",
    type: "date",
    label: "发现时间",
    valueFormat: "YYYY-MM-DD",
  },
]);
onMounted(() => {
  permissionsButtons.map((item) => {
    bottomData.set(item.menuId, item);
  });

  headerData(); //头部数据
  initData(); // 获取列表数据
  getButton();
  initDict(); //字典初始化
});
// 获取列表数据 start
const initData = (type?) => {
  if (type == "init") {
    serchformData.value.pageIndex = 1;
  }
  // 保存筛选条件
  if (type) {
    sessionStorage.setItem("YA_FORM_DATA", JSON.stringify(serchformData.value));
  }
  if (sessionStorage.getItem("YA_FORM_DATA")) {
    let obj = JSON.parse(sessionStorage.getItem("YA_FORM_DATA"));
    Object.keys(obj).forEach((item) => {
      serchformData.value[item] = obj[item];
    });
    if (obj.handleStatus) {
      num.value = obj.handleStatus * 1;
    }
  }
  let _data = JSON.parse(JSON.stringify(serchformData.value)) || {};
  _data.handleStatus = num.value;
  createVul(_data).then((res) => {
    const { code, data = {} } = res || {};
    if (code == 200) {
      tableData.value = data.records || [];
      total.value = data.total;
    }
  });
};

//获取头部数据
const headerData = function () {
  let params = { type: 1 };
  gapsStatistic(params).then((res) => {
    const { code, data = {} } = res || {};
    if (code == 200) {
      headerBlock.value.forEach((item) => {
        item.riskNum = data[item.riskName] || {};
      });
      // headerBlock.value[0].riskNum = data["待下发"] || {};
      // headerBlock.value[1].riskNum = data["待修复"] || {};
      // headerBlock.value[2].riskNum = data["已修复"] || {};
      // headerBlock.value[3].riskNum = data["已忽略"] || {};
    }
  });
};
// 重置
const reset = () => {
  initData("init");
};
// 让批量导出事件执行
const tableBtnClick = (btn, row) => {
  btn.eventName(row);
};
//选中的行的信息
const handleSelectionChange = function (val) {
  selectData.value = val;
};
// 获取列表数据end
let getButton = () => {
  if (bottomData.has(200016)) {
    leftButtons.value.push({
      custom: "dropdown",
      title: bottomData.get(200016).label,
      customData: [
        {
          name: "批量" + bottomData.get(200016).label,
          eventName: function () {
            batchExport("part");
          },
        },
        {
          name: "全部" + bottomData.get(200016).label,
          eventName: function () {
            batchExport("all");
          },
        },
      ],
    });
  }
};
//选择文件格式的弹窗是否要显示
const dialogVisible = ref(false);
//调接口时的参数
const exportData: any = ref({});
//导出事件
const batchExport = function (type) {
  if (tableData.value.length != 0) {
    if (type == "part") {
      if (selectData.value.length == 0) {
        yaMessage("请选择要批量导出的数据", "warning");
        return;
      } else {
        dialogProps.showDialog = true;
        formData.value.fileType = "";
        let selectedList = [];
        selectData.value.forEach((item) => {
          selectedList.push(item.id);
        });
        let selectIds = selectedList.toString();
        exportData.value.id = selectIds;
      }
    } else {
      dialogProps.showDialog = true;
      formData.value.fileType = "";
      exportData.value = JSON.parse(JSON.stringify(serchformData.value));
    }
  }
};
//导出接口
const exportEvent = function (params) {
  exportByIds(params).then((res) => {
    console.log(res);
    downLoadFile(res, "主机漏洞");
    clearSelect();
    yaMessage("导出成功", "success");
  });
};
const multipleTableRef = ref<InstanceType<typeof ElTable>>();
// 清空选择的值
const clearSelect = () => {
  multipleTableRef.value.$refs["ya-table"].$refs["ya-table"].$refs[
    "ya-table"
  ].clearSelection();
};
//弹窗 start
//弹窗规则
const rules = ref({
  fileType: [
    {
      required: true,
      message: "请选择文件格式",
      trigger: "blur",
    },
  ],
});
//填入的弹窗数据
const formData = ref({});
//弹窗的数据
let dialogForm = ref();
const formColumns = ref([
  {
    key: "fileType",
    type: "select",
    label: "选择格式",
    col: 24,
    options: fileTypeArr,
  },
]);
//弹窗是否显示
let dialogProps = reactive({
  showDialog: false,
  title: "",
  size: "",
});
//清空表单数据
let handleDialogOpen = () => {
  nextTick(() => {
    dialogForm.value.resetForm();
  });
};
//弹窗的取消事件
const handleCancel = function () {
  dialogProps.showDialog = false;
};
//弹窗点击确定的表单校验
const handleConfirm = function () {
  dialogForm.value.submitForm(dialogForm.value.ruleFormRef);
};
//弹窗的确定事件
const handleDialogEvent = function (params) {
  if (params.eventName == "errorSubmit") return;
  exportData.value.fileType = formData.value.fileType;
  exportEvent(exportData.value);
  dialogProps.showDialog = false;
};
// 分页
const page = ref(1);
const total = ref(0);
const pageSize = ref(20);
const sizeChange = function (val: number) {
  serchformData.value.pageSize = val;
  initData("page");
};

const currentChange = function (val: number) {
  serchformData.value.pageIndex = val;
  initData("page");
};
const trangle = function (num1) {
  num.value = num1;
  serchformData.value.handleStatus = serchformData.value ? String(num1) : num1;
  initData("status");
};
const goToDetail = function (val) {
  localStorage.setItem("YA_VUL_DATA", JSON.stringify(val));
  router.push({
    path: "./hostVulnerability/fdetail",
  });
};
</script>
<style lang="scss" scoped>
.ya-stateColor1 {
  color: #0095ff;
}
.ya-stateColor2 {
  color: #ec3f3f;
}
.ya-stateColor3 {
  color: #2fcb96;
}
.ya-stateColor4 {
  color: #f18301;
}
.ya-stateColor5 {
  color: #9b9ea1;
}
.el-select {
  width: 334px;
  height: 32px;
  margin-bottom: 24px;
  margin-left: 8px;
}
.select {
  color: #919396;
}
img {
  width: 18px;
  height: 18px;
  vertical-align: middle;
  margin-right: 3px;
}
.ya-type {
  margin-top: 5px;
}
.yaHeader {
  width: 100%;
  height: 140px;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  .ya-risk1,
  .ya-risk2,
  .ya-risk3,
  .ya-risk4 {
    width: 24%;
    box-shadow: 7px 11px 14px 0px rgba(0, 55, 110, 0.05);
    border-radius: 4px;
    position: relative;
    display: flex;
    justify-content: space-between;
    font-size: 14px;
    font-weight: 500;
    color: #ffffff;
    cursor: pointer;
    .ya-risk-left {
      width: 30%;
      box-shadow: 0px 0px 8px 0px rgba(0, 55, 110, 0.1);
      border-radius: 4px;
      backdrop-filter: blur(1px);
      display: flex;
      justify-content: center;
      align-items: center;
      margin: 14px 0px 16px 15px;
    }
    .ya-risk-center {
      flex: 1;
      text-align: center;
      line-height: 22px;
      margin-top: 39px;
    }
    .ya-risk-right {
      width: 33.5%;
      line-height: 22px;
      padding: 24px 0px;
      box-sizing: border-box;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      .ya-risk-right-item {
        display: flex;
        align-items: center;
      }
      .ya-risk-right-item:not(:first-child) {
        margin-top: 10px;
        img {
          width: 18px;
          height: 18px;
          vertical-align: middle;
          margin-right: 6px;
        }
      }
    }
  }
  .ya-risk1 {
    background: linear-gradient(204deg, #1bbfe8 0%, #30a0f0 100%);
    .ya-risk-left {
      img {
        width: 48px;
        height: 50px;
      }
    }
  }
  .ya-risk2 {
    background: linear-gradient(233deg, #ff7c7c 0%, #c55492 100%);
    .ya-risk-left {
      img {
        width: 58px;
        height: 52px;
      }
    }
  }
  .ya-risk3 {
    background: linear-gradient(24deg, #4ce298 0%, #29c696 100%);
    .ya-risk-left {
      img {
        width: 48px;
        height: 50px;
      }
    }
  }
  .ya-risk4 {
    background: linear-gradient(212deg, #739dbf 0%, #7a94a7 100%);
    .ya-risk-left {
      img {
        width: 48px;
        height: 50px;
      }
    }
  }
}
.ya-trangle1 {
  border: 8px solid #1bbfe8;
}
.ya-trangle2 {
  border: 8px solid #ff7c7c;
}
.ya-trangle3 {
  border: 8px solid #4ce298;
}
.ya-trangle4 {
  border: 8px solid #739dbf;
}
.ya-trangle {
  width: 0;
  height: 0;
  border-top-color: transparent;
  border-left-color: transparent;
  border-right-color: transparent;
  position: absolute;
  bottom: -20px;
  left: 50%;
  transform: translateX(-50%);
}
.ya-hand {
  cursor: pointer;
}
</style>
