<!--
 * @Description: 恶意网站分析
 * @Author: xuch
 * @Date: 2022-08-25 15:24:53
 * @LastEditTime: 2023-08-31 11:35:17
 * @LastEditors: 曹文丽
-->
<script lang="ts" setup>
import { ref, reactive, onMounted, watch, unref } from "vue";
import CommonCardVue from "../../../components/CommonCard/CommonCard.vue";
import LineChart from "../../../components/chart/LineChart/LineChart.vue";
import CircularDiagram from "../../../components/chart/CircularDiagram/CircularDiagram.vue";
import RoundTab from "../../../components/RoundTab/RoundTab.vue";
import { dateSwitchOptions } from "../../../settings";
import { bigNumberTransform } from "../../../utils/utils";
import { ElMessage } from "element-plus";
import {
  getList,
  exportRequest,
  getCityList,
  getUserList,
} from "../../../api/monitoring/website/maliciousWebAnalysis";
import { downLoadFile, deepCopy } from "../../../utils/utils";
import lineCircle2 from "../../../assets/image/screen/threat-event/line-2.png";
import { getThemeColor } from "../../../components/chart/options/theme";
onMounted(() => {
  init();
});

// 分页参数
const page = ref(1);
const total = ref(0);
const size = ref(20);

/**
 * @description: 初始化方法
 * @param {*}
 * @return {*}
 * @author: xuch
 */
const init = () => {
  getTableData("init", "loading");
  getLeftButtons();
  getLineChartData();
  initAgrement();
};

/**
 * @description: 获取按钮
 * @param {*}
 * @return {*}
 * @author: xuch
 */
const buttons = ref([]) as any;
const getLeftButtons = () => {
  buttons.value = [
    {
      plain: true,
      text: "批量导出",
    },
  ];
};

// 查询参数
const queryColumns = reactive([
  {
    key: "time",
    type: "daterange",
    label: "时间范围",
    col: 6,
    valueFormat: "YYYY-MM-DD",
    startPlaceholder: "开始时间",
    endPlaceholder: "结束时间",
  },
  {
    key: "url",
    type: "input",
    label: "恶意网站域名",
    placeholder: "请输入恶意网站域名",
    col: 6,
  },
  {
    key: "websiteIp",
    type: "input",
    label: "网站IP",
    placeholder: "请输入网站IP",
    col: 6,
  },
  {
    key: "websiteLocation",
    type: "input",
    label: "网站位置",
    placeholder: "请输入网站位置",
    col: 6,
  },
]);
const queryFormData = reactive({
  time: [],
  url: "",
  websiteIp: "",
  websiteLocation: "",
  visitCount: "",
});

// 表格数据
const tableData = ref([]) as any;
const tableColumn: any[] = [
  {
    type: "selection",
    width: "65px",
  },
  {
    prop: "discoveryTime",
    label: "发现时间",
    width: "190px",
    fixed: "left",
  },
  {
    prop: "url",
    label: "恶意网站域名",
    minWidth: "130px",
  },
  {
    prop: "websiteIp",
    label: "网站IP",
    minWidth: "130px",
  },
  {
    prop: "operator",
    label: "运营商",
    minWidth: "100px",
  },
  // {
  //   prop: "enterprise",
  //   label: "单位",
  //   minWidth: "100px",
  // },
  {
    prop: "websiteLocation",
    label: "网站位置",
    minWidth: "100px",
  },
  {
    prop: "userCount",
    label: "IP数量（个）",
    minWidth: "100px",
  },
  {
    prop: "visitCount",
    label: "用户访问次数（次）",
    fixed: "right",
    minWidth: "100px",
  },
];

/**
 * @description: 表格多选操作
 * @param {*}
 * @return {*}
 * @author: xuch
 */
const selectData = ref([]);
const handleSelect = (data) => {
  selectData.value = data;
};

/**
 * @description: 查询操作
 * @param {*}
 * @return {*}
 * @author: xuch
 */
const search = () => {
  getTableData("init");
};

/**
 * @description: 重置操作
 * @param {*}
 * @return {*}
 * @author: xuch
 */
const reset = () => {
  console.log("调用 reset");
  getTableData("init");
};

/**
 * @description: 获取表格数据
 * @param {*}
 * @return {*}
 * @author: xuch
 */
const getTableData = async (type, loading?) => {
  console.log("调用 search", type);
  let dataObj = deepCopy(queryFormData);
  if (type === "init") {
    page.value = 1;
  }
  if (queryFormData.time) {
    if (queryFormData.time.length > 0) {
      dataObj.startTime = queryFormData.time[0] + " 00:00:00";
      dataObj.endTime = queryFormData.time[1] + " 23:59:59";
    }
    delete dataObj.time;
  }
  try {
    const params = {
      pageNum: page.value,
      pageSize: size.value,
      ...dataObj,
    };
    params.yaLoading = loading;
    const res = await getList(params);
    if (res.code !== 200) return;
    if (res.data) {
      tableData.value = res.data.rows || [];
      total.value = res.data.total;
    }
  } catch (error) {
    console.log(error);
  }
};

/**
 * @description: 页面容量切换
 * @param {*}
 * @return {*}
 * @author: xuch
 */
const sizeChange = function (val: number) {
  size.value = val;
  page.value = 1;
  getTableData("page");
};

/**
 * @description: 分页切换
 * @param {*}
 * @return {*}
 * @author: xuch
 */
const currentChange = function (val: number) {
  page.value = val;
  getTableData("page");
};

/**
 * @description: 批量 / 全部 导出
 * @param {*} type batch | all
 * @return {*}
 * @author: xuch
 */
const handleExport = async (type) => {
  console.log("调用 handleExport", type);

  if (selectData.value.length === 0) {
    ElMessage.warning("请选择要批量导出的数据");
    return;
  }
  // @ts-ignore
  const data = selectData.value.map((item) => item.id);

  handleExportRequest(data);
};

/**
 * @description: 批量 / 全部 导出请求
 * @param {*} data
 * @return {*}
 * @author: xuch
 */
const handleExportRequest = async (data) => {
  console.log(data);
  try {
    const params = {
      ids: data,
    };
    const res = await exportRequest(params);
    if (res) {
      downLoadFile(res, `恶意网站`);
      getTableData("");
    }
  } catch (error) {
    console.log(error);
  }
};
const lineChartData = ref([]) as any;
const linexAxisData = ref([]) as any;
const getLineChartData = async () => {
  linexAxisData.value = [];
  lineChartData.value = [];
  const res = await getUserList({
    type: unref(currentTab),
  });
  const { code, data } = res || {};
  if (code === 200 && data) {
    let chartData = [
      {
        name: "IP数量",
        data: res.data.userSum ? res.data.userSum.split(",") : [],
      },
    ] as any;
    let xAxisData = res.data.date ? res.data.date.split(",") : [];
    linexAxisData.value = xAxisData || [];
    lineChartData.value = chartData;
  }
};

const legendFormatter = (name) => {
  const findItem = unref(chartData).findIndex((item) => item.name === name);
  const _item = unref(chartData)[findItem] as any;
  const _name = `{title|${name}}`;
  const percentage = `{subtitle|${bigNumberTransform(_item.value)}}`;
  return _name + percentage;
};
const currentTab = ref(1);
const options = ref(dateSwitchOptions);
const chartData = ref([]) as any;
const xInterval = ref(1);
watch(currentTab, () => {
  if (unref(currentTab) == 1) {
    xInterval.value = 1;
  } else if (unref(currentTab) == 3) {
    xInterval.value = 3;
  } else {
    xInterval.value = 0;
  }
  initAgrement();
  getLineChartData();
});
const initAgrement = async () => {
  const params = {
    type: unref(currentTab),
  };
  const res = await getCityList(params);
  if (res.code === 200 && res.data?.length) {
    chartData.value = res.data.map((item) => {
      return {
        unit: item.unit,
        name: item.city,
        value: item.userSum,
      };
    });
  } else {
    chartData.value = [];
  }
};

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">${bigNumberTransform(
    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:4px;position:relative"></div>
          <div >
            <div class="rose-linechart-tooltip-subtitle">${name}</div>
            <div class="rose-linechart-tooltip-content">
              ${_resHtml}
            </div>
          </div>
        </div>
      </div>`;
};
</script>

<template>
  <div>
    <div class="top-content">
      <RoundTab class="custom-round-tab" v-model="currentTab" :options="options"></RoundTab>
      <CommonCardVue class="custom-row-item">
        <div class="ya-content">
          <CommonCardVue title="恶意网站访问IP数量统计">
            <LineChart :xInterval="xInterval" :chartData="lineChartData" :xAxisData="linexAxisData" :showSymbol="true"
              title="单位：个" :areaGradientColor="getThemeColor().lineGradient[0]" />
          </CommonCardVue>
          <div class="ya-line"></div>
          <CommonCardVue title="访问IP地市分布TOP10" unit="个">
            <CircularDiagram v-if="chartData.length" :chartData="chartData" chartClass="ya-circle-chart" legendLeft="40%"
              legendTop="auto" :pieCenter="['20%', '50%']" :legendFormatter="legendFormatter" />
            <ya-empty v-else></ya-empty>
          </CommonCardVue>
        </div>
      </CommonCardVue>
    </div>
    <div>
      <YaPageContent :formData="queryFormData" :formColumns="queryColumns" :tableData="tableData"
        templateHeight="calc(100vh - 400px)" :tableColumns="tableColumn" searchLabelWidth="100px" @search="search"
        @reset="reset" :currentPage="page" :pageSize="size" :total="total" @sizeChange="sizeChange"
        @selectionChange="handleSelect" @currentChange="currentChange" :leftButtons="buttons"
        @tableBtnClick="handleExport">
      </YaPageContent>
    </div>
  </div>
</template>

<style scoped lang="scss">
.mt-15 {
  margin-right: 15px;
}

::v-deep .custom-circle-legend {
  max-height: 160px;
}

.top-content {
  // background: #fff;
  border-radius: 4px;
  height: 383px;
  margin-bottom: 16px;
  display: flex;
  width: 100%;
  position: relative;

  .custom-round-tab {
    position: absolute;
    width: calc(100% - 32px);
    margin: 9px 16px 0;

    &::before {
      position: absolute;
      bottom: -16px;
      content: "";
      height: 1px;
      width: 100%;
      background-color: rgba(84, 229, 252, 0.15);
    }
  }

  .top-content-item {
    padding-top: 58px;
    box-sizing: border-box;
    flex: 1;
  }

  .ya-content {
    display: flex;
    height: 100%;

    &>.ya-card:nth-child(1) {
      margin-right: 20px;
    }

    &>.ya-card:nth-last-child(1) {
      margin-left: 20px;
    }

    .ya-line {
      width: 2px;
      background: linear-gradient(180deg,
          rgba(140, 236, 255, 0) 0%,
          rgba(140, 236, 255, 0.64) 53%,
          rgba(140, 236, 255, 0) 100%);
    }

    .ya-card {
      padding: 0;
      border: none;
      background: transparent;
      box-shadow: none;
    }
  }

  .custom-row-item {
    height: 100%;
    width: 100%;
    padding-top: 74px;
    box-sizing: border-box;
  }
}

::v-deep .ya-circle-chart {
  width: 100% !important;
}

::v-deep .chart-flex .custom-circle-legend-item:last-child {
  margin-bottom: 12px;
}
</style>
