<template>
    <div class="alert-container">
      <!-- <el-card class="alert-card">
        <div class="alert-header">告警趋势</div>
        <el-tabs v-model="activeName" @tab-click="handleClick" class="alert-tabs">
          <el-tab-pane label="今日" name="first">
            <div ref="todayLineChartDom" class="chart-container"></div> 
          </el-tab-pane>
          <el-tab-pane label="本周" name="second">
            <div ref="weekLineChartDom" class="chart-container"></div> 
          </el-tab-pane>
          <el-tab-pane label="最近30天" name="third"> 
            <div ref="monthLineChartDom" class="chart-container"></div> 
          </el-tab-pane>
        </el-tabs>
      </el-card> -->
      <el-tabs v-model="activeName" @tab-click="handleClick" class="alert-tabs">
        <el-tab-pane label="今日" name="first">
          <div ref="todayLineChartDom" class="chart-container"></div> <!-- 今日图表 -->
        </el-tab-pane>
        <el-tab-pane label="本周" name="second">
          <div ref="weekLineChartDom" class="chart-container"></div> <!-- 本周图表 -->
        </el-tab-pane>
        <el-tab-pane label="最近30天" name="third"> <!-- 新增最近30天选项卡 -->
          <div ref="monthLineChartDom" class="chart-container"></div> <!-- 最近30天图表 -->
        </el-tab-pane>
      </el-tabs>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted, nextTick } from 'vue';
  import * as echarts from 'echarts';
  import { BoxApi } from '@/utils/boxApi.ts';
  import dayjs from 'dayjs';
  import { debounce } from 'lodash';
  
  
  const activeName = ref('first');
  const hourlyCounts = ref(Array(24).fill(0));
  const dailyCounts = ref(Array(7).fill(0));
  const monthlyCounts = ref(Array(30).fill(0));
  
  const todayLineChartDom = ref(null);
  const weekLineChartDom = ref(null);
  const monthLineChartDom = ref(null);
  
  const chartInstance = ref(null);
  
  const weekDates = ref([]);
  const monthDates = ref([]);
  
  const apiInstance = new BoxApi();
  
  // 设置时间范围获取计数
  const getEventCount = async (timeBefore, timeAfter) => {
    try {
      const token = localStorage.getItem('alertToken');
      const response = await apiInstance.getEventsByParams(token, 1, 1, timeBefore, timeAfter);
      return response.count;
    } catch (error) {
      console.error("Error fetching event count:", error);
      return 0;
    }
  };
  
  // 生成图表的配置选项
  const createChartOption = (title, xAxisData, seriesData) => ({
    // title: {
    //   text: title,          
    //   left: 'center',               
    //   top: '0%',                    
    //   textStyle: {
    //     color: '#ffffff',           
    //     fontSize: 16,               
    //     fontWeight: 'bold',         
    //     fontFamily: 'Arial, sans-serif', 
    //   },
    // },
    tooltip: {
      trigger: 'item',
      axisPointer: { type: 'line' },
      formatter: (params) => {
        const date = params.name;  
        const value = params.value;  
        return `<strong>时间:${date}</strong><br/>告警数量: ${value}`;  
      },
      backgroundColor: 'rgba(50, 50, 50, 0.3)',
      borderWidth: 1, 
      textStyle: {
        color: '#fff', 
        fontStyle: 'italic',
        fontWeight: 'bold', 
        fontFamily: 'Arial, sans-serif',
        fontSize: 12 
      },
      padding: 10 
    },
    grid: {
      top: '10%',
      left: '5%',
      right: '5%',
      bottom: '20%',
    },
    xAxis: {
      type: 'category',
      data: xAxisData,
      axisLabel: { color: '#fff' },
    },
    yAxis: {
      type: 'value', minInterval: 1, axisLabel: { color: '#fff' },
      splitLine: {
        show: false,
        lineStyle: { color: '#cccccc', width: 1, type: 'solid' }
      },
    },
    series: [
      {
        name: '告警数量',
        type: 'line',
        data: seriesData,
        smooth: true,
        areaStyle: { color: 'rgba(74, 172, 178, 0.3)' },
        lineStyle: { color: 'rgb(60,178,239)', width: 2 },
      },
    ],
  });
  
  // 更新计数数据
  const updateCounts = async (range) => {
    let timeAfter, timeBefore = dayjs().format();
  
    if (range === 'day') {
      // 获取“今日”每小时的事件数量
      for (let i = 0; i < 24; i++) {
        timeAfter = dayjs().startOf('day').add(i, 'hour').format();
        timeBefore = dayjs().startOf('day').add(i + 1, 'hour').format();
        hourlyCounts.value[i] = await getEventCount(timeBefore, timeAfter);
        console.log(`Hour ${i}: ${hourlyCounts.value[i]}`);
      }
      delayedInitChart(todayLineChartDom, createChartOption('今日告警趋势', Array.from({ length: 24 }, (_, i) => `${i}:00`), hourlyCounts.value));
  
    } else if (range === 'week') {
      // 获取“本周”每天的事件数量
      for (let i = 0; i < 7; i++) {
        timeAfter = dayjs().subtract(i + 1, 'day').endOf('day').format();
        timeBefore = dayjs().subtract(i, 'day').endOf('day').format();
        dailyCounts.value[6 - i] = await getEventCount(timeBefore, timeAfter);
      }
      delayedInitChart(weekLineChartDom, createChartOption('本周告警趋势', weekDates.value, dailyCounts.value));
  
    } else if (range === 'month') {
      // 获取“最近30天”每天的事件数量
      for (let i = 0; i < 30; i++) {
        timeAfter = dayjs().subtract(i + 1, 'day').endOf('day').format();
        timeBefore = dayjs().subtract(i, 'day').endOf('day').format();
        monthlyCounts.value[29 - i] = await getEventCount(timeBefore, timeAfter);
      }
      delayedInitChart(monthLineChartDom, createChartOption('近30天告警趋势', monthDates.value, monthlyCounts.value));
    }
  };
  
  // 处理选项卡切换
  const handleClick = async (tab) => {
    const range = tab.props.name === 'first' ? 'day' : tab.props.name === 'second' ? 'week' : 'month';
    await updateCounts(range);
  };
  
  // 初始化日期
  const calculateWeekDates = () => {
    weekDates.value = Array.from({ length: 7 }, (_, i) => dayjs().subtract(i, 'day').format('YYYY-MM-DD')).reverse();
  };
  const calculateMonthDates = () => {
    monthDates.value = Array.from({ length: 30 }, (_, i) => dayjs().subtract(i, 'day').format('YYYY-MM-DD')).reverse();
  };
  
  // 图表延迟初始化
  const delayedInitChart = debounce((domRef, option) => {
    nextTick(() => {
      if (domRef.value) {
        chartInstance.value = echarts.init(domRef.value);
        chartInstance.value.setOption(option);
      }
    });
  }, 300);
  
  // 组件挂载时调用
  onMounted(async () => {
    calculateWeekDates();
    calculateMonthDates();
    await handleClick({ props: { name: 'first' } });
    window.addEventListener('resize', debounce(() => {
      if (chartInstance.value) chartInstance.value.resize();
    }, 300));
  });
  </script>
  
  
  
  <style scoped>
  .alert-card {
    background-color: #001529;
    color: #fff;
    border-radius: 8px;
    /* padding: 10px; */
    /* margin: 10px; */
  }
  
  .alert-container {
    background-color: #001529;
    margin: 0vh 1vw 1vh 1vw; 
    /* margin-top: 0; */
  }
  
  /* .alert-header {
    font-size: 18px;
    font-weight: bold;
    border-bottom: 1px solid #3a4b5c;
  } */
  
  .chart-container {
    /* min-height: 350px; */
    width: 100%;
    height: 15vh;
  }
  
  ::v-deep .el-tabs__item {
    color: #fff;
    font-size: 13px;
    padding: 0;
    margin-left: 1vh;
    height: 20px;
  }
  
  ::v-deep .el-tabs__item.is-active {
    color: #2ea0ec;
  }
  
  /* ::v-deep .el-tabs___nav-wrap.is-top::after{
    border: none;
  } */
  
  /* ::v-deep .el-tabs__active-bar.is-top{
  padding: 0 204px;
  box-sizing: border-box !important;
  background-clip: content-box !important;
  } */
  
  
  .el-tabs__active-bar {
    background-color: transparent !important;
  }
  
  
  ::v-deep .el-tabs__nav-wrap::after {
    /* width: 15vw; */
    position: static !important;
  }
  </style>
  