<!--
 * @Author: changjun
 * @FilePath: /qingdao-safety-product/src/views/screen/components/TrendChangeStatistics.vue
 * @Date: 2022-07-27 15:41:56
 * @Description: 趋势变化统计组件
 * @LastEditTime: 2023-09-01 15:25:37
 * @LastEditors: 曹文丽
-->
<script setup lang="ts">
import { ref, reactive, watch, onMounted } from 'vue'
import TabImgBig from '../../../assets/image/bigScreenTabTitle.png';
import TabImgActive from '../../../assets/image/tabImgActive.png';
import TabImgDefault from '../../../assets/image/tabImgDefault.png';
import RoundTab from './RoundTab.vue';
import { TOOLTIP_IMG } from '../constants';
import * as echarts from 'echarts';
import { RiskyAssetsData, VulnerabilityRiskData, RiskyAssetsDataMonth, RiskyAssetsDataYear, VulnerabilityRiskMonth, VulnerabilityRiskYear } from '../fakeData';

const handleLargeNumber = (num) => {
  return Number(num) > 10000 ? (Number(num) / 10000).toFixed(1) + '万' : num;
};

const riskLegend = ['高危资产', '中危资产', '低危资产']; // 风险资产趋势变化图例
const assetLegend = ['高危漏洞', '中危漏洞', '低危漏洞']; // 漏洞趋势变化图例

const legend = [riskLegend, assetLegend];

const riskLegendColor = ['#C8635C', '#A8A03C', '#327FA0'];
const assetLegendColor = ['#C8635C', '#A8A03C', '#327FA0'];
const legendColor = [riskLegendColor, assetLegendColor]; // 风险趋势图例颜色

const riskLineColor = ['#C8635C', '#A8A03C', '#327FA0'];
const assetLineColor = ['#C8635C', '#A8A03C', '#327FA0'];
const lineColor = [riskLineColor, assetLineColor]; // 图表线条颜色

const riskGradientStart = ['rgba(237, 13, 59, .3)', 'rgba(238, 168, 16, .3)', 'rgba(2, 217, 215, .3)'];
const assetGradientStart = ['rgba(2, 217, 215, .3)', 'rgba(238, 168, 16, .3)', 'rgba(237, 13, 59, .3)'];
const gradientStart = [riskGradientStart, assetGradientStart]; // 渐变色 顶部

const riskGradientEnd = ['rgba(227, 87, 89, .05)', 'rgba(238, 168, 16, .05)', 'rgba(2, 217, 215, .05)'];
const assetGradientEnd = ['rgba(2, 217, 215, .05)', 'rgba(238, 168, 16, .05)', 'rgba(227, 87, 89, .05)'];
const gradientEnd = [riskGradientEnd, assetGradientEnd]; // 渐变色 底部

const navs = [
  { name: '风险资产趋势变化', value: 1 },
  { name: '漏洞趋势变化', value: 2 }
];

const activateId = ref(1);
const dateRef = ref(1);

const handleClickNav = (nav) => {
  activateId.value = nav.value;
};

const chartOption = reactive({
  grid: {
    top: '20%',
    left: '4%',
    right: '4%',
    bottom: '20%'
  },
  tooltip: {
    trigger: 'axis',
    position: function (point, params, dom, rect, size) {
      // 鼠标坐标和提示框位置的参考坐标系是：以echarts 容器的左上角那一点为原点，x轴向右，y轴向下
      // 提示框位置
      var x = 0; // x坐标位置
      var y = 0; // y坐标位置

      // 当前鼠标位置
      var pointX = point[0];
      var pointY = point[1];

      // echarts 容器大小
      // var viewWidth = size.viewSize[0];
      // var viewHeight = size.viewSize[1];

      // 提示框大小
      var boxWidth = 97;
      var boxHeight = 105;

      // boxWidth > pointX 说明鼠标左边放不下提示框
      if (boxWidth > pointX) {
        x = pointX + 5; // 此处需要判断 (pointX+5+boxWidth) < size.viewSize[0]
      } else {
        // 左边放的下
        x = pointX - boxWidth;
      }

      // boxHeight > pointY 说明鼠标上边放不下提示框
      if (boxHeight > pointY) {
        y = 5;
      } else {
        // 上边放得下
        y = pointY - boxHeight;
      }

      return [x, y];
    },
    axisPointer: { lineStyle: { color: 'rgba(198, 209, 219, .6)' } },
    show: true,
    backgroundColor: 'rgba(49,120,160,0.7500)',
    extraCssText: 'z-index: 9;box-shadow: 3px 4px 9px 0px rgba(69,171,214,0.3500);',
    appendToBody: false,
    borderColor: '#48B3E0',
    textStyle: {
      fontSize: '12',
      color: '#fff'
    },
    formatter: (params) => {
      let dataStr = `<div>`;
      let timeStr = `<span>${params[0].name}</span>`
      let totalCount = params.reduce((total, item) => {
        return total + Number(item.data);
      }, 0);
      let totalCountStr = `<div style="margin-bottom: 4px;">风险资产总数 ${totalCount}</div>`
      dataStr += timeStr;
      dataStr += totalCountStr;
      params.forEach(item => {
        dataStr += `
        <div style="margin: 4px 0;">
          <div style="display: inline-block;width: 6px;height: 6px;border-radius: 50%;background-color: ${item.color};"></div>
            <span>${item.seriesName}</span>
            <span style="float:right;margin-left:20px;">${item.data}</span>
          </div>
        `;
      });
      dataStr += `</div>`;
      return dataStr;
    }
  },
  legend: {
    top: '6%', // 距离容器上边界的距离
    right: '5%', // 距离容器右边界的距离
    itemWidth: 16, // 图例宽度
    itemHeight: 10, // 图例高度
    itemGap: 13, // 图例间距
    data: [], // 图例数据和图例颜色的对应关系
    // 图例文字的样式
    textStyle: {
      fontSize: 12,
      fontWeight: 400,
      fontFamily: 'Bold',
      color: function (params) { }
    }
  },
  xAxis: [
    {
      data: [],
      axisLabel: {
        // 坐标轴文本标签
        fontSize: 12,
        fontFamily: 'Regular',
        fontWeight: 400,
        color: 'rgba(198, 209, 219, .6)',
        interval: 0 // 设置为0，表示全部显示，1表示隔一个显示，依次类推
      },
      axisTick: { show: false }, // 坐标轴刻度线
      axisLine: { show: true, color: 'rgba(25, 33, 46, .3)' }, // 坐标轴轴线
      boundaryGap: false // 设置为true，表示两边留白，为false表示两边不留白
    }
  ],
  yAxis: [
    {
      type: 'value',
      axisLabel: {
        fontSize: 12,
        fontFamily: 'Regular',
        fontWeight: 400,
        color: 'rgba(198, 209, 219, .6)'
      },
      splitLine: {
        // 坐标轴分割线
        show: true,
        lineStyle: { color: 'rgba(204, 204, 204, .35)', type: 'dashed' } // 分割线颜色
      },
      axisLine: {
        show: true,
        lineStyle: { color: 'rgba(25, 33, 46, .3)' }
      }
    }
  ]
});

const getDefaultSeries = () => {
  return [
    {
      name: '',
      type: 'line',
      showSymbol: false, // 是否显示拐点
      symbol: 'circle',
      symbolSize: 9, // 拐点大小
      data: [],
      itemStyle: { color: '' }, // 图例颜色
      lineStyle: { width: 1, color: '' }, // 线条颜色
      areaStyle: {
        // 区域填充颜色
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: '' }, // 渐变色开始颜色
          { offset: 1, color: '' } // 渐变色结束颜色
        ])
      }
    },
    {
      name: '',
      type: 'line',
      showSymbol: false,
      symbol: 'circle',
      symbolSize: 9, // 拐点大小
      data: [],
      itemStyle: { color: '' },
      lineStyle: { width: 1, color: '' },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: '' },
          { offset: 1, color: '' }
        ])
      }
    },
    {
      name: '',
      type: 'line',
      showSymbol: false,
      symbol: 'circle',
      symbolSize: 9, // 拐点大小
      data: [],
      itemStyle: { color: '' },
      lineStyle: { width: 1, color: '' },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: '' },
          { offset: 1, color: '' }
        ])
      }
    }
  ];
};

const init = async () => {
  let series = getDefaultSeries() as any; //获取默认series配置
  let xAxisData = [] as any; // x轴临时数据
  const oneTab = activateId.value === 1;
  let res = oneTab ? RiskyAssetsData : VulnerabilityRiskData;
  if (dateRef.value === 2) {
    res = oneTab ? RiskyAssetsDataMonth : VulnerabilityRiskMonth;
  }
  if (dateRef.value === 3) {
    res = oneTab ? RiskyAssetsDataYear : VulnerabilityRiskYear;
  }
  const _legend = oneTab ? legend[0] : legend[1];
  const _lineColor = oneTab ? lineColor[0] : lineColor[1];
  const _legendColor = oneTab ? legendColor[0] : legendColor[1];
  const _gradientStart = oneTab ? gradientStart[0] : gradientStart[1];
  const _gradientEnd = oneTab ? gradientEnd[0] : gradientEnd[1];
  for (let i = 0; i < series.length; i++) {
    series[i].name = _legend[i];
    series[i].lineStyle.color = _lineColor[i];
    series[i].itemStyle.color = _legendColor[i];
    series[i].areaStyle.color.colorStops[0].color = _gradientStart[i];
    series[i].areaStyle.color.colorStops[1].color = _gradientEnd[i];
  }

  const data = res.sort(function (a, b) {
    return a.click_date > b.click_date ? 1 : -1; //  坐标轴时间排序
  });

  data.map((item) => {
    xAxisData.push(item.click_date);
    series[0].data.push(item.高危);
    series[1].data.push(item.中危);
    series[2].data.push(item.低危);
    return;
  });

  chartOption.series = series;
  chartOption.legend.data = _legend;
  chartOption.xAxis[0].data = xAxisData;
};

watch(activateId, () => {
  init();
});

watch(dateRef, () => {
  init();
});

onMounted(() => {
  init();
});
</script>

<template>
  <div class="custom-trend-change">
    <div class="custom-screen-block-header">
      <span class="title">趋势变化统计</span>
      <img :src="TabImgBig" alt="" class="img" />
      <RoundTab v-model="dateRef" class="round-tab"></RoundTab>
      <div class="options">
        <div class="item" :class="activateId === nav.value ? 'item-active' : ''" v-for="nav in navs" :key="nav.value"
          @click.stop="handleClickNav(nav)">
          <img class="img" :src="activateId === nav.value ? TabImgActive : TabImgDefault" alt="" />
          <span class="item-text">{{ nav.name }}</span>
        </div>
      </div>
    </div>

    <v-chart ref="myChart" :key="dateRef + activateId" class="chart" :option="chartOption" autoresize />
  </div>
</template>

<style lang="scss" scoped>
.custom-trend-change {
  width: 100%;
  height: 388px;
  color: #fff;
  position: relative;
}

.custom-screen-block-header {
  width: 100%;
  height: 42px;
  position: relative;
  display: flex;
  align-items: center;
  padding-left: 48px;
  box-sizing: border-box;

  .img {
    width: 100%;
    height: 42px;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 0;
  }

  .title {
    font-size: 18px;
    margin-top: -2px;
    font-family: 'MicrosoftYaHei';
    font-weight: 400;
    color: #fff;
    letter-spacing: 2px;
    z-index: 99;
  }

  .options {
    position: absolute;
    right: 0;
    top: 10px;
    height: 32px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .item {
      width: 180px;
      height: 32px;
      font-size: 18px;
      font-family: 'MicrosoftYaHei';
      font-weight: 400;
      color: #42a4cf;
      display: flex;
      align-items: center;
      justify-content: center;
      position: relative;
      cursor: pointer;

      .img {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        z-index: 0;
      }

      .item-text {
        z-index: 1;
      }
    }

    .item+.item {
      margin-left: 20px;
    }

    .item-active {
      color: #fff;
    }
  }
}

.chart {
  width: 100%;
  height: 100%;
}

.round-tab {
  position: absolute;
  top: 60px;
  left: 0;
}
</style>


<style lang="scss">
.tooltip-bg-big {
  width: 97px;
  height: 105px;
}

.trend-data-box {
  position: absolute;
  top: 6px;
  left: 10px;
}

.trend-data-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  column-gap: 8px;
}

.trend-data-font {
  font-size: 12px;
  font-family: 'Regular';
  font-weight: 400;
  color: #e0eef1;
}
</style>
