<script lang="ts" setup>
import { FullScreen, PieChart } from '@element-plus/icons-vue';
import { useElementSize } from '@vueuse/core';
import { BarChart, PieChart as EPieChart, LineChart } from 'echarts/charts';
import {
  BrushComponent,
  GraphicComponent,
  GridComponent,
  LegendComponent,
  TitleComponent,
  TooltipComponent,
} from 'echarts/components';
import * as echarts from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { getLast7DaysTokenUsage, getLast24HoursTokenUsage, getModelTokenUsage, getSelectableTokenInfo, getTodayModelUsage } from '@/api';

// 注册必要的组件
echarts.use([
  LineChart,
  EPieChart,
  BarChart,
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  GraphicComponent,
  BrushComponent,
  CanvasRenderer,
]);

// 图表引用
const lineChart = ref(null);
const pieChart = ref(null);
const barChart = ref(null);
const hourlyBarChart = ref(null); // 新增：近24小时每小时Token消耗柱状图
let lineChartInstance: any = null;
let pieChartInstance: any = null;
let barChartInstance: any = null;
let hourlyBarChartInstance: any = null; // 新增：近24小时柱状图实例

// 全屏状态
const isFullscreen = ref(false);
const usageStatisticsRef = ref<HTMLElement>();

// 容器尺寸监听
const pieContainerSize = useElementSize(pieChart);
const barContainerSize = useElementSize(barChart);

// 数据
const loading = ref(false);
const totalTokens = ref(0);
const usageData = ref<any[]>([]);
const showLast7DaysChart = ref(false); // 是否显示近七天图表
const loadingLast7Days = ref(false); // 近七天数据加载状态
const currentPeriodView = ref('24h'); // 当前显示的时间范围：'24h' 或 '7d'
const modelUsageData = ref<any[]>([]);
const hourlyUsageData = ref<any[]>([]); // 新增：近24小时每小时Token消耗数据
const todayModelUsageData = ref<any[]>([]); // 新增：今日各模型使用量数据

// Token选择相关
const selectedTokenId = ref<string>(''); // 空字符串表示查询全部
const tokenOptions = ref<any[]>([]);
const tokenOptionsLoading = ref(false);

// 计算属性：是否有模型数据
const hasModelData = computed(() => modelUsageData.value.length > 0);

// 计算属性：当前选择的token名称
const selectedTokenName = computed(() => {
  if (!selectedTokenId.value)
    return '全部API密钥';
  const token = tokenOptions.value.find(t => t.tokenId === selectedTokenId.value);
  return token?.name || '未知API密钥';
});

// 计算属性：获取近24小时数据中所有唯一的模型ID（按总token使用量排序，只统计有数据的模型）
const hourlyModels = computed(() => {
  const modelTokenMap = new Map<string, { tokens: number; iconUrl: string }>();
  hourlyUsageData.value.forEach((hour) => {
    hour.modelBreakdown?.forEach((model: any) => {
      // 只统计有实际使用量的模型
      if (model.tokens > 0) {
        const existing = modelTokenMap.get(model.modelId);
        modelTokenMap.set(model.modelId, {
          tokens: (existing?.tokens || 0) + model.tokens,
          iconUrl: model.iconUrl || '',
        });
      }
    });
  });
  return Array.from(modelTokenMap.entries())
    .sort((a, b) => b[1].tokens - a[1].tokens)
    .map(([modelId, data]) => ({ modelId, iconUrl: data.iconUrl }));
});

// 计算属性：模型颜色映射（保持一致性）
const modelColors = computed(() => {
  const baseColors = [
    '#3a4de9',
    '#6a5acd',
    '#9370db',
    '#8a2be2',
    '#9932cc',
    '#ba55d3',
    '#da70d6',
    '#ee82ee',
    '#dda0dd',
    '#ff00ff',
    '#667eea',
    '#764ba2',
    '#f093fb',
    '#f5576c',
    '#4facfe',
    '#00f2fe',
    '#43e97b',
    '#38f9d7',
    '#fa709a',
    '#fee140',
    '#4361ee',
    '#3a0ca3',
    '#7209b7',
    '#f72585',
    '#4cc9f0',
  ];
  const colorMap: Record<string, string> = {};

  // 先为近24小时数据的模型分配颜色
  hourlyModels.value.forEach(({ modelId }, index) => {
    if (!colorMap[modelId]) {
      colorMap[modelId] = baseColors[index % baseColors.length];
    }
  });

  // 为今日模型数据中没有颜色的模型分配颜色
  let colorIndex = hourlyModels.value.length;
  todayModelUsageData.value.forEach((item: any) => {
    if (!colorMap[item.modelId]) {
      colorMap[item.modelId] = baseColors[colorIndex % baseColors.length];
      colorIndex++;
    }
  });

  return colorMap;
});

// 计算属性：模型图标URL映射
const modelIconUrls = computed(() => {
  const iconMap: Record<string, string> = {};
  hourlyModels.value.forEach(({ modelId, iconUrl }) => {
    iconMap[modelId] = iconUrl;
  });
  return iconMap;
});

// 计算属性：今日模型数据的图标映射
const todayModelIcons = computed(() => {
  const iconMap: Record<string, string> = {};
  todayModelUsageData.value.forEach((item: any) => {
    iconMap[item.modelId] = item.iconUrl || '';
  });
  return iconMap;
});

// 获取可选择的Token列表
async function fetchTokenOptions() {
  try {
    tokenOptionsLoading.value = true;
    const res = await getSelectableTokenInfo();
    if (res.data) {
      // 不再过滤禁用的token，全部显示
      tokenOptions.value = res.data;
    }
  }
  catch (error) {
    console.error('获取API密钥列表失败:', error);
    ElMessage.error('获取TAPI密钥列表失败');
  }
  finally {
    tokenOptionsLoading.value = false;
  }
}

// Token选择变化
function handleTokenChange() {
  // 切换 token 时重置近七天数据状态
  showLast7DaysChart.value = false;
  usageData.value = [];
  totalTokens.value = 0;
  // 如果当前是7天视图，切换回24小时视图
  if (currentPeriodView.value === '7d') {
    currentPeriodView.value = '24h';
  }
  fetchUsageData();
}

// 切换时间范围视图（24小时/7天）
function togglePeriodView() {
  if (currentPeriodView.value === '24h') {
    // 切换到7天视图
    currentPeriodView.value = '7d';
    if (!showLast7DaysChart.value) {
      fetchLast7DaysData();
    } else {
      // 使用 nextTick 确保 DOM 更新后再渲染图表
      nextTick(() => {
        // 确保 lineChart 实例已初始化
        if (!lineChartInstance && lineChart.value) {
          lineChartInstance = echarts.init(lineChart.value);
        }
        updateLineChart();
        // 延迟调用 resize 确保容器尺寸正确
        setTimeout(() => {
          lineChartInstance?.resize();
        }, 100);
      });
    }
  } else {
    // 切换回24小时视图
    currentPeriodView.value = '24h';
    // 使用 nextTick 确保 DOM 更新后再渲染图表
    nextTick(() => {
      updateHourlyBarChart();
      setTimeout(() => {
        hourlyBarChartInstance?.resize();
      }, 100);
    });
  }
}

// 获取用量数据（不包含近七天数据）
async function fetchUsageData() {
  loading.value = true;
  try {
    const tokenId = selectedTokenId.value || undefined;
    const [res2, res3, res4] = await Promise.all([
      getModelTokenUsage(tokenId),
      getLast24HoursTokenUsage(tokenId),
      getTodayModelUsage(tokenId),
    ]);

    modelUsageData.value = res2.data || [];
    hourlyUsageData.value = res3.data || [];
    todayModelUsageData.value = res4.data || [];

    updateCharts();
  }
  catch (error) {
    console.error('获取用量数据失败:', error);
    ElMessage.error('获取用量数据失败');
  }
  finally {
    loading.value = false;
  }
}

// 单独加载近七天数据
async function fetchLast7DaysData() {
  loadingLast7Days.value = true;
  try {
    const tokenId = selectedTokenId.value || undefined;
    const res = await getLast7DaysTokenUsage(tokenId);

    usageData.value = res.data || [];
    totalTokens.value = usageData.value.reduce((sum, item) => sum + item.tokens, 0);

    showLast7DaysChart.value = true;
    // 使用 nextTick 确保 DOM 更新后再渲染图表
    nextTick(() => {
      // 确保 lineChart 实例已初始化
      if (!lineChartInstance && lineChart.value) {
        lineChartInstance = echarts.init(lineChart.value);
      }
      updateLineChart();
      // 延迟调用 resize 确保容器尺寸正确
      setTimeout(() => {
        lineChartInstance?.resize();
      }, 100);
    });
  }
  catch (error) {
    console.error('获取近七天数据失败:', error);
    ElMessage.error('获取近七天数据失败');
  }
  finally {
    loadingLast7Days.value = false;
  }
}

// 初始化图表
function initCharts() {
  if (lineChart.value) {
    lineChartInstance = echarts.init(lineChart.value);
  }
  if (pieChart.value) {
    pieChartInstance = echarts.init(pieChart.value);
  }
  if (barChart.value) {
    barChartInstance = echarts.init(barChart.value);
  }
  if (hourlyBarChart.value) {
    hourlyBarChartInstance = echarts.init(hourlyBarChart.value);
  }

  window.addEventListener('resize', resizeCharts);
}

// 更新图表数据
function updateCharts() {
  updateLineChart();
  updatePieChart();
  updateBarChart();
  updateHourlyBarChart(); // 新增：更新近24小时柱状图
}

// 更新折线图
function updateLineChart() {
  if (!lineChartInstance)
    return;

  const dates = usageData.value.map((item) => {
    const date = new Date(item.date);
    return `${date.getMonth() + 1}月${date.getDate()}日`;
  });

  const tokens = usageData.value.map(item => item.tokens);

  const isMobile = window.innerWidth < 768;

  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: '{b}<br/>用量: {c} ',
      confine: true,
      position(point: any, params: any, dom: any, rect: any, size: any) {
        if (isMobile) {
          return ['50%', '10%'];
        }
        return null;
      },
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: dates,
      axisLabel: {
        // rotate: 45,
      },
    },
    yAxis: {
      type: 'value',
      name: 'Token用量',
      axisLine: {
        show: true,
      },
    },
    series: [{
      data: tokens,
      type: 'line',
      smooth: true,
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(58, 77, 233, 0.8)' },
          { offset: 1, color: 'rgba(58, 77, 233, 0.1)' },
        ]),
      },
      itemStyle: {
        color: '#3a4de9',
      },
      lineStyle: {
        width: 3,
      },
      symbolSize: 8,
    }],
  };

  lineChartInstance.setOption(option);
}

// 更新饼图 - 动态适应数据量
function updatePieChart() {
  if (!pieChartInstance)
    return;

  // 空数据状态
  if (modelUsageData.value.length === 0) {
    const emptyOption = {
      graphic: [
        {
          type: 'group',
          left: 'center',
          top: 'center',
          children: [
            {
              type: 'circle',
              shape: {
                r: 80,
              },
              style: {
                fill: '#f5f7fa',
                stroke: '#e9ecef',
                lineWidth: 2,
              },
            },
            {
              type: 'text',
              style: {
                text: '📊',
                fontSize: 48,
                x: -24,
                y: -40,
              },
            },
            {
              type: 'text',
              style: {
                text: '暂无数据',
                fontSize: 18,
                fontWeight: 'bold',
                fill: '#909399',
                x: -36,
                y: 20,
              },
            },
            {
              type: 'text',
              style: {
                text: '还没有模型使用记录',
                fontSize: 14,
                fill: '#c0c4cc',
                x: -70,
                y: 50,
              },
            },
          ],
        },
      ],
    };
    pieChartInstance.setOption(emptyOption, true);
    return;
  }

  const data = modelUsageData.value.map(item => ({
    name: item.model,
    value: item.tokens,
  }));

  const isManyItems = data.length > 8;
  const isSmallContainer = pieContainerSize.width.value < 600;
  const isMobile = window.innerWidth < 768;

  const option = {
    graphic: [], // 清空graphic配置
    tooltip: {
      trigger: 'item',
      formatter: isMobile
        ? (params: any) => {
            // 移动端简化显示
            return `${params.name}<br/>占比: ${params.percent}%`;
          }
        : '{a} <br/>{b}: {c} tokens ({d}%)',
      confine: true,
      textStyle: {
        fontSize: isMobile ? 11 : 14,
      },
      padding: isMobile ? [5, 8] : [10, 15],
      position(point: any, params: any, dom: any, rect: any, size: any) {
        if (isMobile) {
          // 移动端固定在顶部中央
          return ['50%', '10%'];
        }
        // 桌面端自动定位
        return null;
      },
    },
    legend: {
      show: false, // 隐藏图例，使用标签线代替
    },
    series: [
      {
        name: '模型用量',
        type: 'pie',
        radius: isMobile ? ['40%', '60%'] : ['50%', '70%'],
        center: ['50%', '50%'],
        avoidLabelOverlap: true,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2,
        },
        label: {
          show: true,
          position: isMobile ? 'inside' : 'outside',
          formatter: isMobile ? '{d}%' : '{b}: {d}%',
          fontSize: isMobile ? 11 : 13,
          fontWeight: 600,
          color: isMobile ? '#fff' : '#333',
        },
        emphasis: {
          label: {
            show: true,
            fontSize: isMobile ? 13 : 16,
            fontWeight: 'bold',
          },
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.3)',
          },
        },
        labelLine: {
          show: !isMobile,
          length: 15,
          length2: 10,
          lineStyle: {
            width: 1.5,
          },
        },
        data,
      },
    ],
  };

  pieChartInstance.setOption(option, true);
}

// 更新柱状图 - 动态适应数据量
function updateBarChart() {
  if (!barChartInstance)
    return;

  // 空数据状态
  if (modelUsageData.value.length === 0) {
    const emptyOption = {
      graphic: [
        {
          type: 'group',
          left: 'center',
          top: 'center',
          children: [
            {
              type: 'rect',
              shape: {
                width: 160,
                height: 160,
                r: 12,
              },
              style: {
                fill: '#f5f7fa',
                stroke: '#e9ecef',
                lineWidth: 2,
              },
              left: -80,
              top: -80,
            },
            {
              type: 'text',
              style: {
                text: '📈',
                fontSize: 48,
                x: -24,
                y: -40,
              },
            },
            {
              type: 'text',
              style: {
                text: '暂无数据',
                fontSize: 18,
                fontWeight: 'bold',
                fill: '#909399',
                x: -36,
                y: 20,
              },
            },
            {
              type: 'text',
              style: {
                text: '还没有模型使用记录',
                fontSize: 14,
                fill: '#c0c4cc',
                x: -70,
                y: 50,
              },
            },
          ],
        },
      ],
    };
    barChartInstance.setOption(emptyOption, true);
    return;
  }

  const models = modelUsageData.value.map(item => item.model);
  const tokens = modelUsageData.value.map(item => item.tokens);

  const isManyItems = models.length > 10;
  const isSmallContainer = barContainerSize.width.value < 600;
  const isMobile = window.innerWidth < 768;

  const option = {
    graphic: [], // 清空graphic配置
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
      formatter: '{b}<br/>用量: {c} tokens',
      confine: true,
      position(point: any, params: any, dom: any, rect: any, size: any) {
        if (isMobile) {
          // 移动端固定在顶部中央
          return ['50%', '10%'];
        }
        // 桌面端自动定位
        return null;
      },
    },
    grid: {
      left: isMobile ? '5%' : '3%',
      right: isMobile ? '5%' : '4%',
      bottom: '3%',
      top: '3%',
      containLabel: true,
    },
    xAxis: {
      type: 'value',
      name: isMobile ? '' : 'Token用量',
      nameTextStyle: {
        fontSize: isMobile ? 11 : 12,
      },
      axisLabel: {
        fontSize: isMobile ? 10 : 12,
      },
    },
    yAxis: {
      type: 'category',
      data: models,
      axisLabel: {
        interval: 0,
        fontSize: isMobile ? 10 : Math.max(10, 14 - Math.floor(models.length / 10)),
        formatter(value: string) {
          const maxLength = isMobile ? 8 : (isSmallContainer ? 10 : 20);
          if (value.length > maxLength) {
            return `${value.substring(0, maxLength - 2)}...`;
          }
          return value;
        },
      },
    },
    series: [
      {
        name: '用量',
        type: 'bar',
        barWidth: isManyItems ? '60%' : '80%',
        data: tokens,
        itemStyle: {
          color(params: any) {
            const colorList = [
              '#3a4de9',
              '#6a5acd',
              '#9370db',
              '#8a2be2',
              '#9932cc',
              '#ba55d3',
              '#da70d6',
              '#ee82ee',
              '#dda0dd',
              '#ff00ff',
            ];
            return colorList[params.dataIndex % colorList.length];
          },
          borderRadius: [0, 4, 4, 0],
        },
        label: {
          show: !isMobile,
          position: 'right',
          formatter: '{c} ',
          fontSize: isMobile ? 10 : 12,
        },
      },
    ],
  };

  barChartInstance.setOption(option, true);
}

// 更新近24小时每小时Token消耗柱状图（堆叠柱状图）
function updateHourlyBarChart() {
  if (!hourlyBarChartInstance)
    return;

  // 空数据状态
  if (hourlyUsageData.value.length === 0 || hourlyModels.value.length === 0) {
    const emptyOption = {
      graphic: [
        {
          type: 'group',
          left: 'center',
          top: 'center',
          children: [
            {
              type: 'rect',
              shape: {
                width: 160,
                height: 160,
                r: 12,
              },
              style: {
                fill: '#f5f7fa',
                stroke: '#e9ecef',
                lineWidth: 2,
              },
              left: -80,
              top: -80,
            },
            {
              type: 'text',
              style: {
                text: '📊',
                fontSize: 48,
                x: -24,
                y: -40,
              },
            },
            {
              type: 'text',
              style: {
                text: '暂无数据',
                fontSize: 18,
                fontWeight: 'bold',
                fill: '#909399',
                x: -36,
                y: 20,
              },
            },
            {
              type: 'text',
              style: {
                text: '近24小时暂无使用记录',
                fontSize: 14,
                fill: '#c0c4cc',
                x: -80,
                y: 50,
              },
            },
          ],
        },
      ],
    };
    hourlyBarChartInstance.setOption(emptyOption, true);
    return;
  }

  const hours = hourlyUsageData.value.map((item) => {
    const date = new Date(item.hour);
    return `${date.getHours().toString().padStart(2, '0')}:00`;
  });
  const totalTokens = hourlyUsageData.value.map(item => item.totalTokens);

  const isMobile = window.innerWidth < 768;

  // 堆叠柱状图强调样式
  const emphasisStyle = {
    itemStyle: {
      shadowBlur: 10,
      shadowOffsetX: 0,
      shadowColor: 'rgba(0, 0, 0, 0.3)',
    },
  };

  // 构建每个模型的数据系列（堆叠柱状图）
  const series = hourlyModels.value.map(({ modelId }, index) => {
    const data = hourlyUsageData.value.map((hour) => {
      const modelData = hour.modelBreakdown?.find((m: any) => m.modelId === modelId);
      return modelData?.tokens || 0;
    });

    return {
      name: modelId,
      type: 'bar',
      stack: 'total', // 所有系列堆叠在一起
      emphasis: emphasisStyle,
      data,
      itemStyle: {
        color: modelColors.value[modelId],
        borderRadius: [0, 0, 0, 0], // 堆叠柱状图不需要圆角
        borderWidth: 0,
      },
      label: {
        show: false, // 堆叠柱状图不显示标签
      },
    };
  });

  const option = {
    graphic: [],
    calculable: true,
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
        label: {
          show: true,
        },
      },
      formatter: (params: any) => {
        if (!params || params.length === 0)
          return '';
        const hour = params[0].axisValue;

        // 过滤出有数据的模型并按token使用量降序
        const activeParams = params
          .filter((p: any) => p.value > 0)
          .sort((a: any, b: any) => b.value - a.value);

        if (activeParams.length === 0)
          return `<div style="padding: 8px 12px; font-size: 13px; color: #999;">${hour}<br/>暂无数据</div>`;

        // 计算总token
        const totalTokens = activeParams.reduce((sum: number, p: any) => sum + p.value, 0);

        let result = `<div style="margin-bottom: 10px; padding-bottom: 8px; border-bottom: 1px solid #eee;">
          <div style="font-size: 14px; font-weight: bold; color: #333;">${hour}</div>
          <div style="font-size: 12px; color: #999; margin-top: 2px;">总计: ${totalTokens.toLocaleString()} tokens</div>
        </div>`;

        // 限制显示的模型数量（最多显示前8个）
        const maxDisplay = 8;
        const displayParams = activeParams.slice(0, maxDisplay);

        displayParams.forEach((param: any, index: number) => {
          const percent = ((param.value / totalTokens) * 100).toFixed(1);
          result += `<div style="display: flex; align-items: center; justify-content: space-between; gap: ${isMobile ? 12 : 20}px; margin-bottom: ${index === displayParams.length - 1 && activeParams.length > maxDisplay ? 6 : 4}px;">
            <span style="display: flex; align-items: center;">
              <span style="display: inline-block; width: 10px; height: 10px; border-radius: 2px; background: ${param.color}; margin-right: 8px;"></span>
              <span style="font-size: ${isMobile ? 11 : 12}px; color: #555;">${param.seriesName}</span>
            </span>
            <span style="display: flex; align-items: center; gap: 8px;">
              <span style="font-size: ${isMobile ? 11 : 12}px; font-weight: 600; color: #333;">${param.value.toLocaleString()}</span>
              <span style="font-size: ${isMobile ? 10 : 11}px; color: #999;">${percent}%</span>
            </span>
          </div>`;
        });

        // 如果有更多模型，显示提示
        if (activeParams.length > maxDisplay) {
          result += `<div style="margin-top: 6px; padding-top: 6px; border-top: 1px dashed #eee; font-size: 11px; color: #999; text-align: center;">
            还有 ${activeParams.length - maxDisplay} 个模型未显示
          </div>`;
        }

        return result;
      },
      confine: true,
      backgroundColor: 'rgba(255, 255, 255, 0.98)',
      borderColor: '#e9ecef',
      borderWidth: 1,
      borderRadius: 8,
      padding: [12, 16],
      textStyle: {
        fontSize: 13,
        color: '#333',
      },
      position(point: any, params: any, dom: any, rect: any, size: any) {
        if (isMobile) {
          return ['50%', '10%'];
        }
        return null;
      },
    },
    toolbox: {
      show: true,
      feature: {
        magicType: {
          type: ['stack', 'line'],
          title: {
            stack: '切换为堆叠',
            line: '切换为折线',
          },
        },
        dataView: {
          title: '数据视图',
          readOnly: true,
        },
        restore: {
          show: true,
          title: '还原',
        },
        saveAsImage: {
          show: true,
          title: '保存为图片',
          pixelRatio: 2,
        },
      },
      right: 15,
      top: 5,
      itemSize: 18,
      iconStyle: {
        borderColor: '#667eea',
        borderWidth: 2,
      },
      emphasis: {
        iconStyle: {
          borderColor: '#764ba2',
        },
      },
      tooltip: {
        show: true,
        position: 'bottom',
        formatter: (param: any) => {
          return param.title;
        },
        textStyle: {
          fontSize: 11,
        },
      },
    },
    brush: {
      toolbox: ['lineX', 'keep', 'clear'],
      xAxisIndex: 0,
      brushLink: 'all',
      throttleType: 'debounce',
      throttleDelay: 300,
      removeOnClick: true,
      brushType: false,
      inBrush: {
        opacity: 1,
      },
      outOfBrush: {
        opacity: 0.15,
      },
      brushStyle: {
        borderWidth: 1,
        color: 'rgba(102, 126, 234, 0.15)',
        borderColor: '#667eea',
      },
    },
    legend: {
      show: true,
      type: hourlyModels.value.length > 8 || isMobile ? 'scroll' : 'plain',
      top: isMobile ? '0%' : '3%',
      left: 'center',
      itemWidth: 14,
      itemHeight: 10,
      itemGap: isMobile ? 8 : 10,
      textStyle: {
        fontSize: isMobile ? 10 : 12,
        color: '#666',
      },
      data: hourlyModels.value.map(({ modelId }) => ({
        name: modelId,
        icon: 'rect',
      })),
      pageTextStyle: {
        color: '#999',
      },
      pageIconColor: '#667eea',
      pageIconInactiveColor: '#ccc',
      pageButtonItemGap: 5,
    },
    grid: {
      top: '12%',
      left: '1%',
      right: isMobile ? '8%' : '3%',
      bottom: '10%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: hours,
      name: '时间',
      nameTextStyle: {
        fontSize: isMobile ? 11 : 12,
        color: '#999',
        padding: [0, 0, 0, 0],
      },
      axisLine: {
        show: true,
        lineStyle: {
          color: '#e9ecef',
          width: 1,
        },
      },
      axisTick: {
        show: false,
      },
      axisLabel: {
        interval: isMobile ? 3 : 0,
        rotate: isMobile ? 45 : 0,
        fontSize: isMobile ? 10 : 12,
        color: '#666',
        fontFamily: 'monospace',
      },
      splitLine: {
        show: false,
      },
      splitArea: {
        show: false,
      },
    },
    yAxis: {
      type: 'value',
      name: 'Token用量',
      nameTextStyle: {
        fontSize: isMobile ? 11 : 12,
        color: '#999',
        padding: [0, 0, 0, 0],
      },
      axisLine: {
        show: true,
        lineStyle: {
          color: '#e9ecef',
          width: 1,
        },
      },
      axisTick: {
        show: false,
      },
      axisLabel: {
        fontSize: isMobile ? 10 : 12,
        color: '#666',
        formatter: (value: number) => {
          if (value >= 1000000)
            return `${(value / 1000000).toFixed(1)}M`;
          if (value >= 1000)
            return `${(value / 1000).toFixed(0)}K`;
          return value.toString();
        },
      },
      splitLine: {
        lineStyle: {
          color: '#f0f0f0',
          type: 'dashed',
          width: 1,
        },
      },
    },
    series,
  };

  hourlyBarChartInstance.setOption(option, true);
}

// 调整图表大小
function resizeCharts() {
  lineChartInstance?.resize();
  pieChartInstance?.resize();
  barChartInstance?.resize();
  hourlyBarChartInstance?.resize();
}

// 切换全屏
function toggleFullscreen() {
  isFullscreen.value = !isFullscreen.value;
  nextTick(() => {
    resizeCharts();
  });
}

// 监听容器大小变化
watch([pieContainerSize.width, barContainerSize.width], () => {
  updatePieChart();
  updateBarChart();
});

onMounted(() => {
  initCharts();
  fetchTokenOptions();
  fetchUsageData();
});

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeCharts);
  lineChartInstance?.dispose();
  pieChartInstance?.dispose();
  barChartInstance?.dispose();
  hourlyBarChartInstance?.dispose();
});
</script>

<template>
  <div
    ref="usageStatisticsRef"
    class="usage-statistics"
    :class="{ 'fullscreen-mode': isFullscreen }"
  >
    <div class="header">
      <h2>
        <el-icon><PieChart /></el-icon>
        Token用量统计
      </h2>
      <div class="header-actions">
        <el-select
          v-model="selectedTokenId"
          placeholder="选择API密钥"
          clearable
          filterable
          :loading="tokenOptionsLoading"
          class="token-selector"
          @change="handleTokenChange"
        >
          <el-option label="全部Token" value="">
            <div class="token-option">
              <el-icon class="option-icon all-icon">
                <i-ep-folder-opened />
              </el-icon>
              <span class="option-label">全部Token</span>
            </div>
          </el-option>
          <el-option
            v-for="token in tokenOptions"
            :key="token.tokenId"
            :label="token.name"
            :value="token.tokenId"
            :disabled="token.isDisabled"
          >
            <div class="token-option" :class="{ 'disabled-token': token.isDisabled }">
              <el-icon class="option-icon" :class="{ 'disabled-icon': token.isDisabled }">
                <i-ep-key />
              </el-icon>
              <span class="option-label">{{ token.name }}</span>
              <el-tag v-if="token.isDisabled" type="info" size="small" effect="plain" class="disabled-tag">
                已禁用
              </el-tag>
            </div>
          </el-option>
        </el-select>
        <el-button
          v-if="false"
          :icon="FullScreen"
          circle
          plain
          size="small"
          @click="toggleFullscreen"
        />
      </div>
    </div>

    <!-- 时间范围图表（可切换：24小时/7天） -->
    <el-card v-loading="currentPeriodView === '7d' ? loadingLast7Days : loading" class="chart-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">
            {{ currentPeriodView === '24h' ? '⏰ 近24小时每小时Token消耗' : '📊 近七天每日Token消耗量' }}{{ selectedTokenId ? ` (${selectedTokenName})` : '' }}
          </span>
          <!-- 切换按钮 -->
          <div class="period-toggle-group">
            <el-button
              :type="currentPeriodView === '24h' ? 'primary' : 'default'"
              size="small"
              @click="togglePeriodView"
            >
              近24小时
            </el-button>
            <el-button
              :type="currentPeriodView === '7d' ? 'primary' : 'default'"
              size="small"
              @click="togglePeriodView"
            >
              近7天
            </el-button>
          </div>
        </div>
      </template>
      <!-- 24小时视图 -->
      <div v-show="currentPeriodView === '24h'" class="chart-container">
        <div ref="hourlyBarChart" class="chart hourly-bar-chart" />
      </div>
      <!-- 7天视图 -->
      <div v-show="currentPeriodView === '7d'" class="chart-container">
        <div v-if="!showLast7DaysChart" class="load-chart-inline">
          <div class="load-inline-content">
            <div class="load-inline-icon">📊</div>
            <div class="load-inline-text">该功能查询性能消耗较大</div>
            <el-button type="primary" @click="fetchLast7DaysData" :loading="loadingLast7Days">
              加载近七天数据
            </el-button>
          </div>
        </div>
        <div v-else ref="lineChart" class="chart line-chart" />
      </div>
    </el-card>

    <!-- 今日各模型使用量卡片列表 -->
    <el-card v-loading="loading" class="chart-card today-model-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">📋 今日各模型使用量统计(凌晨零点至现在){{ selectedTokenId ? ` (${selectedTokenName})` : '' }}</span>
          <el-tag v-if="todayModelUsageData.length > 0" type="success" effect="plain">
            共 {{ todayModelUsageData.length }} 个模型
          </el-tag>
        </div>
      </template>
      <div class="today-model-cards">
        <div v-if="todayModelUsageData.length === 0" class="empty-state">
          <div class="empty-icon">
            📊
          </div>
          <div class="empty-text">
            暂无数据
          </div>
          <div class="empty-hint">
            今日暂无模型使用记录
          </div>
        </div>
        <div v-else class="model-cards-grid">
          <div
            v-for="item in todayModelUsageData"
            :key="item.modelId"
            class="model-card"
            :style="{ borderColor: modelColors[item.modelId] || '#e9ecef' }"
          >
            <div class="model-card-header">
              <div class="model-icon-wrapper">
                <img
                  v-if="item.iconUrl"
                  :src="item.iconUrl"
                  :alt="item.modelId"
                  class="model-logo"
                  @error="(e) => { (e.target as HTMLImageElement).style.display = 'none'; (e.target as HTMLImageElement).nextElementSibling?.classList.remove('fallback-icon'); }"
                >
                <div v-else class="model-logo-fallback" :style="{ background: modelColors[item.modelId] || '#667eea' }">
                  {{ item.modelId.charAt(0).toUpperCase() }}
                </div>
              </div>
              <div class="model-info">
                <div class="model-name" :title="item.modelId">
                  {{ item.modelId }}
                </div>
                <div class="model-usage-count">
                  <el-icon><i-ep-data-analysis /></el-icon>
                  使用 {{ item.usageCount }} 次
                </div>
              </div>
            </div>
            <div class="model-card-footer">
              <div class="token-info">
                <span class="token-label">Token消耗</span>
                <span class="token-value" :style="{ color: modelColors[item.modelId] || '#667eea' }">
                  {{ item.totalTokens.toLocaleString() }}
                </span>
              </div>
              <div class="token-chart-mini">
                <div
                  class="token-bar"
                  :style="{
                    width: `${Math.min(100, (item.totalTokens / Math.max(...todayModelUsageData.map((d: any) => d.totalTokens))) * 100)}%`,
                    background: `linear-gradient(90deg, ${modelColors[item.modelId] || '#667eea'} 0%, ${modelColors[item.modelId] || '#764ba2'} 100%)`,
                  }"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 各模型Token消耗占比和总Token消耗量并排显示 -->
    <div class="charts-row">
      <el-card v-loading="loading" class="chart-card half-width">
        <template #header>
          <div class="card-header">
            <span class="card-title">🥧 各模型总Token消耗占比{{ selectedTokenId ? ` (${selectedTokenName})` : '' }}</span>
          </div>
        </template>
        <div class="chart-container">
          <div ref="pieChart" class="chart pie-chart" />
        </div>
      </el-card>

      <el-card v-loading="loading" class="chart-card half-width">
        <template #header>
          <div class="card-header">
            <span class="card-title">📈 各模型总Token消耗量{{ selectedTokenId ? ` (${selectedTokenName})` : '' }}</span>
          </div>
        </template>
        <div class="chart-container">
          <div ref="barChart" class="chart bar-chart" />
        </div>
      </el-card>
    </div>
  </div>
</template>

<style scoped>
.usage-statistics {
  position: relative;
  transition: all 0.3s ease;
  overflow-y: auto;
}

.usage-statistics:hover {
}

.usage-statistics.fullscreen-mode {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 2000;
  padding: 30px;
  overflow-y: auto;
  border-radius: 0;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.token-selector {
  width: 240px;
}

.token-option {
  display: flex;
  align-items: center;
  gap: 8px;
  width: 100%;

  &.disabled-token {
    opacity: 0.6;

    .option-label {
      text-decoration: line-through;
    }
  }
}

.option-icon {
  color: #667eea;
  font-size: 16px;
  flex-shrink: 0;

  &.all-icon {
    color: #409eff;
  }

  &.disabled-icon {
  }
}

.option-label {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.disabled-tag {
  margin-left: auto;
  flex-shrink: 0;
  font-size: 11px;
  padding: 0 6px;
  height: 18px;
  line-height: 18px;
}

.header h2 {
  display: flex;
  align-items: center;
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #333;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.header .el-icon {
  margin-right: 10px;
  color: #3a4de9;
  font-size: 28px;
}

.chart-card {
  margin-bottom: 30px;
  border-radius: 16px;
  overflow: hidden;
}

.chart-card:hover {
  transform: translateY(-4px);
}

/* 图表行布局：两个图表并排显示 */
.charts-row {
  display: flex;
  gap: 20px;
  margin-bottom: 30px;
}

.charts-row .chart-card {
  flex: 1;
  margin-bottom: 0;
}

.charts-row .half-width {
  width: 50%;
}

/* 时间范围切换按钮组 */
.period-toggle-group {
  display: flex;
  gap: 8px;
  align-items: center;
}

.period-toggle-group .el-button {
  padding: 6px 16px;
  font-size: 13px;
}

/* 内联加载提示 */
.load-chart-inline {
  min-height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.load-inline-content {
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
}

.load-inline-icon {
  font-size: 48px;
}

.load-inline-text {
  font-size: 14px;
  color: #999;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: 600;
  color: #333;
  padding: 8px 0;
}

.card-title {
  font-size: 18px;
  font-weight: 700;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.chart-container {
  width: 100%;
  padding: 10px;
  background: linear-gradient(135deg, #fafbfc 0%, #f5f6f8 100%);
  border-radius: 12px;
}

.chart {
  width: 100%;
  transition: all 0.3s ease;
}

/* 不同图表类型的默认高度 */
.line-chart {
  height: 350px;
}

.pie-chart {
  height: 400px;
}

.bar-chart {
  height: 450px;
}

.hourly-bar-chart {
  height: 400px;
}

/* 今日模型使用量卡片样式 */
.today-model-card {
  transition: all 0.3s ease;
}

.today-model-cards {
  padding: 10px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 16px;
}

.empty-text {
  font-size: 18px;
  font-weight: 600;
  color: #909399;
  margin-bottom: 8px;
}

.empty-hint {
  font-size: 14px;
  color: #c0c4cc;
}

.model-cards-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 14px;
}

.model-card {
  background: #fff;
  border: 1px solid #e9ecef;
  border-radius: 12px;
  padding: 14px;
  transition: all 0.25s ease;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.03);
}

.model-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  border-color: currentColor;
}

.model-card-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 12px;
}

.model-icon-wrapper {
  width: 40px;
  height: 40px;
  flex-shrink: 0;
}

.model-logo {
  width: 100%;
  height: 100%;
  object-fit: contain;
  border-radius: 8px;
  padding: 2px;
  background: #f8f9fa;
}

.model-logo-fallback {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 8px;
  font-size: 18px;
  font-weight: 600;
  color: #fff;
}

.model-info {
  flex: 1;
  min-width: 0;
}

.model-name {
  font-size: 13px;
  font-weight: 600;
  color: #333;
  margin-bottom: 2px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  line-height: 1.4;
}

.model-usage-count {
  font-size: 11px;
  color: #999;
  display: flex;
  align-items: center;
  gap: 3px;
  line-height: 1.3;
}

.model-card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 10px;
  border-top: 1px solid #f0f0f0;
}

.token-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.token-label {
  font-size: 10px;
  color: #aaa;
  line-height: 1.2;
}

.token-value {
  font-size: 16px;
  font-weight: 700;
  line-height: 1.2;
}

.token-chart-mini {
  flex: 1;
  height: 4px;
  background: #f0f0f0;
  border-radius: 2px;
  overflow: hidden;
  margin-left: 12px;
  align-self: center;
  max-width: 80px;
}

.token-bar {
  height: 100%;
  border-radius: 2px;
  transition: width 0.6s ease;
}

@media (max-width: 768px) {
  .usage-statistics {
    padding: 12px;
  }

  .header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
    margin-bottom: 16px;
    padding-bottom: 12px;
  }

  .header h2 {
    font-size: 18px;
  }

  .header .el-icon {
    font-size: 20px;
  }

  .header-actions {
    width: 100%;
    flex-direction: column;
    gap: 8px;
  }

  .token-selector {
    width: 100% !important;
  }

  .chart-card {
    margin-bottom: 16px;
    border-radius: 12px;
  }

  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
    font-size: 14px;
  }

  .card-title {
    font-size: 14px;
    word-break: break-word;
  }

  .chart-container {
    padding: 8px;
    overflow: hidden;
  }

  /* 移动端图表行垂直排列 */
  .charts-row {
    flex-direction: column;
    gap: 16px;
  }

  .charts-row .half-width {
    width: 100%;
  }

  /* 移动端切换按钮组 */
  .period-toggle-group {
    flex-direction: column;
    gap: 4px;
  }

  .period-toggle-group .el-button {
    padding: 4px 12px;
    font-size: 12px;
  }

  /* 移动端内联加载提示 */
  .load-chart-inline {
    min-height: 280px;
  }

  .load-inline-icon {
    font-size: 40px;
  }

  .load-inline-text {
    font-size: 13px;
  }

  /* 移动端图表高度优化 */
  .line-chart {
    height: 280px !important;
  }

  .pie-chart {
    height: 350px !important;
  }

  .bar-chart {
    height: 400px !important;
  }

  .hourly-bar-chart {
    height: 340px !important;
  }

  .model-cards-grid {
    grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
    gap: 10px;
  }

  .model-card {
    padding: 12px;
  }

  .model-icon-wrapper {
    width: 36px;
    height: 36px;
  }

  .model-logo-fallback {
    font-size: 16px;
  }

  .model-name {
    font-size: 12px;
  }

  .model-usage-count {
    font-size: 10px;
  }

  .token-value {
    font-size: 14px;
  }

  .token-chart-mini {
    max-width: 60px;
    height: 3px;
  }

  .usage-statistics.fullscreen-mode {
    padding: 12px;
  }

  /* Tag 样式优化 */
  :deep(.el-tag) {
    font-size: 11px;
    padding: 2px 6px;
    height: auto;
  }
}

@media (max-width: 480px) {
  .usage-statistics {
    padding: 8px;
  }

  .header h2 {
    font-size: 16px;
  }

  .card-title {
    font-size: 13px;
  }

  /* 超小屏幕图表行垂直排列 */
  .charts-row {
    flex-direction: column;
    gap: 12px;
  }

  .charts-row .half-width {
    width: 100%;
  }

  /* 超小屏幕切换按钮组 */
  .period-toggle-group .el-button {
    padding: 4px 10px;
    font-size: 11px;
  }

  .load-chart-inline {
    min-height: 240px;
  }

  /* 超小屏幕图表高度 */
  .line-chart {
    height: 250px !important;
  }

  .pie-chart {
    height: 320px !important;
  }

  .bar-chart {
    height: 380px !important;
  }

  .hourly-bar-chart {
    height: 300px !important;
  }

  .model-cards-grid {
    grid-template-columns: 1fr;
    gap: 10px;
  }

  .model-card {
    padding: 12px;
  }

  .model-icon-wrapper {
    width: 36px;
    height: 36px;
  }

  .model-logo-fallback {
    font-size: 16px;
  }

  .model-name {
    font-size: 12px;
  }

  .model-usage-count {
    font-size: 10px;
  }

  .token-value {
    font-size: 14px;
  }

  .token-chart-mini {
    max-width: 60px;
    height: 3px;
  }

  .chart-card {
    margin-bottom: 12px;
  }

  .chart-container {
    padding: 6px;
  }
}
</style>
