import React, { useRef, useEffect, useState } 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); // 用于动画的进度

    useEffect(() => {
        if (data && Array.isArray(data.windowList)) {
            // 计算windowList中的最大值作为maxValue
            const maxDrug = Math.max(...data.windowList.map(item => item.noDrugCount));
            const maxComplete = Math.max(...data.windowList.map(item => item.noCompleteCount));
            const calculatedMaxValue = Math.max(maxDrug, maxComplete) + 20;
            setMaxValue(calculatedMaxValue);

            // 开始动画
            setAnimationProgress(0);
            requestAnimationFrame(animate);
        } else {
            console.error('Invalid data structure: ', data);
        }
    }, [data]);

    const animate = (timestamp?: number) => {
        setAnimationProgress((prevProgress) => {
            const newProgress = prevProgress + 0.02; // 增加进度
            if (newProgress >= 1) {
                return 1; // 动画完成时，将进度设置为1
            } else {
                requestAnimationFrame(animate);
                return newProgress;
            }
        });
    };

    const drawChart = () => {
        const canvas = canvasRef.current;
        const container = containerRef.current;

        if (!canvas || !container || !Array.isArray(data.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 / data.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).toString(), leftMargin - 10, y + fontSize / 2);
        }

        // 绘制中央柱状图区域
        data.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);
        });

        // 绘制左侧区域
        drawSideBox(ctx, leftMargin * 0.25, 0, leftMargin * 0.5, chartHeight, data.noDrugCount);

        // 绘制右侧区域
        drawSideBox(ctx, width - rightMargin * 0.75, 0, rightMargin * 0.5, chartHeight, data.noCompleteCount, true);
    };

    const drawSideBox = (
        ctx: CanvasRenderingContext2D,
        x: number,
        y: number,
        width: number,
        height: number,
        value: number,
        reverse: boolean = false
    ) => {
        // 调整背景颜色和渐变
        const gradient = ctx.createLinearGradient(0, y, 0, y + height);
        gradient.addColorStop(0, '#051833');  // 更深的背景色
        gradient.addColorStop(1, '#233958');  // 渐变到较浅的颜色

        // 填充柱子背景
        ctx.fillStyle = gradient;
        ctx.fillRect(x, y, width, height);

        // 绘制圆角矩形边框
        const borderRadius = 8;
        ctx.strokeStyle = '#334866';  // 边框颜色
        ctx.lineWidth = 2;  // 边框宽度
        ctx.beginPath();
        ctx.moveTo(x + borderRadius, y);
        ctx.lineTo(x + width - borderRadius, y);
        ctx.quadraticCurveTo(x + width, y, x + width, y + borderRadius);
        ctx.lineTo(x + width, y + height - borderRadius);
        ctx.quadraticCurveTo(x + width, y + height, x + width - borderRadius, y + height);
        ctx.lineTo(x + borderRadius, y + height);
        ctx.quadraticCurveTo(x, y + height, x, y + height - borderRadius);
        ctx.lineTo(x, y + borderRadius);
        ctx.quadraticCurveTo(x, y, x + borderRadius, y);
        ctx.closePath();
        ctx.stroke();

        // 根据value调整顶部的数字
        ctx.font = `bold ${width * 0.3}px Arial`;
        ctx.fillStyle = '#FFF';
        ctx.textAlign = 'center';
        ctx.fillText(value.toString().padStart(3, '0'), x + width / 2, y + height * 0.15);

        ctx.font = `${width * 0.13}px Arial`;
        ctx.fillText(reverse ? '待发预警（人）' : '待配预警（人）', x + width / 2 + 3, y + height * 0.9);

        // 根据数值动态绘制小块，从底部开始递增
        const barCount = Math.min(10, Math.round((value / maxValue) * 20)); // 最大绘制10个小块
        const barHeight = height * 0.02;  // 小块的高度
        const barSpacing = barHeight * 0.5;  // 小块之间的间距
        const startY = y + height * 0.75;  // 小块的起始Y坐标，从底部开始

        ctx.fillStyle = reverse ? '#FFDA7A' : '#80C0FF';
        for (let i = 0; i < barCount * animationProgress; i++) {
            ctx.fillRect(x + width * 0.1, startY - i * (barHeight + barSpacing), width * 0.8, barHeight);
        }
    };

    useEffect(() => {
        data&&drawChart();
    }, [data, maxValue, animationProgress]);

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

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

export default BarChartZuhe;
