<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 chartInstanceToday = ref(null);
  const chartInstanceWeek = ref(null);
  const chartInstanceMonth = ref(null);
  
  const weekDates = ref([]);
  const monthDates = ref([]);
  
  let isTodayChartInitialized = false;
  let isWeekChartInitialized = false;
  let isMonthChartInitialized = false;
  
  const apiInstance = new BoxApi();
  const allEvents = ref([]);
  
  // 日期格式化函数
  const formatDateTime = (date) => dayjs(date).format('YYYY-MM-DD HH:mm:ss');
  
  // 获取时间参数
  const getDayParams = () => {
    const today = dayjs();
    return { timeAfter: today.startOf('day').format(), timeBefore: today.endOf('day').format() };
  };
  const getWeeklyParams = () => {
    const today = dayjs();
    return { timeAfter: today.subtract(7, 'day').format(), timeBefore: today.endOf('day').format() };
  };
  const getMonthlyParams = () => {
    const today = dayjs();
    return { timeAfter: today.subtract(30, 'day').format(), timeBefore: today.endOf('day').format() };
  };
  
  // 计算日期
  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((chartInstance, domRef, option) => {
    nextTick(() => {
      if (domRef.value) {
        chartInstance.value = echarts.init(domRef.value);
        chartInstance.value.setOption(option);
      }
    });
  }, 300);
  
  // 初始化图表选项配置
  const createTodayChartOption = () => ({
    tooltip: {
      trigger: 'item',
      axisPointer: { type: 'line' },
      formatter: (params) => {
        console.log('Tooltip params:', params);
        const date = params.name;  
        const value = params.value;  
        return `<strong>时间:${date}</strong><br/>告警数量: ${value}`;  // 使用 <strong> 标签作为小标题
      },
      backgroundColor: 'rgba(50, 50, 50, 0.3)',
      borderWidth: 1, 
      textStyle: {
        color: '#fff', 
        fontStyle: 'italic', // 字体样式，可以是 'normal', 'italic', 'oblique'
        fontWeight: 'bold', 
        fontFamily: 'Arial, sans-serif', // 字体
        fontSize: 12 
      },
      padding: 10 
    },
    grid: {
      top: '10%',
      left: '5%',
      right: '5%',
      bottom: '20%',
    },
    xAxis: {
      type: 'category',
      data: Array.from({ length: 24 }, (_, i) => `${i}:00`),
      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: hourlyCounts.value,
        smooth: true,
        areaStyle: { color: 'rgba(74, 172, 178, 0.3)' },
        lineStyle: { color: 'rgb(60,178,239)', width: 2 },
      },
    ],
  });
  
  const createWeekChartOption = () => ({
    tooltip: {
      trigger: 'item',
      axisPointer: { type: 'line' },
      formatter: (params) => {
        console.log('Tooltip params:', params);
        const date = params.name;  
        const value = params.value;  
        return `<strong>时间:${date}</strong><br/>告警数量: ${value}`;  // 使用 <strong> 标签作为小标题
      },
      backgroundColor: 'rgba(50, 50, 50, 0.3)',
      borderWidth: 1, 
      textStyle: {
        color: '#fff', 
        fontStyle: 'italic', // 字体样式，可以是 'normal', 'italic', 'oblique'
        fontWeight: 'bold', 
        fontFamily: 'Arial, sans-serif', // 字体
        fontSize: 12 
      },
      padding: 10 
    },
    grid: {
      top: '10%',
      left: '5%',
      right: '5%',
      bottom: '20%',
    },
    xAxis: {
      type: 'category',
      data: weekDates.value,
      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: dailyCounts.value,
        smooth: true,
        areaStyle: { color: 'rgba(74, 172, 178, 0.3)' },
        lineStyle: { color: 'rgb(60,178,239)', width: 2 },
      },
    ],
  });
  
  const createMonthChartOption = () => ({
    tooltip: {
      trigger: 'item',
      axisPointer: { type: 'line' },
      formatter: (params) => {
        console.log('Tooltip params:', params);
        const date = params.name;  
        const value = params.value;  
        return `<strong>时间:${date}</strong><br/>告警数量: ${value}`;  // 使用 <strong> 标签作为小标题
      },
      backgroundColor: 'rgba(50, 50, 50, 0.3)',
      borderWidth: 1, 
      textStyle: {
        color: '#fff', 
        fontStyle: 'italic', // 字体样式，可以是 'normal', 'italic', 'oblique'
        fontWeight: 'bold', 
        fontFamily: 'Arial, sans-serif', // 字体
        fontSize: 12 
      },
      padding: 10 
    },
    grid: {
      top: '10%',
      left: '5%',
      right: '5%',
      bottom: '20%',
    },
    xAxis: {
      type: 'category',
      data: monthDates.value,
      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: monthlyCounts.value,
        smooth: true,
        areaStyle: { color: 'rgba(74, 172, 178, 0.3)' },
        lineStyle: { color: 'rgb(60,178,239)', width: 2 },
      },
    ],
  });
  
  // 获取和处理事件数据
  const fetchAndProcessEvents = async (timeParams) => {
    try {
      let currentPage = 1;
      const pageSize = 1000;
      const token = localStorage.getItem('alertToken');
      allEvents.value = [];
  
      const firstResponse = await apiInstance.getEventsByParams(token, pageSize, currentPage, timeParams.timeBefore, timeParams.timeAfter);
      const totalItems = firstResponse.count;
      allEvents.value.push(...firstResponse.results);
  
      const totalPages = Math.ceil(totalItems / pageSize);
      while (currentPage < totalPages) {
        currentPage++;
        const response = await apiInstance.getEventsByParams(token, pageSize, currentPage, timeParams.timeBefore, timeParams.timeAfter);
        allEvents.value.push(...response.results);
      }
  
      processEventData(allEvents.value);
    } catch (error) {
      console.error("Error fetching events:", error);
    }
  };
  
  // 处理事件数据
  const processEventData = (events) => {
    hourlyCounts.value.fill(0);
    dailyCounts.value.fill(0);
    monthlyCounts.value.fill(0);
    events.forEach((event) => {
      const hour = dayjs(event.ended_at).hour();
      const dayDiff = dayjs().diff(dayjs(event.ended_at), 'day');
      if (dayDiff < 1) hourlyCounts.value[hour] += 1;
      if (dayDiff < 7) dailyCounts.value[6 - dayDiff] += 1;
      if (dayDiff < 30) monthlyCounts.value[29 - dayDiff] += 1;
    });
    updateCharts();
  };
  
  // 更新图表
  const updateCharts = () => {
    if (chartInstanceToday.value) chartInstanceToday.value.setOption({ series: [{ data: hourlyCounts.value }] });
    if (chartInstanceWeek.value) chartInstanceWeek.value.setOption({ series: [{ data: dailyCounts.value }] });
    if (chartInstanceMonth.value) chartInstanceMonth.value.setOption({ series: [{ data: monthlyCounts.value }] });
  };
  
  // 处理选项卡切换
  const handleClick = async (tab) => {
    let timeParams;
    if (tab.props.name === 'first' && !isTodayChartInitialized) {
      timeParams = getDayParams();
      await fetchAndProcessEvents(timeParams);
      delayedInitChart(chartInstanceToday, todayLineChartDom, createTodayChartOption());
      isTodayChartInitialized = true;
    } else if (tab.props.name === 'second' && !isWeekChartInitialized) {
      timeParams = getWeeklyParams();
      await fetchAndProcessEvents(timeParams);
      delayedInitChart(chartInstanceWeek, weekLineChartDom, createWeekChartOption());
      isWeekChartInitialized = true;
    } else if (tab.props.name === 'third' && !isMonthChartInitialized) {
      timeParams = getMonthlyParams();
      await fetchAndProcessEvents(timeParams);
      delayedInitChart(chartInstanceMonth, monthLineChartDom, createMonthChartOption());
      isMonthChartInitialized = true;
    }
  };
  
  // 窗口调整时重新渲染图表
  const resizeCharts = debounce(() => {
    if (chartInstanceToday.value) chartInstanceToday.value.resize();
    if (chartInstanceWeek.value) chartInstanceWeek.value.resize();
    if (chartInstanceMonth.value) chartInstanceMonth.value.resize();
  }, 300);
  
  // 组件挂载时调用
  onMounted(async () => {
    calculateWeekDates();
    calculateMonthDates();
    await handleClick({ props: { name: 'first' } });
    window.addEventListener('resize', resizeCharts);
  });
  </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>
  