<!--
 * @Author: changjun
 * @FilePath: /yuan-qingdao-zld-browser/src/views/monitoring/attackEvent/AbnormalSampleDetail.vue
 * @Date: 2022-09-15 15:06:37
 * @Description: 
 * @LastEditTime: 2023-08-31 15:11:05
 * @LastEditors: 曹文丽
-->
<script setup lang="ts">
import { onMounted, watch, ref, unref, reactive } from 'vue'
import { ElScrollbar } from "element-plus";
import FlyLineWorldMap from "../../../components/chart/map/FlyLineWorldMap.vue";
import CommonCard from "../../../components/CommonCard/CommonCard.vue";
import CircularDiagram from "../../../components/chart/CircularDiagram/CircularDiagram.vue";
import { getContryItemIcon } from "../../../assets/js/countryFlagBase64";
import { useRouteQuery } from "@vueuse/router";
import { useGetChartData } from "../../../components/chart/logic";

const currentIp = useRouteQuery("ip");
const startTime = useRouteQuery("startTime");
const endTime = useRouteQuery("endTime");
const sumDate = useRouteQuery("sumDate");

const tabs = [
  {
    title: "攻击者流量TOP10",
    value: 1,
  },
  {
    title: "攻击者地域流量TOP10 ",
    value: 2,
  },
];
const currentTab = ref(1);
/**
 * @description: 概况显示内容
 */
const surveyDetail = ref([
  {
    name: "被攻击流量",
    key: "attackData",
    value: "",
  },
  {
    name: "连接峰速（每秒）",
    key: "linkPeak",
    value: "",
  },
  {
    name: "攻击IP数",
    key: "attackIpCount",
    value: "",
  },
  {
    name: "攻击源IP的熵",
    key: "attackIpEntropy",
    value: "",
  },
  {
    name: "并发连接数",
    key: "linkCount",
    value: "",
  },
  {
    name: "攻击源端口的熵",
    key: "attackPortEntropy",
    value: "",
  },
  {
    name: "带宽峰值（Mbps）",
    key: "bandwidthPeak",
    value: "",
  },
  // {
  //   name: '目的IP的熵',
  //   key: 'attackIpEntropy',
  //   value: ''
  // },
  {
    name: "运营商",
    key: "attackedOperator",
    value: "",
  },
  {
    name: "单位",
    key: "attackedEnterprise",
    value: "",
  },
]);

/**
 * @description: 获取详情概括
 */
const getSurvey = async () => {
  const params = {
    goalIp: currentIp.value,
    startTime: startTime.value,
    endTime: endTime.value,
  };
  const res = await useGetChartData(
    "/networkSafeDetect/ddosAttackEvent/abnormalFeaturesSample/queryParticulars",
    (res) => res,
    params
  );
  if (res) {
    console.log(typeof 0);
    surveyDetail.value = surveyDetail.value.map((item) => {
      item.value =
        typeof res[item.key] == "number"
          ? res[item.key].toString()
          : res[item.key];
      return item;
    });
    console.log("surveyDetail", surveyDetail.value);
  }
};

const chartData = ref([]) as any;
const chartApi =
  "/networkSafeDetect/ddosAttackEvent/flowRecall/queryAttackSourceLocation";
const targetCoordinates = [117.0056, 36.6670723];

/**
 * @description: 获取攻击流量分布
 */
const getMapChartData = async () => {
  const params = {
    goalIp: unref(currentIp),
    startTime: unref(startTime),
    endTime: unref(endTime),
    sumDate: unref(sumDate),
  };
  const res = await useGetChartData(chartApi, (res) => res, params);
  if (!res) return;
  chartData.value = res.map((item) => {
    item.state = item.attackCountry;
    return item;
  });
};

let trafficRatioChartData = ref([]) as any;
/**
 * @description: 处理返回数据
 */
const handleTraaficResData = (res) => {
  console.log(res, "---");
  let arr = [];
  arr.push({
    name: res.protocol,
    value: res.attackData,
    valueFormat: res.attackData,
    percent: res.ratio,
  });
  return arr;
  // return res.map(item => {
  //   return {
  //     ...item,
  //     name: item.agreementType,
  //     value: item.agreementPercentage.replace('%', ''),
  //     valueFormat: item.agreementPercentage
  //   }
  // })
};
/**
 * @description: 获取流量协议占比
 */
const getTrafficChartData = async () => {
  const params = {
    goalIp: currentIp.value,
    startTime: unref(startTime),
    endTime: unref(endTime),
    sumData: unref(sumDate),
  };
  const res = await useGetChartData(
    "/networkSafeDetect/ddosAttackEvent/abnormalFeaturesSample/queryProtocolList",
    handleTraaficResData,
    params
  );
  trafficRatioChartData.value = Object.keys(res).length > 0 ? res : [];
};
/**
 * @description: 攻击信息列表表格
 */
const attackTableColumn = [
  {
    prop: "attackIp",
    label: "攻击IP",
    width: 160,
  },
  {
    prop: "attackOperator",
    label: "运营商",
  },
  // {
  //   prop: "attackEnterprise",
  //   label: "单位",
  // },
  {
    prop: "address",
    label: "所属地",
    slotName: "countries",
    minWidth: 200,
  },
  {
    prop: "attackData",
    label: "攻击流量",
    minWidth: 90,
  },
  {
    prop: "startTime",
    label: "开始时间",
    width: 190,
  },
  {
    prop: "endTime",
    label: "结束时间",
    width: 190,
  },
  {
    prop: "attackProportion",
    label: "流量占比",
    minWidth: 120,
  },
];
const attackTableData = ref([]) as any;
const attackPage = ref(1);
const attackPageSize = ref(10);
const attackTotal = ref(0);
const attackApi =
  "/networkSafeDetect/ddosAttackEvent/flowRecall/queryAttackInformation";
/**
 * @description: 切换分页
 */
const handleAttackPageChange = (val: number) => {
  attackPage.value = val;
  getTableData(1, false);
};
/**
 * @description: 分页
 */
const handleAttackPageSizeChange = (val: number) => {
  attackPage.value = 1;
  attackPageSize.value = val;
  getTableData(1, false);
};

const attackSourceApi =
  "/networkSafeDetect/ddosAttackEvent/flowRecall/queryAttackSourceLocation";
const attackSourceTableData = ref([]) as any;
const attackSourceTableColumn = [
  {
    prop: "placeOrigin",
    label: "所属地",
    slotName: "countries",
    minWidth: 200,
  },
  {
    prop: "attackData",
    label: "攻击流量",
    minWidth: 90,
  },
  {
    prop: "attackProportion",
    label: "流量占比",
    minWidth: 80,
  },
];
const attackSourcePage = ref(1);
const attackSourceTotal = ref(0);
const attackSourcePageSize = ref(10);
/**
 * @description: 切换分页
 */
const handleAttackSourcePageChange = (val: number) => {
  attackSourcePage.value = val;
  getTableData(2, false);
};
/**
 * @description: 分页
 */
const handleAttackSourcePageSizeChange = (val: number) => {
  attackSourcePage.value = 1;
  attackSourcePageSize.value = val;
  getTableData(2, false);
};
/**
 * @description: 处理返回数据
 */
const handleResData = (list) => {
  return list.map((item, index) => {
    return {
      ...item,
      // serialNumber: (attackPage.value - 1) * 10 + (index + 1), // demo
      countryIcon: getContryItemIcon("name", item.attackCountry),
    };
  });
};
/**
 * @description: 获取表格数据
 */
const getTableData = async (type, init) => {
  const isAttack = type === 1;
  const _api = isAttack ? attackApi : attackSourceApi;
  if (init) {
    if (isAttack) {
      attackPage.value = 1;
      attackPageSize.value = 10;
    } else {
      attackSourcePage.value = 1;
      attackPageSize.value = 10;
    }
  }
  const params = {
    // pageNum: isAttack ? unref(attackPage) : unref(attackSourcePage),
    // pageSize: isAttack ? unref(attackPageSize) : unref(attackSourcePageSize),
    goalIp: unref(currentIp),
    startTime: unref(startTime),
    endTime: unref(endTime),
    sumDate: unref(sumDate),
  };
  const res = await useGetChartData(_api, (res) => res, params);
  if (res) {
    if (isAttack) {
      // attackTotal.value = res.total
      attackTableData.value = handleResData(res);
    } else {
      // attackSourceTotal.value = res.total
      attackSourceTableData.value = handleResData(res);
    }
  }
};
/**
 * @description: 鼠标经过地图提示
 */
const tooltipFormatter = function (params) {
  const { attackData = "", attackProportion = "", unit = "" } = params.data;
  return `<div class="light-map-tip-box">
      <div class="light-map-tip-box-content">
        <div class="light-map-tip-box-item">
          <div class="light-map-tip-box-label">攻击流量</div>
          <div class="light-map-tip-box-value">${attackData || 0}${unit}</div>
        </div>
        <div class="light-map-tip-box-item">
          <div class="light-map-tip-box-label">流量占比</div>
          <div class="light-map-tip-box-value">${attackProportion || 0}</div>
        </div>
      </div>
      
    </div>`;
};
/**
 * @description: 监听tab变化
 */
watch(currentTab, (val) => {
  const isAttack = val === 1;
  getTableData(isAttack ? 1 : 2, true);
});

/**
 * @description: 初始化执行
 */
const init = () => {
  getSurvey();
  getTrafficChartData();
  getMapChartData();
  getTableData(1, true);
};
// const tooltipValueFormatter = (val) => {
//   return val;
// };
const tooltipValueFormatter = (params) => {
  let _resHtml = "";
  const { color, seriesName, value, name, percentage } = params;
  _resHtml += `<div class="rose-linechart-tooltip-content-item">
              <div class="rose-linechart-tooltip-content-item-value">${value}
              </div>
          </div>`;
  return `<div class="rose-linechart-tooltip">
        <div style="display: flex;">
          <div class="rose-linechart-tooltip-content-item-icon" style="background: ${color};top:6px;position:relative;margin-right: 6px"></div>
          <div >
            <div class="rose-linechart-tooltip-subtitle">${name}</div>
            <div class="rose-linechart-tooltip-content">
              ${_resHtml}
            </div>
          </div>  
        </div>
      </div>`;
};
onMounted(() => {
  init();
});
const pageContentDetail = reactive({
  value: "目的IP：" + currentIp.value,
});
</script>

<template>
  <div class="abnormal-sample-detail">
    <ElScrollbar>
      <div class="top-detail ya-bg-colors">
        <div class="title-box-ip ya-border-color">
          <YaContentDetail class="page-detail-title" :obj="pageContentDetail" />
        </div>
        <div class="bottom-box">
          <div class="left-info ya-border-color">
            <div class="title-box">
              <div class="title prefix ya-primary-text">概况</div>
            </div>
            <div class="content-box">
              <div class="content-box-item" v-for="(desci, index) in surveyDetail" :key="index">
                <div class="content-box-item-label ya-regular-text">
                  {{ desci.name }}
                </div>
                <div class="content-box-item-value ya-primary-text">
                  {{ desci.value || "-" }}
                </div>
              </div>
            </div>
          </div>
          <div class="right-chart">
            <div class="title-box">
              <div class="title prefix ya-primary-text">流量协议占比</div>
            </div>
            <div v-if="trafficRatioChartData.length" class="chart-wrap-box">
              <CircularDiagram legendTop="10px" :pieCenter="['20%', '50%']" :chartData="trafficRatioChartData"
                name="流量协议占比" />
            </div>
            <ya-empty v-else></ya-empty>
          </div>
        </div>
      </div>
      <CommonCard title="攻击流量分布" class="mt-16 center-map-box">
        <FlyLineWorldMap :tooltipFormatter="tooltipFormatter" :chartData="chartData"
          :targetCoordinates="targetCoordinates" />
      </CommonCard>
      <div class="bottom-table mt-16 ya-bg-colors ya-border-color">
        <YaTabs class="custom-common-tabs" :tabs="tabs" v-model="currentTab"></YaTabs>
        <div class="bottom-table-box" v-if="currentTab === 1">
          <YaTable class="custom-table-attack" :data="attackTableData" :column="attackTableColumn">
            <template #countries="{ item }">
              <div class="countries-table-column">
                <img :src="item.countryIcon" alt="" class="country-icon" />
                <div class="countries-name ya-primary-text">
                  {{ item.address }}
                </div>
              </div>
            </template>
          </YaTable>

          <!-- <div class="page-box">
            <YaPagination :page-sizes="[10, 20, 30, 40, 50, 100]" :currentPage="attackPage" :pageSize="attackPageSize"
              @sizeChange="handleAttackPageSizeChange" @currentChange="handleAttackPageChange" small
              :total="attackTotal">
            </YaPagination>
          </div> -->
        </div>

        <div class="bottom-table-box" v-if="currentTab === 2">
          <YaTable class="custom-table-attack" :data="attackSourceTableData" :column="attackSourceTableColumn">
            <template #countries="{ item }">
              <div class="countries-table-column">
                <img :src="item.countryIcon" alt="" class="country-icon" />
                <div class="countries-name ya-primary-text">
                  {{ item.address }}
                </div>
              </div>
            </template>
          </YaTable>

          <!-- <div class="page-box">
            <YaPagination :page-sizes="[10, 20, 30, 40, 50, 100]" :currentPage="attackSourcePage"
              :pageSize="attackSourcePageSize" @sizeChange="handleAttackSourcePageSizeChange"
              @currentChange="handleAttackSourcePageChange" small :total="attackSourceTotal">
            </YaPagination>
          </div> -->
        </div>
      </div>
    </ElScrollbar>
  </div>
</template>

<style lang="scss" scoped>
// .ya-page-container-back-title {
//   font-size: 30px;
//   font-weight: bold;
//   color: rgba(0,0,0,0.65);
// }
.abnormal-sample-detail {
  width: 100%;
  height: calc(100vh - 56px - 40px - 12px - 12px);

  .top-detail {
    width: 100%;
    height: 318px;
    border-radius: 4px;
    padding: 16px 24px;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    padding-top: 10px;

    .title-box-ip {
      width: 100%;
      height: 62px;
      font-size: 30px;
      font-weight: 600;
      color: rgba(0, 0, 0, 0.65);
      // box-shadow: inset 0px -1px 0px 0px #EBEBEB;
      border-bottom: 1px solid #ebebeb;
      line-height: 55px;
    }

    .bottom-box {
      display: flex;
      margin-top: 24px;
      height: 214px;

      .left-info {
        flex: 1;
        border-right: 1px solid #d8d8d8;

        .content-box {
          display: flex;
          flex-wrap: wrap;

          .content-box-item {
            display: flex;
            margin-top: 14px;
            width: calc((100% - 14px) / 2);

            .content-box-item-label {
              width: 124px;
              font-size: 14px;
              font-weight: 400;
              color: rgba(0, 0, 0, 0.4);
              text-align: left;
              flex-shrink: 0;
            }

            .content-box-item-value {
              flex: 1;
              font-size: 14px;
              font-weight: 400;
              color: rgba(0, 0, 0, 0.65);
              margin-left: 8px;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
          }

          .content-box-item:nth-child(2n) {
            margin-left: 14px;
          }
        }
      }

      .right-chart {
        flex: 1;
        padding-left: 40px;

        .chart-wrap-box {
          width: 100%;
          height: 170px;
          display: flex;
          position: relative;
        }
      }
    }
  }

  .mt-16 {
    margin-top: 16px;
  }

  .center-map-box {
    width: 100%;
    height: 704px;
  }

  .bottom-table {
    width: 100%;
    height: 580px;
    border-radius: 4px;
    padding: 10px 24px 16px 24px;
    box-sizing: border-box;
    border: 1px solid #fff;

    .bottom-table-box {
      margin-top: 16px;
      display: flex;
      flex-direction: column;

      .page-box {
        margin-top: 16px;
        display: flex;
        flex-direction: row-reverse;
      }
    }
  }

  .empty-block {
    width: 100%;
    height: 72px;
  }

  .prefix {
    position: relative;
  }

  .prefix::after {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    margin: auto 0;
    width: 3px;
    height: 14px;
    background: #0095ff;
  }

  .title-box {
    min-width: 0;
    box-sizing: border-box;
  }

  .title {
    font-size: 14px;
    font-weight: 600;
    color: rgba(0, 0, 0, 0.65);
    padding-left: 11px;
    box-sizing: border-box;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}

.countries-table-column {
  .country-icon {
    width: 18px;
    height: 14px;
    margin-right: 4px;
    display: inline-block;
  }

  .countries-name {
    font-size: 14px;
    font-weight: 400;
    color: rgba(0, 0, 0, 0.65);
    display: inline-block;
  }
}

:deep(.custom-table-attack) {
  .el-table__body-wrapper {
    height: 440px;
  }
}

::v-deep .custom-circle-legend {
  top: 45% !important;
}
</style>
