<template>
  <div>
    <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"> <!-- 新增最近30天选项卡 -->
          <div ref="monthLineChartDom" class="chart-container"></div> <!-- 最近30天图表 -->
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, 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)); // 初始化24小时的计数器
const chartInstanceToday = ref(null);
const todayLineChartDom = ref(null);

const dailyCounts = ref(Array(7).fill(0)); // 初始化7天的计数器
const weekDates = ref([]); // 存储前7天的日期
const chartInstanceWeek = ref(null);
const weekLineChartDom = ref(null);

const monthlyCounts = ref(Array(30).fill(0)); // 初始化30天的计数器
const monthDates = ref([]); // 存储前30天的日期
const chartInstanceMonth = ref(null); // 30天的图表实例
const monthLineChartDom = ref(null);

const apiInstance = new BoxApi();
const allEvents = ref([]); // 使用响应式 allEvents

let isTodayChartInitialized = false;
let isWeekChartInitialized = false;
let isMonthChartInitialized = false; // 30天图表是否初始化

// 计算前7天的日期
const calculateWeekDates = () => {
  const today = dayjs();
  weekDates.value = Array.from({ length: 7 }, (_, i) => today.subtract(i, 'day').format('YYYY-MM-DD')).reverse();
};

// 计算前30天的日期
const calculateMonthDates = () => {
  const today = dayjs();
  monthDates.value = Array.from({ length: 30 }, (_, i) => today.subtract(i, 'day').format('YYYY-MM-DD')).reverse();
};

// 初始化今日图表
const initTodayChart = () => {
  if (todayLineChartDom.value) {
    chartInstanceToday.value = echarts.init(todayLineChartDom.value);

    const option = {
      title: {
        text: '今日告警数量趋势',
        top: '3%',
        textStyle: {
          color: '#fff',
          fontWeight: 'bold',
        },
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
        },
        formatter: function (params) {
          const { value, name } = params[0];
          return `${name}<br/>告警数量: ${value}`;
        },
        textStyle: {
          color: '#fff',
          fontSize: 12,
        },
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: Array.from({ length: 24 }, (_, i) => `${i.toString().padStart(2, '0')}:00`),
        axisLabel: {
          rotate: 0,
          color: '#fff',
        },
      },
      yAxis: {
        type: 'value',
        min: 0,
        minInterval: 1,
        axisLabel: {
          color: '#fff',
        },
      },
      series: [
        {
          name: '告警数量',
          type: 'line',
          data: hourlyCounts.value.length > 0 ? hourlyCounts.value : Array(24).fill(0),
          smooth: true,
          label: {
            show: true,
            position: 'top',
            textStyle: {
              color: '#fff',
            },
          },
          lineStyle: {
            color: 'rgb(60,178,239)', // 曲线颜色
            width: 2,
          },
          areaStyle: {
            color: 'rgba(74, 172, 178, 0.3)', // 覆盖面积颜色
          },
        },
      ],
    };
    chartInstanceToday.value.setOption(option);
  }
};

// 初始化本周图表
const initWeekChart = () => {
  if (weekLineChartDom.value) {
    chartInstanceWeek.value = echarts.init(weekLineChartDom.value);

    const option = {
      title: {
        text: '最近7天告警数量趋势',
        top: '5%',
        textStyle: {
          color: '#fff',
          fontSize: 18,
          fontWeight: 'bold',
        },
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
        },
        formatter: function (params) {
          const { value } = params[0];
          return `告警数量: ${value}`;
        },
        textStyle: {
          color: '#fff',
          fontSize: 12,
        },
      },
      xAxis: {
        type: 'category',
        boundaryGap: true,
        data: weekDates.value.length > 0 ? weekDates.value : Array.from({ length: 7 }, (_, i) => `日期 ${i + 1}`),
        axisLabel: {
          rotate: 0,
          interval: 0,
          color: '#fff',
          fontSize: 12,
        },
      },
      yAxis: {
        type: 'value',
        min: 0,
        minInterval: 1,
        axisLabel: {
          color: '#fff',
          fontSize: 12,
        },
      },
      series: [
        {
          name: '告警数量',
          type: 'line',
          data: dailyCounts.value.length > 0 ? dailyCounts.value : Array(7).fill(0),
          smooth: true,
          label: {
            show: true,
            position: 'top',
            textStyle: {
              color: '#fff',
              fontSize: 12,
            },
          },
          lineStyle: {
            color: 'rgb(60,178,239)', // 曲线颜色
            width: 2,
          },
          areaStyle: {
            color: 'rgba(74, 172, 178, 0.3)', // 覆盖面积颜色
          },
        },
      ],
    };

    chartInstanceWeek.value.setOption(option);
  }
};

// 初始化最近30天图表
const initMonthChart = () => {
  if (monthLineChartDom.value) {
    chartInstanceMonth.value = echarts.init(monthLineChartDom.value);

    const option = {
      title: {
        text: '最近30天告警数量趋势',
        top: '3%',
        textStyle: {
          color: '#fff',
          fontWeight: 'bold',
        },
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
        },
        formatter: function (params) {
          const { value, name } = params[0];
          return `${name}<br/>告警数量: ${value}`;
        },
        textStyle: {
          color: '#fff',
          fontSize: 12,
        },
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: monthDates.value,
        axisLabel: {
          rotate: 0,
          color: '#fff',
        },
      },
      yAxis: {
        type: 'value',
        min: 0,
        minInterval: 1,
        axisLabel: {
          color: '#fff',
        },
      },
      series: [
        {
          name: '告警数量',
          type: 'line',
          data: monthlyCounts.value.length > 0 ? monthlyCounts.value : Array(30).fill(0),
          smooth: true,
          label: {
            show: true,
            position: 'top',
            textStyle: {
              color: '#fff',
            },
          },
          lineStyle: {
            color: 'rgb(60,178,239)', // 曲线颜色
            width: 2,
          },
          areaStyle: {
            color: 'rgba(74, 172, 178, 0.3)', // 覆盖面积颜色
          },
        },
      ],
    };
    chartInstanceMonth.value.setOption(option);
  }
};

// 获取并处理告警数据
const fetchAndProcessEvents = async (token) => {
  try {
    let currentPage = 1;
    const pageSize = 1000;

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

    // 根据告警总数逐页加载所有数据
    const totalPages = Math.ceil(totalItems / pageSize);

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

    // 处理数据
    processEventData(allEvents.value); // 今日告警数据
    processWeekData(); // 本周告警数据
    processMonthData(); // 最近30天告警数据
  } catch (error) {
    console.error("Error fetching events:", error);
  }
};

// 处理今日告警数据并更新图表
const processEventData = (events) => {
  hourlyCounts.value = Array(24).fill(0);
  const today = new Date();
  const startOfToday = new Date(today.getFullYear(), today.getMonth(), today.getDate());
  const endOfToday = new Date(today.getFullYear(), today.getMonth(), today.getDate() + 1);

  events.forEach((event) => {
    const endedAt = event.ended_at;
    if (endedAt) {
      const endedDate = new Date(endedAt);
      if (endedDate >= startOfToday && endedDate < endOfToday) {
        const hour = endedDate.getHours();
        hourlyCounts.value[hour] += 1;
      }
    }
  });

  updateCharts();
};

// 处理本周告警数据
const processWeekData = () => {
  dailyCounts.value = Array(7).fill(0);

  allEvents.value.forEach((event) => {
    const endedAt = event.ended_at;
    if (endedAt) {
      const endedDay = dayjs(endedAt).format('YYYY-MM-DD');
      weekDates.value.forEach((date, index) => {
        if (endedDay === date) {
          dailyCounts.value[index] += 1;
        }
      });
    }
  });

  updateWeekChart();
};

// 处理最近30天告警数据
const processMonthData = () => {
  monthlyCounts.value = Array(30).fill(0);

  allEvents.value.forEach((event) => {
    const endedAt = event.ended_at;
    if (endedAt) {
      const endedDay = dayjs(endedAt).format('YYYY-MM-DD');
      monthDates.value.forEach((date, index) => {
        if (endedDay === date) {
          monthlyCounts.value[index] += 1;
        }
      });
    }
  });

  updateMonthChart();
};

// 更新今日图表
const updateCharts = () => {
  if (chartInstanceToday.value) {
    chartInstanceToday.value.setOption({
      series: [{ data: hourlyCounts.value }],
    });
  }
};

// 更新本周图表
const updateWeekChart = () => {
  if (chartInstanceWeek.value) {
    chartInstanceWeek.value.setOption({
      series: [{ data: dailyCounts.value }],
    });
  }
};

// 更新最近30天图表
const updateMonthChart = () => {
  if (chartInstanceMonth.value) {
    chartInstanceMonth.value.setOption({
      series: [{ data: monthlyCounts.value }],
    });
  }
};

// 处理选项卡切换
const handleClick = async (tab) => {
  if (tab.props.name === 'first') {
    if (!isTodayChartInitialized) {
      await nextTick();
      initTodayChart();
      isTodayChartInitialized = true;
    }
    delayInstanceToday();
  } else if (tab.props.name === 'second') {
    await processWeekData();
    if (!isWeekChartInitialized) {
      await nextTick();
      initWeekChart();
      isWeekChartInitialized = true;
    }
    delayInstanceWeek();
  } else if (tab.props.name === 'third') {
    await processMonthData();
    if (!isMonthChartInitialized) {
      await nextTick();
      initMonthChart();
      isMonthChartInitialized = true;
    }
    delayInstanceMonth();
  }
};

// 窗口调整时重新渲染图表
const delayInstanceToday = debounce(() => {
  if (chartInstanceToday.value) {
    chartInstanceToday.value.resize();
    updateCharts();
  }
}, 300);

const delayInstanceWeek = debounce(() => {
  if (chartInstanceWeek.value) {
    chartInstanceWeek.value.resize();
    updateWeekChart();
  }
}, 300);

const delayInstanceMonth = debounce(() => {
  if (chartInstanceMonth.value) {
    chartInstanceMonth.value.resize();
    updateMonthChart();
  }
}, 300);

// 组件挂载时调用
onMounted(async () => {
  calculateWeekDates(); // 计算前7天日期
  calculateMonthDates(); // 计算前30天日期
  const token = localStorage.getItem('alertToken');
  await fetchAndProcessEvents(token); // 加载数据

  initTodayChart();
});

// 监听数据变化，更新对应的图表
watch(hourlyCounts, () => {
  if (chartInstanceToday.value) {
    chartInstanceToday.value.setOption({
      series: [{ data: hourlyCounts.value }],
    });
  }
});

watch(dailyCounts, () => {
  if (chartInstanceWeek.value) {
    chartInstanceWeek.value.setOption({
      series: [{ data: dailyCounts.value }],
    });
  }
});

watch(monthlyCounts, () => {
  if (chartInstanceMonth.value) {
    chartInstanceMonth.value.setOption({
      series: [{ data: monthlyCounts.value }],
    });
  }
});

</script>

<style scoped>
.alert-card {
  background-color: #304555;
  color: #fff;
  border-radius: 8px;
  /* padding: 10px; */
  /* margin: 10px; */
}

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

.chart-container {
  /* min-height: 350px; */
  min-height: 41vh;
  min-width: 40vw;
}

::v-deep .el-tabs__item {
  color: #fff;
}

::v-deep .el-tabs__item.is-active {
  color: #2ea0ec;
}
</style>
