import React, { useEffect, useRef } from 'react';
import './style.less';

interface TimeSeriesChartProps {
  labels: string[];
  barData1: number[];
  barData2: number[];
}

const TimeSeriesChart: React.FC<TimeSeriesChartProps> = ({ labels, barData1, barData2 }) => {
  const canvasRef = useRef<HTMLCanvasElement>(null);

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;

    const ctx = canvas.getContext('2d');
    if (!ctx) return;

    let animationId: number;
    let progress = 0;

    // 动态计算最大数据值
    const maxDataValue = Math.max(...barData1, ...barData2);

    const draw = () => {
      // 获取设备像素比
      const dpr = window.devicePixelRatio || 1;
      // 设置画布的尺寸
      canvas.width = canvas.clientWidth * dpr;
      canvas.height = canvas.clientHeight * dpr;
      ctx.scale(dpr, dpr);

      // 清除画布
      ctx.clearRect(0, 0, canvas.clientWidth, canvas.clientHeight);

      // 尺寸
      const chartWidth = canvas.clientWidth;
      const chartHeight = canvas.clientHeight;
      const leftPadding = 0;
      const rightPadding = 0;
      const bottomPadding = chartHeight * 0.2;
      const topPadding = chartHeight * 0.1;
      const totalBars = labels.length;
      const barGroupWidth = (chartWidth - leftPadding - rightPadding) / totalBars;
      const barWidth = barGroupWidth / 3.5; // 每个组合两个柱子和一个间隙
      const maxBarHeight = chartHeight - topPadding - bottomPadding;
      const fontSize = chartWidth * 0.02; // 使用相对单位设置字体大小

      // 绘制y轴标签和网格线
      const yLabels = [0, maxDataValue * 0.2, maxDataValue * 0.4, maxDataValue * 0.6, maxDataValue * 0.8, maxDataValue];
      yLabels.forEach(value => {
        const y = chartHeight - bottomPadding - (value / maxDataValue) * maxBarHeight;
        // 网格线
        ctx.strokeStyle = '#3e4b5b';
        ctx.lineWidth = 1;
        ctx.beginPath();
        ctx.moveTo(leftPadding, y);
        ctx.lineTo(chartWidth - rightPadding, y);
        ctx.stroke();
        // y轴标签
        ctx.fillStyle = '#FFFFFF';
        ctx.textAlign = 'right';
        ctx.font = `${fontSize * 0.6}px Arial`;
        ctx.fillText(`${Math.round(value)}`, leftPadding - 10, y + 3);
      });

      // 绘制柱形图
      const drawBar = (value: number, index: number, barOffset: number, colorStart: string, colorEnd: string) => {
        const barHeight = (value / maxDataValue) * maxBarHeight * progress;
        const x = leftPadding + index * barGroupWidth + barWidth * barOffset;
        const y = chartHeight - bottomPadding - barHeight;

        // 检查 x, y, barHeight 是否为有限数字
        if (!isFinite(x) || !isFinite(y) || !isFinite(barHeight)) {
          console.error('Invalid value for gradient creation:', { x, y, barHeight });
          return;
        }

        // 创建渐变颜色
        const gradient = ctx.createLinearGradient(x, y, x, y + barHeight);
        gradient.addColorStop(0, colorStart);
        gradient.addColorStop(1, colorEnd);

        // 绘制柱子
        ctx.fillStyle = gradient;
        ctx.fillRect(x, y, barWidth, barHeight);
        ctx.fillStyle = '#FFFFFF';
        ctx.textAlign = 'center';
        ctx.font = `${fontSize * 0.5}px Arial`;
        ctx.fillText(`${value}`, x + barWidth / 2, y - 10);
      };

      barData1.forEach((value, index) => {
        drawBar(value, index, 0.25, 'rgba(77, 182, 225, 1)', 'rgba(77, 182, 225, 0.2)');
      });

      barData2.forEach((value, index) => {
        drawBar(value, index, 1.25, 'rgba(255, 215, 0, 1)', 'rgba(255, 215, 0, 0.2)');
      });

      // 绘制x轴标签
      labels.forEach((label, index) => {
        const x = leftPadding + index * barGroupWidth + barGroupWidth / 2;
        ctx.fillStyle = '#FFFFFF';
        ctx.textAlign = 'center';
        ctx.font = `${fontSize * 0.7}px Arial`;
        ctx.fillText(label, x, chartHeight - bottomPadding + 15);
      });

      // 动画效果
      if (progress < 1) {
        progress += 0.02;
        animationId = requestAnimationFrame(draw);
      } else {
        cancelAnimationFrame(animationId);
      }
    };

    const resizeCanvas = () => {
      const canvasWidth = canvas.clientWidth;
      const canvasHeight = canvas.clientHeight;
      canvas.width = canvasWidth;
      canvas.height = canvasHeight;
      draw();
    };

    resizeCanvas();
    window.addEventListener('resize', resizeCanvas);
    animationId = requestAnimationFrame(draw);
    return () => {
      window.removeEventListener('resize', resizeCanvas);
      cancelAnimationFrame(animationId);
    };
  }, [labels, barData1, barData2]);

  return <canvas ref={canvasRef} className="time-series-chart" />;
};

export default TimeSeriesChart;
