// 页面加载动画
document.addEventListener('DOMContentLoaded', function () {
    document.body.style.opacity = '0';

    // 页面淡入动画
    setTimeout(() => {
        document.body.style.transition = 'opacity 1.5s ease-in-out';
        document.body.style.opacity = '1';
    }, 100);

    // 添加页面加载完成的特效
    setTimeout(() => {
        addPageLoadEffect();
    }, 2000);

    // 初始化图表
    initBarChart();
    initMaterialChart();
    initProgressBars();
    initParticles();
    initHeaderParticles();
    initAlertChart2();
    initAlertList2();
    initStatusTable();

    // 启动图表动画循环
    startChartAnimations();

    // 添加鼠标交互效果
    addMouseInteractionEffects();

    // 添加键盘控制
    addKeyboardControls();

    // 添加页面可见性控制
    addVisibilityControl();
});

// 图表实例存储
let barChartInstance = null;
let materialChartInstance = null;
let alertChart2Instance = null;

// 动画控制
let animationEnabled = true;
let animationInterval = null;

// 跳转下一页
function goNext() {
  window.location.href="https://cxcygl.lnnu.edu.cn/bigScreen/inen/index.html";
}

// 启动图表动画循环
function startChartAnimations() {
    if (!animationEnabled) return;

    // 每10秒更新一次图表数据
    animationInterval = setInterval(() => {
        if (!animationEnabled) return;

        updateBarChartData();
        updateMaterialChartData();
        updateAlertChart2Data();
        updateProgressData();
        updateNumberData();
        updateTableData();
        updateAlertList();
    }, 10000);
}

// 停止动画
function stopAnimations() {
    animationEnabled = false;
    if (animationInterval) {
        clearInterval(animationInterval);
        animationInterval = null;
    }
}

// 重启动画
function resumeAnimations() {
    animationEnabled = true;
    startChartAnimations();
}

// 初始化柱状图
function initBarChart() {
    const chartDom = document.getElementById('barChart');
    barChartInstance = echarts.init(chartDom);

    const option = {
        backgroundColor: 'transparent',
        // 禁用工具栏（包括缩放功能）
        toolbox: {
            show: false
        },
        // 禁用数据缩放
        dataZoom: [],
        // 禁用动画和缩放
        animation: false,
        // 禁用鼠标滚轮缩放
        brush: {
            toolbox: []
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            },
            backgroundColor: 'rgba(0, 0, 0, 0.8)',
            borderColor: '#4FC3F7',
            borderWidth: 1,
            textStyle: {
                color: '#ffffff'
            },
            formatter: function (params) {
                let result = params[0].name + '<br/>';
                params.forEach(function (item) {
                    result += '<span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:' + item.color + ';"></span>';
                    result += item.seriesName + ': ' + item.value + '件<br/>';
                });
                return result;
            }
        },
        grid: [
            {
                left: '5%',
                right: '5%',
                top: '8%',
                height: '35%',
                containLabel: true
            },
            {
                left: '5%',
                right: '5%',
                top: '55%',
                height: '35%',
                containLabel: true
            }
        ],
        xAxis: [
            {
                type: 'category',
                data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
                gridIndex: 0,
                axisLine: {
                    lineStyle: {
                        color: '#00d4ff'
                    }
                },
                axisLabel: {
                    color: '#ffffff',
                    fontSize: 10
                },
                axisTick: {
                    show: false
                }
            },
            {
                type: 'category',
                data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
                gridIndex: 1,
                axisLine: {
                    lineStyle: {
                        color: '#00d4ff'
                    }
                },
                axisLabel: {
                    color: '#ffffff',
                    fontSize: 10
                },
                axisTick: {
                    show: false
                }
            }
        ],
        yAxis: [
            {
                type: 'value',
                gridIndex: 0,
                max: 800,
                interval: 200,
                axisLine: {
                    show: false
                },
                axisTick: {
                    show: false
                },
                axisLabel: {
                    color: '#ffffff',
                    fontSize: 10
                },
                splitLine: {
                    lineStyle: {
                        color: 'rgba(0, 212, 255, 0.2)',
                        type: 'solid'
                    }
                }
            },
            {
                type: 'value',
                gridIndex: 1,
                max: 800,
                interval: 200,
                axisLine: {
                    show: false
                },
                axisTick: {
                    show: false
                },
                axisLabel: {
                    color: '#ffffff',
                    fontSize: 10
                },
                splitLine: {
                    lineStyle: {
                        color: 'rgba(0, 212, 255, 0.2)',
                        type: 'solid'
                    }
                }
            }
        ],
        series: [
            {
                name: '入库统计',
                type: 'bar',
                xAxisIndex: 0,
                yAxisIndex: 0,
                data: [500, 450, 400, 250, 450, 200, 650, 450, 400, 300, 450, 100],
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: '#66ffff' },
                        { offset: 0.2, color: '#33ddff' },
                        { offset: 0.4, color: '#00bbff' },
                        { offset: 0.6, color: '#0099dd' },
                        { offset: 0.8, color: '#0077bb' },
                        { offset: 1, color: '#005599' }
                    ]),
                    borderColor: '#00aaff',
                    borderWidth: 1,
                    shadowColor: 'rgba(0, 170, 255, 0.6)',
                    shadowBlur: 15,
                    shadowOffsetX: 6,
                    shadowOffsetY: 6
                },
                barWidth: '70%',
                emphasis: {
                    itemStyle: {
                        shadowColor: 'rgba(0, 255, 255, 0.8)',
                        shadowBlur: 20,
                        shadowOffsetX: 8,
                        shadowOffsetY: 8
                    }
                }
            },
            {
                name: '出库统计',
                type: 'bar',
                xAxisIndex: 1,
                yAxisIndex: 1,
                data: [200, 500, 550, 200, 600, 350, 150, 200, 200, 100, 500, 300],
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: '#00ff99' },
                        { offset: 0.2, color: '#00ee88' },
                        { offset: 0.4, color: '#00dd77' },
                        { offset: 0.6, color: '#07ac59' },
                        { offset: 0.8, color: '#03a74c' },
                        { offset: 1, color: '#00aa44' }
                    ]),
                    borderColor: '#00dd77',
                    borderWidth: 1,
                    shadowColor: 'rgba(0, 221, 119, 0.6)',
                    shadowBlur: 15,
                    shadowOffsetX: 6,
                    shadowOffsetY: 6
                },
                barWidth: '70%',
                emphasis: {
                    itemStyle: {
                        shadowColor: 'rgba(0, 255, 153, 0.8)',
                        shadowBlur: 20,
                        shadowOffsetX: 8,
                        shadowOffsetY: 8
                    }
                }
            }
        ],
        graphic: [
            {
                type: 'image',
                right: 20,
                top: '3%',
                style: {
                    image: 'images/icon_bg.png',
                    width: 100,
                    height: 35
                },
                z: 99
            },
            {
                type: 'text',
                right: 40,
                top: '6%',
                style: {
                    text: '入库统计',
                    fill: '#ffffff',
                    fontSize: 15,
                    textAlign: 'center'
                },
                z: 100
            },
            {
                type: 'image',
                right: 20,
                top: '50%',
                style: {
                    image: 'images/icon_bg.png',
                    width: 100,
                    height: 35
                },
                z: 99
            },
            {
                type: 'text',
                right: 40,
                top: '53%',
                style: {
                    text: '出库统计',
                    fill: '#ffffff',
                    fontSize: 15,
                    textAlign: 'center'
                },
                z: 100
            }
        ]
    };

    barChartInstance.setOption(option);

    // 禁用鼠标滚轮缩放和拖拽缩放
    const barChartDom = document.getElementById('barChart');
    if (barChartDom) {
        barChartDom.addEventListener('wheel', function (e) {
            e.preventDefault();
            e.stopPropagation();
        }, { passive: false });

        barChartDom.addEventListener('mousedown', function (e) {
            if (e.ctrlKey || e.metaKey) {
                e.preventDefault();
                e.stopPropagation();
            }
        });
    }

    // 响应式
    window.addEventListener('resize', () => {
        barChartInstance.resize();
    });
}

// 初始化材料分布饼图
function initMaterialChart() {
    materialChartInstance = echarts.init(document.getElementById('materialChart'));

    const materialData = [
        { value: 8500, name: '钢材', itemStyle: { color: '#4FC3F7' } },
        { value: 4200, name: '锌', itemStyle: { color: '#7986CB' } },
        { value: 3800, name: '五金', itemStyle: { color: '#81C784' } },
        { value: 3200, name: '电器', itemStyle: { color: '#FFB74D' } },
        { value: 2800, name: '水泥', itemStyle: { color: '#FF8A65' } },
        { value: 2400, name: '化工', itemStyle: { color: '#F06292' } },
        { value: 2000, name: '工具用具', itemStyle: { color: '#BA68C8' } },
        { value: 1800, name: '安全劳保', itemStyle: { color: '#9575CD' } },
        { value: 1500, name: '易耗', itemStyle: { color: '#64B5F6' } },
        { value: 1200, name: '半成品', itemStyle: { color: '#CE93D8' } },
        { value: 1000, name: '周转材料', itemStyle: { color: '#A1887F' } },
        { value: 800, name: '装饰', itemStyle: { color: '#90A4AE' } },
        { value: 600, name: '地材', itemStyle: { color: '#FFCC02' } },
        { value: 500, name: '木材', itemStyle: { color: '#8BC34A' } }
    ];

    const option = {
        backgroundColor: 'transparent',
        // 禁用工具栏（包括缩放功能）
        toolbox: {
            show: false
        },
        // 禁用数据缩放
        dataZoom: [],
        // 禁用动画和缩放
        animation: false,
        // 禁用鼠标滚轮缩放
        brush: {
            toolbox: []
        },
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c}件 ({d}%)',
            backgroundColor: 'rgba(0, 0, 0, 0.8)',
            borderColor: '#4FC3F7',
            borderWidth: 1,
            textStyle: {
                color: '#ffffff'
            }
        },
        legend: [
            {
                orient: 'vertical',
                right: 120,
                top: 150,
                itemWidth: 10,
                itemHeight: 10,
                itemGap: 6,
                textStyle: {
                    color: '#ffffff',
                    fontSize: 14
                },
                data: materialData.slice(0, 7).map(item => item.name)
            },
            {
                orient: 'vertical',
                right: 20,
                top: 150,
                itemWidth: 10,
                itemHeight: 10,
                itemGap: 6,
                textStyle: {
                    color: '#ffffff',
                    fontSize: 14
                },
                data: materialData.slice(7).map(item => item.name)
            }
        ],
        series: [
            {
                name: '材料分布',
                type: 'pie',
                radius: ['0%', '55%'],
                center: ['35%', '60%'],
                avoidLabelOverlap: true,
                label: {
                    show: true,
                    position: 'outside',
                    formatter: function (params) {
                        // 显示所有材料的标签
                        if (params.value >= 2500) { // 大材料
                            return `{main|${params.name}}`;
                        } else if (params.value >= 1000) { // 中等材料
                            return `{main|${params.name}}`;
                        } else { // 小材料
                            return `{small|${params.name}}`;
                        }
                    },
                    rich: {
                        title: {
                            color: '#ffffff',
                            fontSize: 16,
                            fontWeight: 'bold',
                            padding: [0, 0, 5, 0]
                        },
                        main: {
                            color: '#ffffff',
                            fontSize: 14,
                            fontWeight: 'normal'
                        },
                        small: {
                            color: '#ffffff',
                            fontSize: 12,
                            fontWeight: 'normal'
                        }
                    },
                    // 防止标签重叠
                    minMargin: 5,
                    // 调整标签距离
                    distanceToLabelLine: 5
                },
                labelLine: {
                    show: true,
                    length: 35,
                    length2: 20,
                    lineStyle: {
                        color: '#00cbfd',
                        width: 1
                    },

                },
                emphasis: {
                    itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                },
                data: materialData
            }
        ]
    };

    materialChartInstance.setOption(option);

    // 禁用鼠标滚轮缩放和拖拽缩放
    const materialChartDom = document.getElementById('materialChart');
    if (materialChartDom) {
        materialChartDom.addEventListener('wheel', function (e) {
            e.preventDefault();
            e.stopPropagation();
        }, { passive: false });

        materialChartDom.addEventListener('mousedown', function (e) {
            if (e.ctrlKey || e.metaKey) {
                e.preventDefault();
                e.stopPropagation();
            }
        });
    }

    // 响应式
    window.addEventListener('resize', () => {
        materialChartInstance.resize();
    });
}

// 初始化进度条动画
function initProgressBars() {
    const progressFills = document.querySelectorAll('.progress-fill');

    // 初始时设置宽度为0
    progressFills.forEach(fill => {
        const targetWidth = fill.style.width;
        fill.style.width = '0%';

        // 延迟执行动画
        setTimeout(() => {
            fill.style.width = targetWidth;
        }, 500);
    });
}

// 初始化粒子特效
function initParticles() {
    const particleContainers = document.querySelectorAll('.particles-container');

    particleContainers.forEach(container => {
        // 为每个容器创建粒子
        createParticles(container, 12);
    });
}

// 创建粒子
function createParticles(container, count) {
    for (let i = 0; i < count; i++) {
        const particle = document.createElement('div');
        particle.className = 'particle';

        // 随机位置
        const x = Math.random() * 100;
        const y = Math.random() * 100;

        particle.style.left = x + '%';
        particle.style.top = y + '%';

        // 随机动画延迟
        const delay = Math.random() * 3;
        particle.style.animationDelay = delay + 's';

        container.appendChild(particle);
    }
}

// 初始化头部粒子特效
function initHeaderParticles() {
    const headerParticlesContainer = document.querySelector('.header-particles');

    if (headerParticlesContainer) {
        createHeaderParticles(headerParticlesContainer, 20);
    }
}

// 创建头部粒子
function createHeaderParticles(container, count) {
    for (let i = 0; i < count; i++) {
        const particle = document.createElement('div');

        // 随机垂直位置
        const y = Math.random() * 100;
        particle.style.top = y + '%';

        // 随机动画延迟
        const delay = Math.random() * 6;
        particle.style.animationDelay = delay + 's';

        // 一半粒子从左边来，一半从右边来
        if (i < count / 2) {
            // 从左边来的粒子
            particle.className = 'header-particle from-left';
            particle.style.left = '0px'; // CSS动画会控制位置
        } else {
            // 从右边来的粒子
            particle.className = 'header-particle from-right';
            particle.style.left = '0px'; // CSS动画会控制位置
        }

        container.appendChild(particle);
    }
}

// 初始化第二个告警图表
function initAlertChart2() {
    const chartDom = document.getElementById('alertChart2');
    if (!chartDom) return;

    alertChart2Instance = echarts.init(chartDom);

    const option = {
        backgroundColor: 'transparent',
        // 禁用工具栏（包括缩放功能）
        toolbox: {
            show: false
        },
        // 禁用数据缩放
        dataZoom: [],
        // 禁用动画和缩放
        animation: false,
        // 禁用鼠标滚轮缩放
        brush: {
            toolbox: []
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            },
            backgroundColor: 'rgba(0, 0, 0, 0.8)',
            borderColor: '#4FC3F7',
            borderWidth: 1,
            textStyle: {
                color: '#ffffff'
            }
        },
        legend: {
            data: ['库存告警', '库龄告警', '温湿度告警'],
            top: '5%',
            textStyle: {
                color: '#ffffff',
                fontSize: 12
            },
            itemWidth: 15,
            itemHeight: 10
        },
        grid: {
            left: '8%',
            right: '8%',
            bottom: '5%',
            top: '25%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
            axisLine: {
                lineStyle: {
                    color: '#00d4ff'
                }
            },
            axisLabel: {
                color: '#ffffff',
                fontSize: 11
            },
            axisTick: {
                show: false
            }
        },
        yAxis: {
            type: 'value',
            max: 30,
            interval: 10,
            axisLine: {
                show: false
            },
            axisTick: {
                show: false
            },
            axisLabel: {
                color: '#ffffff',
                fontSize: 11
            },
            splitLine: {
                lineStyle: {
                    color: 'rgba(0, 212, 255, 0.2)',
                    type: 'solid'
                }
            }
        },
        series: [
            {
                name: '库存告警',
                type: 'bar',
                data: [15, 22, 10, 6, 12, 18, 9, 15, 13, 11, 19, 8],
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: '#ff6b6b' },
                        { offset: 0.5, color: '#ff5252' },
                        { offset: 1, color: '#d32f2f' }
                    ]),
                    borderRadius: [2, 2, 0, 0]
                },
                barWidth: '25%'
            },
            {
                name: '库龄告警',
                type: 'bar',
                data: [6, 10, 4, 3, 8, 6, 4, 7, 5, 4, 9, 3],
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: '#4FC3F7' },
                        { offset: 0.5, color: '#29B6F6' },
                        { offset: 1, color: '#0288D1' }
                    ]),
                    borderRadius: [2, 2, 0, 0]
                },
                barWidth: '25%'
            },
            {
                name: '温湿度告警',
                type: 'bar',
                data: [3, 6, 2, 1, 4, 3, 2, 4, 3, 2, 5, 1],
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: '#FFEB3B' },
                        { offset: 0.5, color: '#FFC107' },
                        { offset: 1, color: '#FF8F00' }
                    ]),
                    borderRadius: [2, 2, 0, 0]
                },
                barWidth: '25%'
            }
        ]
    };

    alertChart2Instance.setOption(option);

    // 禁用鼠标滚轮缩放和拖拽缩放
    const alertChart2Dom = document.getElementById('alertChart2');
    if (alertChart2Dom) {
        alertChart2Dom.addEventListener('wheel', function (e) {
            e.preventDefault();
            e.stopPropagation();
        }, { passive: false });

        alertChart2Dom.addEventListener('mousedown', function (e) {
            if (e.ctrlKey || e.metaKey) {
                e.preventDefault();
                e.stopPropagation();
            }
        });
    }

    // 响应式
    window.addEventListener('resize', () => {
        alertChart2Instance.resize();
    });
}

// 初始化第二个告警列表动画
function initAlertList2() {
    const alertItems = document.querySelectorAll('.alert-item2');

    // 初始时隐藏所有告警项
    alertItems.forEach((item, index) => {
        item.style.opacity = '0';
        item.style.transform = 'translateX(-30px)';

        // 依次显示告警项
        setTimeout(() => {
            item.style.transition = 'all 0.5s ease';
            item.style.opacity = '1';
            item.style.transform = 'translateX(0)';
        }, index * 200 + 1500); // 延迟1.5秒后开始，每个间隔200ms
    });
}

// 初始化状态表格
function initStatusTable() {
    const tableBody = document.getElementById('statusTableBody');
    if (!tableBody) return;

    // 状态数据
    const statusData = [
        { name: '地材物资', status: 'out', time: '2021-01-15 10:04:10', operator: '袁文' },
        { name: '木材物资', status: 'in', time: '2021-01-15 10:04:10', operator: '张三' },
        { name: '五金物资', status: 'in', time: '2021-01-15 10:04:10', operator: '张三' },
        { name: '安全防护物资', status: 'out', time: '2021-01-15 10:04:10', operator: '张三丰' },
        { name: '钢材物资', status: 'in', time: '2021-01-15 11:15:20', operator: '李四' },
        { name: '电器设备', status: 'out', time: '2021-01-15 11:30:45', operator: '王五' },
        { name: '化工原料', status: 'in', time: '2021-01-15 12:05:30', operator: '赵六' },
        { name: '工具用具', status: 'out', time: '2021-01-15 12:20:15', operator: '孙七' },
        { name: '水泥建材', status: 'in', time: '2021-01-15 13:10:25', operator: '周八' },
        { name: '装饰材料', status: 'out', time: '2021-01-15 13:45:50', operator: '吴九' },
        { name: '半成品材料', status: 'in', time: '2021-01-15 14:20:30', operator: '郑十' },
        { name: '易耗品', status: 'out', time: '2021-01-15 14:55:15', operator: '陈一' },
        { name: '周转材料', status: 'in', time: '2021-01-15 15:30:40', operator: '刘二' },
        { name: '锌合金', status: 'out', time: '2021-01-15 16:05:25', operator: '黄三' },
        { name: '劳保用品', status: 'in', time: '2021-01-15 16:40:10', operator: '林四' }
    ];

    // 复制数据以实现无缝滚动
    const duplicatedData = [...statusData, ...statusData];

    // 清空现有内容
    tableBody.innerHTML = '';

    // 生成表格行
    duplicatedData.forEach((item, index) => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${item.name}</td>
            <td><span class="status-${item.status}">${item.status === 'in' ? '入库' : '出库'}</span></td>
            <td>${item.time}</td>
            <td>${item.operator}</td>
        `;

        // 添加鼠标悬停效果
        row.addEventListener('mouseenter', function () {
            this.style.background = 'rgba(0, 212, 255, 0.3)';
            this.style.transform = 'scale(1.02)';
            this.style.boxShadow = '0 4px 15px rgba(0, 212, 255, 0.4)';
        });

        row.addEventListener('mouseleave', function () {
            // 恢复原来的背景色
            if (index % 2 === 0) {
                this.style.background = 'rgba(0, 50, 80, 0.4)';
            } else {
                this.style.background = 'rgba(0, 30, 50, 0.6)';
            }
            this.style.transform = 'scale(1)';
            this.style.boxShadow = 'none';
        });

        tableBody.appendChild(row);
    });

    // 添加表格容器的鼠标事件
    const tableContainer = document.querySelector('.table-container');
    if (tableContainer) {
        tableContainer.addEventListener('mouseenter', function () {
            const table = this.querySelector('.status-table');
            if (table) {
                table.style.animationPlayState = 'paused';
            }
        });

        tableContainer.addEventListener('mouseleave', function () {
            const table = this.querySelector('.status-table');
            if (table) {
                table.style.animationPlayState = 'running';
            }
        });
    }
}

// 更新柱状图数据
function updateBarChartData() {
    if (!barChartInstance) return;

    // 生成随机数据
    const inData = Array.from({ length: 12 }, () => Math.floor(Math.random() * 600) + 100);
    const outData = Array.from({ length: 12 }, () => Math.floor(Math.random() * 600) + 100);

    barChartInstance.setOption({
        series: [
            {
                data: inData,
                animationDuration: 2000,
                animationEasing: 'elasticOut'
            },
            {
                data: outData,
                animationDuration: 2000,
                animationEasing: 'elasticOut'
            }
        ]
    });
}

// 更新材料分布饼图数据
function updateMaterialChartData() {
    if (!materialChartInstance) return;

    const materialNames = ['钢材', '锌', '五金', '电器', '水泥', '化工', '工具用具', '安全劳保', '易耗', '半成品', '周转材料', '装饰', '地材', '木材'];
    const colors = ['#4FC3F7', '#7986CB', '#81C784', '#FFB74D', '#FF8A65', '#F06292', '#BA68C8', '#9575CD', '#64B5F6', '#CE93D8', '#A1887F', '#90A4AE', '#FFCC02', '#8BC34A'];

    const newData = materialNames.map((name, index) => ({
        value: Math.floor(Math.random() * 8000) + 500,
        name: name,
        itemStyle: { color: colors[index] }
    }));

    materialChartInstance.setOption({
        series: [{
            data: newData,
            animationDuration: 2000,
            animationEasing: 'elasticOut'
        }]
    });
}

// 更新告警图表数据
function updateAlertChart2Data() {
    if (!alertChart2Instance) return;

    const data1 = Array.from({ length: 12 }, () => Math.floor(Math.random() * 25) + 5);
    const data2 = Array.from({ length: 12 }, () => Math.floor(Math.random() * 15) + 2);
    const data3 = Array.from({ length: 12 }, () => Math.floor(Math.random() * 8) + 1);

    alertChart2Instance.setOption({
        series: [
            {
                data: data1,
                animationDuration: 2000,
                animationEasing: 'elasticOut'
            },
            {
                data: data2,
                animationDuration: 2000,
                animationEasing: 'elasticOut'
            },
            {
                data: data3,
                animationDuration: 2000,
                animationEasing: 'elasticOut'
            }
        ]
    });
}

// 更新进度条数据
function updateProgressData() {
    const progressFills = document.querySelectorAll('.progress-fill');
    const progressValues = document.querySelectorAll('.progress-value');

    progressFills.forEach((fill, index) => {
        const newWidth = Math.floor(Math.random() * 80) + 20;
        const newValue = Math.floor(Math.random() * 200) + 50;

        fill.style.width = newWidth + '%';
        if (progressValues[index]) {
            progressValues[index].textContent = newValue + '次';
        }
    });
}

// 更新数字数据
function updateNumberData() {
    const counts = document.querySelectorAll('.count');

    counts.forEach(count => {
        const currentValue = parseInt(count.textContent);
        const newValue = Math.floor(currentValue * (0.9 + Math.random() * 0.2));

        // 数字动画效果
        animateNumber(count, currentValue, newValue, 2000);
    });
}

// 数字动画函数
function animateNumber(element, start, end, duration) {
    const startTime = performance.now();
    const difference = end - start;

    function updateNumber(currentTime) {
        const elapsed = currentTime - startTime;
        const progress = Math.min(elapsed / duration, 1);

        // 使用缓动函数
        const easeOutQuart = 1 - Math.pow(1 - progress, 4);
        const current = Math.floor(start + difference * easeOutQuart);

        element.textContent = current;

        if (progress < 1) {
            requestAnimationFrame(updateNumber);
        }
    }

    requestAnimationFrame(updateNumber);
}

// 更新表格数据
function updateTableData() {
    const tableBody = document.getElementById('statusTableBody');
    if (!tableBody) return;

    const materialNames = ['地材物资', '木材物资', '五金物资', '安全防护物资', '钢材物资', '电器设备', '化工原料', '工具用具', '水泥建材', '装饰材料', '半成品材料', '易耗品', '周转材料', '锌合金', '劳保用品'];
    const operators = ['袁文', '张三', '李四', '王五', '赵六', '孙七', '周八', '吴九', '郑十', '陈一', '刘二', '黄三', '林四', '张三丰'];
    const statuses = ['in', 'out'];

    // 随机选择几行进行更新
    const rows = tableBody.querySelectorAll('tr');
    const updateCount = Math.floor(Math.random() * 3) + 1; // 更新1-3行

    for (let i = 0; i < updateCount; i++) {
        const randomRowIndex = Math.floor(Math.random() * Math.min(rows.length, 10)); // 只更新前10行
        const row = rows[randomRowIndex];
        if (!row) continue;

        const cells = row.querySelectorAll('td');
        if (cells.length >= 4) {
            // 更新材料名称
            cells[0].textContent = materialNames[Math.floor(Math.random() * materialNames.length)];

            // 更新状态
            const newStatus = statuses[Math.floor(Math.random() * statuses.length)];
            const statusSpan = cells[1].querySelector('span');
            if (statusSpan) {
                statusSpan.className = `status-${newStatus}`;
                statusSpan.textContent = newStatus === 'in' ? '入库' : '出库';
            }

            // 更新时间
            const now = new Date();
            const timeString = now.getFullYear() + '-' +
                String(now.getMonth() + 1).padStart(2, '0') + '-' +
                String(now.getDate()).padStart(2, '0') + ' ' +
                String(now.getHours()).padStart(2, '0') + ':' +
                String(now.getMinutes()).padStart(2, '0') + ':' +
                String(now.getSeconds()).padStart(2, '0');
            cells[2].textContent = timeString;

            // 更新操作人
            cells[3].textContent = operators[Math.floor(Math.random() * operators.length)];

            // 添加更新动画效果
            row.style.background = 'rgba(0, 255, 255, 0.3)';
            row.style.transform = 'scale(1.02)';
            row.style.transition = 'all 0.5s ease';

            setTimeout(() => {
                row.style.background = '';
                row.style.transform = 'scale(1)';
            }, 1000);
        }
    }
}

// 更新告警列表
function updateAlertList() {
    const alertItems = document.querySelectorAll('.alert-item2');
    if (alertItems.length === 0) return;

    const alertTypes = [
        '库位物资库存不足告警',
        '库位钢材物资库龄告警',
        '仓库测温点位温度异常告警',
        '库位湿度超标告警',
        '物资过期告警',
        '库位安全告警',
        '设备故障告警',
        '库存盘点异常告警'
    ];

    const locations = ['C01-J99-01-01', 'C01-J10-04-03', 'C02-A15-02-05', 'C03-B20-01-08', 'C01-K05-03-02'];

    // 随机更新一个告警项
    const randomIndex = Math.floor(Math.random() * alertItems.length);
    const alertItem = alertItems[randomIndex];

    const alertTitle = alertItem.querySelector('.alert-title2');
    const alertTime = alertItem.querySelector('.alert-time2');

    if (alertTitle && alertTime) {
        // 生成新的告警内容
        const location = locations[Math.floor(Math.random() * locations.length)];
        const alertType = alertTypes[Math.floor(Math.random() * alertTypes.length)];
        alertTitle.textContent = location + alertType;

        // 更新时间
        const now = new Date();
        const timeString = now.getFullYear() + '-' +
            String(now.getMonth() + 1).padStart(2, '0') + '-' +
            String(now.getDate()).padStart(2, '0') + ' ' +
            String(now.getHours()).padStart(2, '0') + ':' +
            String(now.getMinutes()).padStart(2, '0') + ':' +
            String(now.getSeconds()).padStart(2, '0');
        alertTime.textContent = timeString;

        // 添加更新动画效果
        alertItem.style.background = 'rgba(255, 107, 107, 0.2)';
        alertItem.style.transform = 'translateX(8px) scale(1.02)';
        alertItem.style.transition = 'all 0.5s ease';

        setTimeout(() => {
            alertItem.style.background = '';
            alertItem.style.transform = 'translateX(0) scale(1)';
        }, 1500);
    }
}

// 页面加载完成特效
function addPageLoadEffect() {
    // 创建闪光效果
    const flash = document.createElement('div');
    flash.style.cssText = `
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: radial-gradient(circle, rgba(0, 255, 255, 0.3) 0%, transparent 70%);
        pointer-events: none;
        z-index: 9999;
        opacity: 0;
        animation: flashEffect 2s ease-out forwards;
    `;

    document.body.appendChild(flash);

    // 2秒后移除闪光效果
    setTimeout(() => {
        document.body.removeChild(flash);
    }, 2000);

    // 添加CSS动画
    const style = document.createElement('style');
    style.textContent = `
        @keyframes flashEffect {
            0% {
                opacity: 0;
                transform: scale(0.5);
            }
            50% {
                opacity: 0.8;
                transform: scale(1.2);
            }
            100% {
                opacity: 0;
                transform: scale(2);
            }
        }
    `;
    document.head.appendChild(style);
}

// 添加鼠标交互效果
function addMouseInteractionEffects() {
    // 为所有面板添加鼠标悬停效果
    const panels = document.querySelectorAll('.left-top, .left-bottom, .middle, .right-top, .right-bottom');

    panels.forEach(panel => {
        panel.addEventListener('mouseenter', function () {
            this.style.transform = 'scale(1.02)';
            this.style.filter = 'brightness(1.1) saturate(1.1)';
            this.style.transition = 'all 0.3s ease';
            this.style.zIndex = '10';
        });

        panel.addEventListener('mouseleave', function () {
            this.style.transform = 'scale(1)';
            this.style.filter = 'brightness(1) saturate(1)';
            this.style.zIndex = '1';
        });
    });

    // 为图表容器添加特殊的鼠标效果
    const chartContainers = document.querySelectorAll('.chart-container, .chart-container2, .chart-container3');

    chartContainers.forEach(container => {
        container.addEventListener('mouseenter', function () {
            this.style.filter = 'brightness(1.15) saturate(1.2) drop-shadow(0 0 20px rgba(0, 212, 255, 0.4))';
            this.style.transition = 'all 0.3s ease';
        });

        container.addEventListener('mouseleave', function () {
            this.style.filter = 'brightness(1) saturate(1)';
        });
    });

    // 为数字添加点击效果
    const counts = document.querySelectorAll('.count');

    counts.forEach(count => {
        count.addEventListener('click', function () {
            // 创建点击波纹效果
            const ripple = document.createElement('span');
            ripple.style.cssText = `
                position: absolute;
                border-radius: 50%;
                background: rgba(0, 255, 255, 0.6);
                transform: scale(0);
                animation: rippleEffect 0.6s linear;
                pointer-events: none;
            `;

            const rect = this.getBoundingClientRect();
            const size = Math.max(rect.width, rect.height);
            ripple.style.width = ripple.style.height = size + 'px';
            ripple.style.left = (rect.width / 2 - size / 2) + 'px';
            ripple.style.top = (rect.height / 2 - size / 2) + 'px';

            this.style.position = 'relative';
            this.appendChild(ripple);

            setTimeout(() => {
                ripple.remove();
            }, 600);
        });
    });

    // 添加波纹动画CSS
    const rippleStyle = document.createElement('style');
    rippleStyle.textContent = `
        @keyframes rippleEffect {
            to {
                transform: scale(2);
                opacity: 0;
            }
        }
    `;
    document.head.appendChild(rippleStyle);
}

// 添加键盘控制
function addKeyboardControls() {
    document.addEventListener('keydown', function (event) {
        // 按 'A' 键切换动画开关
        if (event.key.toLowerCase() === 'a') {
            if (animationEnabled) {
                stopAnimations();
                showNotification('动画已暂停 (按A键恢复)', 'warning');
            } else {
                resumeAnimations();
                showNotification('动画已恢复', 'success');
            }
        }

        // 按 'R' 键手动刷新数据
        if (event.key.toLowerCase() === 'r') {
            updateBarChartData();
            updateMaterialChartData();
            updateAlertChart2Data();
            updateProgressData();
            updateNumberData();
            updateTableData();
            updateAlertList();
            showNotification('数据已刷新', 'info');
        }

        // 按 'H' 键显示帮助
        if (event.key.toLowerCase() === 'h') {
            showNotification('快捷键: A-切换动画, R-刷新数据, H-帮助', 'info');
        }
    });
}

// 显示通知
function showNotification(message, type = 'info') {
    const notification = document.createElement('div');
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        padding: 12px 20px;
        border-radius: 6px;
        color: white;
        font-size: 14px;
        z-index: 10000;
        opacity: 0;
        transform: translateX(100%);
        transition: all 0.3s ease;
        pointer-events: none;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
    `;

    // 根据类型设置颜色
    switch (type) {
        case 'success':
            notification.style.background = 'linear-gradient(135deg, #00ff88, #00dd77)';
            break;
        case 'warning':
            notification.style.background = 'linear-gradient(135deg, #ffaa00, #ff8800)';
            break;
        case 'error':
            notification.style.background = 'linear-gradient(135deg, #ff6b6b, #ff5252)';
            break;
        default:
            notification.style.background = 'linear-gradient(135deg, #4FC3F7, #29B6F6)';
    }

    notification.textContent = message;
    document.body.appendChild(notification);

    // 显示动画
    setTimeout(() => {
        notification.style.opacity = '1';
        notification.style.transform = 'translateX(0)';
    }, 100);

    // 3秒后隐藏
    setTimeout(() => {
        notification.style.opacity = '0';
        notification.style.transform = 'translateX(100%)';
        setTimeout(() => {
            document.body.removeChild(notification);
        }, 300);
    }, 3000);
}

// 页面可见性控制
function addVisibilityControl() {
    let wasAnimationEnabled = animationEnabled;

    document.addEventListener('visibilitychange', function () {
        if (document.hidden) {
            // 页面隐藏时暂停动画
            wasAnimationEnabled = animationEnabled;
            if (animationEnabled) {
                stopAnimations();
            }
        } else {
            // 页面显示时恢复动画
            if (wasAnimationEnabled) {
                resumeAnimations();
            }
        }
    });

    // 窗口失去焦点时暂停动画
    window.addEventListener('blur', function () {
        wasAnimationEnabled = animationEnabled;
        if (animationEnabled) {
            stopAnimations();
        }
    });

    // 窗口获得焦点时恢复动画
    window.addEventListener('focus', function () {
        if (wasAnimationEnabled) {
            resumeAnimations();
        }
    });
}