<template>
  <div>
    <el-card class="stats-card">
      <div class="stats-header">告警数量和类型分布</div>
      <el-row :gutter="20" class="stats-row">
        <el-col :span="24">
          <div ref="chart" class="chart"></div>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import * as echarts from 'echarts';
import { BoxApi } from '@/utils/boxApi.ts'; // 引入 BoxApi 类

// 响应式数据
const chart = ref(null);
const seriesData = ref([]);

// BoxApi 实例
const apiInstance = new BoxApi();

// 获取告警类型的映射
const fetchTypeMapping = async (token) => {
  const algorithms = await apiInstance.getAlgorithms(token);
  let mapping = algorithms.map(algorithm => ({
    value: 0,
    code_name: algorithm.code_name,
    name: algorithm.name
  }));

  // 添加额外的类型
  const newMapping = [
    { code_name: "minizawu:532", name: "杂物堆积", value: 0 }
  ];

  seriesData.value = mapping.concat(newMapping);
};

// 分批次获取全量告警数据并更新 seriesData
const fetchAndProcessEvents = async (token) => {
  try {
    let currentPage = 1;
    const pageSize = 1000;  // 每次加载 2000 条
    let allEvents = [];

    // 第一次请求，获取告警总数和首批数据
    const { tableData: firstBatch, totalItems } = await apiInstance.getEvents(token, pageSize, currentPage);
    allEvents = [...firstBatch];

    // 根据告警总数计算总页数
    const totalPages = Math.ceil(totalItems / pageSize);

    // 循环分页加载剩余的数据
    while (currentPage < totalPages) {
      currentPage++;
      const { tableData: nextBatch } = await apiInstance.getEvents(token, pageSize, currentPage);
      allEvents = [...allEvents, ...nextBatch];

      // 每次加载数据后逐步更新图表
      processEventData(allEvents);
      updateChart();  // 逐步更新图表
    }

    // 最终处理全部数据
    processEventData(allEvents);
    updateChart();  // 最终更新图表
  } catch (error) {
    console.error("Error fetching events:", error);
  }
};

// 处理告警事件数据并更新 seriesData
const processEventData = (events) => {
  // 重置数据，防止累计错误
  seriesData.value.forEach(item => {
    item.value = 0;
  });

  // 遍历事件并统计告警类型数量
  events.forEach(event => {
    const matchAlgorithm = seriesData.value.find(item => item.code_name === event.types);
    if (matchAlgorithm) {
      matchAlgorithm.value += 1;
    }
  });
};

// 初始化图表
const initChart = () => {
  // 初始化 ECharts 实例
  if (!chart.value) {
    console.error("Chart DOM element is not available");
    return;
  }

  chart.value = echarts.init(chart.value);
  const option = {
    tooltip: {
      trigger: 'item',
    },
    legend: {
      orient: 'horizontal',
      bottom: 10,
      textStyle: {
        color: '#fff',
      },
      itemGap: 20,
      data: seriesData.value.map(item => item.name),
      show : true
    },
    series: [
      {
        name: '告警类型',
        type: 'pie',
        radius: '50%',
        center: ['50%', '50%'],
        data: seriesData.value,
        data: [],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)',
          }
        },
        label: {
          show: false,
        },
        stillShowZeroSum: false,
      }
    ]
  };
  chart.value.setOption(option);
};

// 更新图表数据
const updateChart = () => {
  if (chart.value && typeof chart.value.setOption === 'function') {
    chart.value.setOption({
      series: [
        {
          data: seriesData.value
        }
      ]
    });
  } else {
    console.error("ECharts instance is not initialized properly");
  }
};

// 生命周期钩子
onMounted(async () => {
  try {
    const token = localStorage.getItem('alertToken');

    // 获取告警类型映射
    await fetchTypeMapping(token);

    // 初始化图表
    initChart();

    // 分批次获取告警数据并更新图表
    await fetchAndProcessEvents(token);
  } catch (error) {
    console.error("Error fetching data:", error);
  }
});
</script>

<style scoped>
.stats-card {
  background-color: #304555;
  /* background: linear-gradient(to top, rgba(16, 84, 194, 0.6), rgba(31, 48, 207, 0.7)); */
  color: #fff;
  border-radius: 8px;
  /* margin: 10px; */
  /* padding: 10px; */
  /* height: 100vh; */
}

.stats-header {
  font-size: 18px;
  font-weight: bold;
  border-bottom: 1px solid #3a4b5c;
  padding-bottom: 10px;
}

.stats-row {
  margin-top: 10px;
  margin-bottom: 34px;
}

.chart {
  width: 100%;
  /* min-height: 365px; */
  height: 41vh;
  min-width: 40vw;
  /* height: 445px; */
}
</style>
