<!--
 * @Author: chris
 * @Date: 2025-08-18 09:36:11
 * @LastEditors: chris
 * @LastEditTime: 2025-10-16 10:29:23
-->
<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue';
import { BarChart } from 'echarts/charts';
// 引入标题，提示框，直角坐标系，数据集，内置数据转换器组件
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent
} from 'echarts/components';
// 标签自动布局、全局过渡动画等特性
import { LabelLayout, UniversalTransition } from 'echarts/features';
// 引入 Canvas 渲染器
import { CanvasRenderer } from 'echarts/renderers';

const props = defineProps({
  chartData: {
    type: Object,
    default: () => ({
      names: [],
      data: []
    })
  }
});


// 获取组件实例
const { proxy } = getCurrentInstance();
// 图表引用
const barChartRef = ref(null);
// ECharts实例
let barChart = null;
// 当前选中的天数（7天或15天）
const selectedDays = ref(7);

const dateRange = ref([]);

const emits = defineEmits(['dayRangeChange']);

// 注册ECharts组件
function registerComponents() {
  proxy.$echarts.use([
    TitleComponent,
    TooltipComponent,
    GridComponent,
    DatasetComponent,
    TransformComponent,
    BarChart,
    LabelLayout,
    UniversalTransition,
    CanvasRenderer
  ]);
}

// 生成指定天数的日期数组
// function generateDates(days) {
//   const dates = [];
//   const today = new Date();

//   for (let i = days - 1; i >= 0; i--) {
//     const date = new Date(today);
//     date.setDate(date.getDate() - i);
//     // 格式化为 MM/DD 格式
//     dates.push(`${date.getMonth() + 1}/${date.getDate()}`);
//   }

//   return dates;
// }

// // 生成随机的消息数量数据
// function generateMessageCount(days) {
//   const counts = [];
  
//   for (let i = 0; i < days; i++) {
//     // 生成10-200之间的随机数
//     const count = Math.floor(Math.random() * 190) + 10;
//     counts.push(count);
//   }
  
//   return counts;
// }

// // 初始化图表数据
// function initChartData() {
//   const dates = generateDates(selectedDays.value);
//   const messageCounts = generateMessageCount(selectedDays.value);
  
//   return {
//     names: dates,
//     data: messageCounts
//   };
// }

// 创建图表配置选项
function createOption(data) {
  return {
    title: {
      text: '消息推送统计',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(0, 0, 0, 0.7)',
      borderColor: '#333',
      textStyle: {
        color: '#fff'
      },
      formatter: function(params) {
        const data = params[0];
        return `${data.name}<br/>推送数量: ${data.value}`;
      },
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: data.names,
      axisLine: {
        lineStyle: {
          color: '#464646'
        }
      },
      axisLabel: {
        color: '#333'
      }
    },
    yAxis: {
      type: 'value',
      name: '推送数量',
      nameTextStyle: {
        color: '#333'
      },
      min: 0,
      axisLine: {
        lineStyle: {
          color: '#464646'
        }
      },
      axisLabel: {
        color: '#333'
      },
      splitLine: {
        lineStyle: {
          color: '#f0f0f0',
          type: 'dashed'
        }
      }
    },
    series: [
      {
        name: '推送数量',
        type: 'bar',
        data: data.data,
        itemStyle: {
          color: new proxy.$echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: '#4dabf7'
            },
            {
              offset: 1,
              color: '#228be6'
            }
          ])
        },
        emphasis: {
          itemStyle: {
            color: new proxy.$echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color: '#339af0'
              },
              {
                offset: 1,
                color: '#1c7ed6'
              }
            ])
          }
        },
        // 在柱子上显示数值
        label: {
          show: true,
          position: 'top',
          color: '#333'
        }
      }
    ]
  };
}

// 初始化图表
function initBarChart() {
  if (barChartRef.value && proxy.$echarts) {
    // 销毁已存在的图表实例
    if (barChart) {
      barChart.dispose();
    }
    
    barChart = proxy.$echarts.init(barChartRef.value);
    barChart.setOption(createOption(props.chartData));
  }
}

// 处理窗口大小变化
function handleResize() {
  if (barChart) {
    barChart.resize();
  }
}

// 处理时间范围切换
function handleTimeRangeChange(days) {
  selectedDays.value = days;
  dateRange.value = proxy.$utils.getDateRange(days);
  emits('dayRangeChange', dateRange.value);
}

// 监听图表数据变化
watch(() => props.chartData, (newData) => {
  if (barChart) {
    barChart.setOption(createOption(newData));
  }
}, { immediate: true });

// 生命周期钩子
onMounted(() => {
  registerComponents();
  initBarChart();
  window.addEventListener('resize', handleResize);
});

onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  if (barChart) {
    barChart.dispose();
    barChart = null;
  }
});
</script>

<template>
  <div class="statistics-container">
    <!-- 时间范围选择器 -->
    <div class="time-range-selector">
      <el-radio-group v-model="selectedDays" @change="handleTimeRangeChange">
        <el-radio-button :value="7">近7天</el-radio-button>
        <el-radio-button :value="15">近15天</el-radio-button>
        <el-radio-button :value="30">近30天</el-radio-button>
      </el-radio-group>
    </div>
    
    <!-- 柱状图容器 -->
    <div class="chart-container">
      <div class="bar-chart" style="height: 100%;" ref="barChartRef"></div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.statistics-container {
  width: 100%;
  height: 100%;
  
  .time-range-selector {
    margin-bottom: 10px;
  }
  
  .chart-container {
    width: 100%;
    height: calc(100% - 40px);
    
    .bar-chart {
      width: 100%;
      height: 100%;
      min-height: 340px;
    }
  }
}
</style>
