import React, { useRef, useEffect, useState, useCallback } from 'react';

interface WindowData {
    windowNo: string;
    noDrugCount: number;
    noCompleteCount: number;
}

interface BarChartData {
    noDrugCount: number;
    noCompleteCount: number;
    windowList: WindowData[];
}

interface BarChartProps {
    data: BarChartData;
}

const BarChartZuhe: React.FC<BarChartProps> = ({ data }) => {
    const canvasRef = useRef<HTMLCanvasElement>(null);
    const containerRef = useRef<HTMLDivElement>(null);
    const [maxValue, setMaxValue] = useState(0);
    const [animationProgress, setAnimationProgress] = useState(0);

    // 默认数据，用于防止空数据报错
    const defaultData: BarChartData = {
        noDrugCount: 0,
        noCompleteCount: 0,
        windowList: [],
    };


    const safeData = data || defaultData;

    // 动画启动
    const startAnimation = () => {
        let progress = 0;

        const step = () => {
            progress += 0.02;
            if (progress <= 1) {
                setAnimationProgress(progress);
                requestAnimationFrame(step);
            }
        };

        requestAnimationFrame(step);
    };

    // 绘制图表
    const drawChart = useCallback(() => {
        const canvas = canvasRef.current;
        const container = containerRef.current;

        if (!canvas || !container || !Array.isArray(safeData.windowList)) return;

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

        const width = container.clientWidth;
        const height = container.clientHeight;

        canvas.width = width;
        canvas.height = height;

        const leftMargin = width * 0.2;
        const rightMargin = width * 0.2;
        const chartWidth = width - leftMargin - rightMargin;
        const groupWidth = chartWidth / safeData.windowList.length;
        const barWidth = groupWidth / 6;

        const chartHeight = height * 0.8;
        const chartBottom = height * 0.83;
        const chartTop = height * 0.1;

        ctx.clearRect(0, 0, width, height);

        const fontSize = Math.min(width, height) * 0.03;
        ctx.font = `${fontSize}px Arial`;

        // 绘制网格线
        const yStep = maxValue / 5;
        ctx.strokeStyle = '#3e4b5b';
        ctx.lineWidth = 1;
        ctx.fillStyle = '#FFF';
        ctx.textAlign = 'right';

        for (let i = 0; i <= 5; i++) {
            const y = chartBottom - (i * chartHeight) / 5;
            ctx.beginPath();
            ctx.moveTo(leftMargin, y);
            ctx.lineTo(width - rightMargin, y);
            ctx.stroke();
            ctx.fillText(((i * yStep).toFixed(2)).toString(), leftMargin - 10, y + fontSize / 2);
        }

        // 绘制柱状图
        safeData.windowList.forEach((group, index) => {
            const x = leftMargin + index * groupWidth + groupWidth / 4;

            const noDrugCount = group.noDrugCount || 0;
            const noCompleteCount = group.noCompleteCount || 0;

            const barHeight1 = maxValue > 0 ? (noDrugCount / maxValue) * chartHeight * animationProgress : 0;
            const y1 = chartBottom - barHeight1;

            const barHeight2 = maxValue > 0 ? (noCompleteCount / maxValue) * chartHeight * animationProgress : 0;
            const y2 = chartBottom - barHeight2;

            const gradient1 = ctx.createLinearGradient(0, y1, 0, chartBottom);
            gradient1.addColorStop(0, '#80BFFF');
            gradient1.addColorStop(1, 'rgba(128,191,255,0)');

            ctx.fillStyle = gradient1;
            ctx.fillRect(x, y1, barWidth, barHeight1);

            ctx.fillStyle = '#FFF';
            ctx.textAlign = 'center';
            ctx.fillText(noDrugCount.toString(), x + barWidth / 2, y1 - 5);

            const gradient2 = ctx.createLinearGradient(0, y2, 0, chartBottom);
            gradient2.addColorStop(0, '#FFEA81');
            gradient2.addColorStop(1, 'rgba(255,234,128,0)');

            ctx.fillStyle = gradient2;
            ctx.fillRect(x + barWidth * 1.8, y2, barWidth, barHeight2);

            ctx.fillStyle = '#FFF';
            ctx.fillText(noCompleteCount.toString(), x + barWidth * 1.8 + barWidth / 2, y2 - 5);

            ctx.fillText(`窗口${group.windowNo}`, x + groupWidth / 4, chartBottom + 10);
        });
    }, [safeData, maxValue, animationProgress]);

    // 计算最大值并触发动画
    useEffect(() => {
        if (safeData.windowList.length > 0) {
            const maxDrug = Math.max(...safeData.windowList.map(item => item.noDrugCount));
            const maxComplete = Math.max(...safeData.windowList.map(item => item.noCompleteCount));
            setMaxValue(Math.max(maxDrug, maxComplete) + 20);

            startAnimation();
        }
    }, [safeData]);

    // 监听动画进度或窗口大小变化时重新绘制图表
    useEffect(() => {
        drawChart();
    }, [drawChart]);

    // 监听窗口大小变化
    useEffect(() => {
        const handleResize = () => drawChart();
        const debounceResize = debounce(handleResize, 200);

        window.addEventListener('resize', debounceResize);
        return () => {
            window.removeEventListener('resize', debounceResize);
        };
    }, [drawChart]);

    return (
        <div ref={containerRef} style={{ width: '100%', height: '100%', position: 'relative' }}>
            <canvas ref={canvasRef} style={{ display: 'block', width: '100%', height: '100%' }} />
        </div>
    );
};

// debounce 函数
const debounce = (fn: Function, delay: number) => {
    let timer: NodeJS.Timeout;
    return (...args: any[]) => {
        clearTimeout(timer);
        timer = setTimeout(() => fn(...args), delay);
    };
};

export default BarChartZuhe;
