// 实时时间显示
function updateDateTime() {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  const seconds = String(now.getSeconds()).padStart(2, '0')

  const dateTimeString = `🕐 ${year}年${month}月${day}日${hours}:${minutes}:${seconds}`
  document.getElementById('datetime').textContent = dateTimeString
}

// 跳转下一页
function goNext() {
  window.location.href = 'https://cxcygl.lnnu.edu.cn/bigScreen/match/index.html'
  // localStorage.clear()
  // window.location.reload()
}

// 每秒更新时间
setInterval(updateDateTime, 1000)
updateDateTime()


// 事件紧急程度图表 - 使用ECharts
function createUrgencyChart() {
  try {
    console.log('Creating urgencyChart...')
    const chartDom = document.getElementById('urgencyChart')
    if (!chartDom) {
      console.error('urgencyChart element not found')
      return
    }
    console.log('urgencyChart element found:', chartDom)
    const myChart = echarts.init(chartDom)
    console.log('ECharts instance created for urgencyChart')

    let option = {
      backgroundColor: 'transparent',
      // 优化的动画配置
      animation: true,
      animationDuration: 2000,
      animationEasing: 'elasticOut',
      animationDelay: function(idx) {
        return idx * 300
      },
      title: [
        {
          text: '总数',
          left: '39%',
          top: '38%',
          textAlign: 'center',
          textStyle: {
            color: '#00ffff',
            fontSize: 16,
            fontWeight: 'normal'
          }
        },
        {
          text: '100%',
          left: '39%',
          top: '48%',
          textAlign: 'center',
          textStyle: {
            color: '#ffffff',
            fontSize: 20,
            fontWeight: 'bold'
          }
        }
      ],
      legend: {
        orient: 'vertical',
        right: '2%',
        top: 'center',
        textStyle: {
          color: '#ffffff',
          fontSize: 14
        },
        itemWidth: 12,
        itemHeight: 12,
        itemGap: 20
      },
      series: [
        // 外层底色圆环
        {
          type: 'pie',
          radius: ['40%', '80%'],
          center: ['40%', '50%'],
          silent: true,
          label: {
            show: false
          },
          labelLine: {
            show: false
          },
          data: [{
            value: 100,
            itemStyle: {
              color: 'rgba(255, 255, 255, 0.1)'
            }
          }]
        },
        // 主要数据圆环
        {
          type: 'pie',
          radius: ['45%', '75%'],
          center: ['40%', '50%'],
          avoidLabelOverlap: false,
          label: {
            show: true,
            position: 'inside',
            formatter: '{b}\n{c}%',
            textStyle: {
              color: '#ffffff',
              fontSize: 14,
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: true,
            length: 10,
            length2: 10,
            lineStyle: {
              color: '#ffffff',
              width: 1
            }
          },
          data: []
        }
      ]
    }
    fetchReq.get('/system/bigScreen/getValueByKey', { key: 'inen_project_level' }).then(res => {
      if (res.success) {
        option.series[1].data = res.result
      }
    }).finally(() => {
      myChart.setOption(option)
    })
    console.log('urgencyChart option set successfully')

    // 将图表实例和配置保存到全局管理器
    window.chartManager = window.chartManager || {}
    window.chartManager.urgencyChart = {
      instance: myChart,
      option: option,
      emptyOption: {
        series: [
          {
            data: [{ value: 100, itemStyle: { color: 'rgba(255, 255, 255, 0.1)' } }]
          },
          {
            data: [
              { value: 0, name: '普通' },
              { value: 0, name: '紧急' },
              { value: 0, name: '非常紧急' }
            ]
          }
        ]
      }
    }

    // 响应式调整
    window.addEventListener('resize', function() {
      myChart.resize()
    })

    console.log('urgencyChart created successfully')
  } catch (error) {
    console.error('Error creating urgencyChart:', error)
  }
}

// 事件上报情况图表 - 使用ECharts
function createReportingChart() {
  try {
    console.log('Creating reportingChart...')
    const chartDom = document.getElementById('reportingChart')
    if (!chartDom) {
      console.error('reportingChart element not found')
      return
    }
    console.log('reportingChart element found:', chartDom)
    const myChart = echarts.init(chartDom)
    let option = {
      backgroundColor: 'transparent',
      // 优化的动画配置
      animation: true,
      animationDuration: 1000, // 总动画时长8秒
      animationEasing: 'elasticOut',
      animationDelay: 0, // 全局不延迟，让每个柱子控制自己的延迟
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        },
        backgroundColor: 'rgba(0, 0, 0, 0.8)',
        borderColor: '#00d4ff',
        borderWidth: 1,
        textStyle: {
          color: '#fff'
        }
      },
      legend: {
        data: ['参与人数'], // 只显示实际数据系列，不包括背景
        textStyle: {
          color: '#ffffff',
          fontSize: 14
        },
        top: '5%',
        right: '5%'
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: [],
        axisLine: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.2)'
          }
        },
        axisTick: {
          show: false
        },
        axisLabel: {
          color: '#ffffff',
          fontSize: 12,
          rotate: 30
        }
      },
      yAxis: {
        type: 'value',
        max: 300,
        name: '(参与人数)',
        nameTextStyle: {
          color: '#ffffff',
          fontSize: 12
        },
        axisLine: {
          show: false
        },
        axisTick: {
          show: false
        },
        axisLabel: {
          color: '#ffffff',
          fontSize: 12
        },
        splitLine: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.1)'
          }
        }
      },
      series: [
        {
          name: '参与人数',
          type: 'bar',
          data: [],
          // 优化的柱子动画配置
          animation: true,
          animationDuration: 1000, // 每个柱子动画1.5秒
          animationEasing: 'bounceOut',
          animationDelay: function(idx) {
            return idx * 100 // 每个蓝色柱子间隔1.2秒开始
          },
          itemStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [{
                offset: 0, color: 'rgba(55, 137, 255, 1)' // 顶部颜色
              }, {
                offset: 1, color: 'rgba(55, 137, 255, 0.2)' // 底部颜色
              }]
            },
            borderRadius: [4, 4, 0, 0]
          },
          backgroundStyle: {
            color: 'rgba(7,65,124,0.8)'
          },
          showBackground: true,
          barWidth: '20%',
          label: {
            show: true,
            position: 'top',
            color: '#00ffff',
            fontSize: 11,
            fontWeight: 'bold',
            textShadow: '0 0 4px rgba(0, 255, 255, 0.8)',
            formatter: '{c}',
            // 数字动画
            animation: true,
            animationDuration: 600,
            animationEasing: 'bounceOut',
            animationDelay: function(idx) {
              return idx * 2500 + 2000 // 蓝色柱子完成后数字出现
            }
          }
        }
      ]
    }

    fetchReq.get('/system/bigScreen/getValueByKey', { key: 'inen_project_college' }).then(res => {
      if (res.success) {
        option.xAxis.data = res.result.college
        option.series[0].data = res.result.data
      }
    }).finally(() => {
      myChart.setOption(option)
    })

    console.log('reportingChart option set successfully')

    // 将图表实例和配置保存到全局管理器
    window.chartManager.reportingChart = {
      instance: myChart,
      option: option,
      emptyOption: {
        series: [
          { data: [0, 0, 0, 0, 0] },
          { data: [0, 0, 0, 0, 0] }
        ]
      }
    }

    // 响应式处理
    window.addEventListener('resize', function() {
      myChart.resize()
    })

    console.log('reportingChart created successfully')
  } catch (error) {
    console.error('Error creating reportingChart:', error)
  }
}

// 事件上报情况图表 - 使用ECharts
function createReportingCharts() {
  try {
    console.log('Creating reportingCharts...')
    const chartDom = document.getElementById('reportingCharts')
    if (!chartDom) {
      console.error('reportingCharts element not found')
      return
    }
    console.log('reportingCharts element found:', chartDom)
    const myChart = echarts.init(chartDom)
    let option = {
      backgroundColor: 'transparent',
      // 优化的动画配置
      animation: true,
      animationDuration: 1000, // 总动画时长8秒
      animationEasing: 'elasticOut',
      animationDelay: 0, // 全局不延迟，让每个柱子控制自己的延迟
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        },
        backgroundColor: 'rgba(0, 0, 0, 0.8)',
        borderColor: '#00d4ff',
        borderWidth: 1,
        textStyle: {
          color: '#fff'
        }
      },
      legend: {
        data: ['参与人数'], // 只显示实际数据系列，不包括背景
        textStyle: {
          color: '#ffffff',
          fontSize: 14
        },
        top: '5%',
        right: '5%'
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: [],
        axisLine: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.2)'
          }
        },
        axisTick: {
          show: false
        },
        axisLabel: {
          color: '#ffffff',
          fontSize: 12,
          rotate: 30
        }
      },
      yAxis: {
        type: 'value',
        max: 600,
        name: '(参与人数)',
        nameTextStyle: {
          color: '#ffffff',
          fontSize: 12
        },
        axisLine: {
          show: false
        },
        axisTick: {
          show: false
        },
        axisLabel: {
          color: '#ffffff',
          fontSize: 12
        },
        splitLine: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.1)'
          }
        }
      },
      series: [
        {
          name: '参与人数',
          type: 'bar',
          data: [],
          // 优化的柱子动画配置
          animation: true,
          animationDuration: 100, // 每个柱子动画1.5秒
          animationEasing: 'bounceOut',
          animationDelay: function(idx) {
            return idx * 100 // 每个蓝色柱子间隔1.2秒开始
          },
          itemStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [{
                offset: 0, color: 'rgba(55, 137, 255, 1)' // 顶部颜色
              }, {
                offset: 1, color: 'rgba(55, 137, 255, 0.2)' // 底部颜色
              }]
            },
            borderRadius: [4, 4, 0, 0]
          },
          backgroundStyle: {
            color: 'rgba(7,65,124,0.8)'
          },
          showBackground: true,
          barWidth: '20%',
          label: {
            show: true,
            position: 'top',
            color: '#00ffff',
            fontSize: 11,
            fontWeight: 'bold',
            textShadow: '0 0 4px rgba(0, 255, 255, 0.8)',
            formatter: '{c}',
            // 数字动画
            animation: true,
            animationDuration: 600,
            animationEasing: 'bounceOut',
            animationDelay: function(idx) {
              return idx * 2500 + 2000 // 蓝色柱子完成后数字出现
            }
          }
        }

      ]
    }

    fetchReq.get('/system/bigScreen/getValueByKey', { key: 'inen_project_signup' }).then(res => {
      if (res.success) {
        option.xAxis.data = res.result.yearData
        option.series[0].data = res.result.valueData
      }
    }).finally(() => {
      myChart.setOption(option)
    })

    // 将图表实例和配置保存到全局管理器
    window.chartManager.reportingCharts = {
      instance: myChart,
      option: option,
      emptyOption: {
        series: [
          { data: [0, 0, 0, 0, 0] },
          { data: [0, 0, 0, 0, 0] }
        ]
      }
    }

    // 响应式处理
    window.addEventListener('resize', function() {
      myChart.resize()
    })

    console.log('reportingChart created successfully')
  } catch (error) {
    console.error('Error creating reportingChart:', error)
  }
}

// 最近七日上报趋势图表
function createTrendChart() {
  try {
    console.log('Creating trendChart...')
    const chartDom = document.getElementById('trendChart')
    if (!chartDom) {
      console.error('trendChart element not found')
      return
    }
    const myChart = echarts.init(chartDom)

    let option = {
      backgroundColor: 'transparent',
      // 动画配置
      animation: true,
      animationDuration: 3800,
      animationEasing: 'cubicOut',
      animationDelay: function(idx) {
        return idx * 200
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
          label: {
            backgroundColor: '#6a7985'
          }
        },
        backgroundColor: 'rgba(0, 0, 0, 0.8)',
        borderColor: 'rgba(255, 255, 255, 0.2)',
        borderWidth: 1,
        textStyle: {
          color: '#ffffff',
          fontSize: 12
        },
        formatter: function(params) {
          let result = params[0].name + '<br/>'
          const colors = {
            '事件': '#fad870',
            '日志': '#0bb988'
          }
          params.forEach(function(item) {
            const color = colors[item.seriesName] || item.color
            result += '<span style="display:inline-block;margin-right:5px;border-radius:50%;width:6px;height:6px;background-color:' + color + ';"></span>'
            result += item.seriesName + ': ' + item.value + '<br/>'
          })
          return result
        }
      },
      legend: {
        data: [],
        top: '5%',
        right: '5%',
        textStyle: {
          color: '#ffffff',
          fontSize: 14
        },
        itemWidth: 20,
        itemHeight: 6,
        itemGap: 15
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        top: '20%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: [],
        axisLine: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.3)'
          }
        },
        axisTick: {
          show: false
        },
        axisLabel: {
          color: '#ffffff',
          fontSize: 12
        }
      },
      yAxis: {
        type: 'value',
        name: '(获奖数量)',
        nameTextStyle: {
          color: '#ffffff',
          fontSize: 12
        },
        max: 100,
        splitLine: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.1)',
            width: 1
          }
        },
        axisLabel: {
          color: '#ffffff',
          fontSize: 10
        },
        axisLine: {
          show: false
        },
        axisTick: {
          show: false
        }
      },
      series: [
        {
          name: '省级获奖',
          type: 'line',
          smooth: true,
          data: [],
          lineStyle: {
            color: '#fad870',
            width: 3
          },
          itemStyle: {
            color: '#fad870',
            borderColor: '#fad870',
            borderWidth: 2
          },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [{
                offset: 0, color: 'rgba(250, 216, 112, 0.3)'
              }, {
                offset: 1, color: 'rgba(250, 216, 112, 0.05)'
              }]
            }
          },
          symbol: 'circle',
          symbolSize: 6
        },
        {
          name: '国家级获奖',
          type: 'line',
          smooth: true,
          data: [],
          lineStyle: {
            color: '#0bb988',
            width: 3
          },
          itemStyle: {
            color: '#0bb988',
            borderColor: '#0bb988',
            borderWidth: 2
          },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [{
                offset: 0, color: 'rgba(250, 216, 112, 0.3)'
              }, {
                offset: 1, color: 'rgba(250, 216, 112, 0.05)'
              }]
            }
          },
          symbol: 'circle',
          symbolSize: 6
        }
      ]
    }

    // setTimeout(() => {
    //   option.legend.data = ['省级获奖', '国家级获奖']
    //   option.xAxis.data = ['2020年', '2021年', '2022年', '2023年', '2024年']
    //   option.series[0].data = [44, 61, 79, 66, 82]
    //   option.series[1].data = [22, 30, 39, 34, 42]
    //   myChart.setOption(option)
    // }, 5000)

    fetchReq.get('/system/bigScreen/getValueByKey', { key: 'inen_project_award' }).then(res => {
      if (res.success) {
        option.legend.data = res.result.levelName
        option.xAxis.data = res.result.year
        option.series[0].data = res.result.level2
        option.series[1].data = res.result.level1
      }
    }).finally(() => {
      myChart.setOption(option)
    })
    console.log('trendChart created successfully')

    // 将图表实例和配置保存到全局管理器
    window.chartManager.trendChart = {
      instance: myChart,
      option: option,
      emptyOption: {
        series: [
          { data: [0, 0, 0, 0, 0, 0, 0] },
          { data: [0, 0, 0, 0, 0, 0, 0] }
        ]
      }
    }

    // 响应式处理
    window.addEventListener('resize', function() {
      myChart.resize()
    })
  } catch (error) {
    console.error('Error creating trendChart:', error)
  }
}


// 事件得分图表
function createChart() {
  try {
    console.log('Creating scoreChart...')
    const chartDom = document.getElementById('scoreChart')
    if (!chartDom) {
      console.error('scoreChart element not found')
      return
    }
    const myChart = echarts.init(chartDom)

    const option = {
      backgroundColor: 'transparent',
      // 动画配置
      animation: true,
      animationDuration: 18000, // 总动画时长18秒（5个柱子 × 3.5秒 + 缓冲）
      animationEasing: 'cubicOut',
      animationDelay: 0, // 全局不延迟，让柱子控制自己的延迟
      animationDurationUpdate: 1500,
      animationEasingUpdate: 'cubicInOut',
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        },
        backgroundColor: 'rgba(0, 0, 0, 0.8)',
        borderColor: 'rgba(255, 255, 255, 0.2)',
        borderWidth: 1,
        textStyle: {
          color: '#ffffff',
          fontSize: 12
        },
        formatter: function(params) {
          return params[0].name + '<br/>' +
            '得分: ' + params[0].value + '分'
        }
      },
      legend: {
        data: ['参与总人数：1961'], // 只显示实际数据系列，不包括背景
        textStyle: {
          color: '#ffffff',
          fontSize: 10
        },
        top: '5%',
        right: '5%'
      },
      grid: {
        left: '2%',
        right: '2%',
        bottom: '5%',
        top: '25%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: ['2019级', '2020级', '2021级', '2022级', '2023级'],
        axisLine: {
          show: false
        },
        axisTick: {
          show: false
        },
        axisLabel: {
          color: '#ffffff',
          fontSize: 12
        }
      },
      yAxis: {
        type: 'value',
        name: '(报名人数)',
        nameTextStyle: {
          color: '#ffffff',
          fontSize: 12
        },
        max: 1200,
        splitLine: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.1)',
            width: 1
          }
        },
        axisLabel: {
          color: '#ffffff',
          fontSize: 10
        },
        axisLine: {
          show: false
        },
        axisTick: {
          show: false
        }
      },
      series: [
        {
          name: '报名人数',
          type: 'bar',
          data: [1, 14, 477, 1147, 322],
          // 柱状图动画配置
          animation: true,
          animationDuration: 2500, // 每个柱子动画2.5秒
          animationEasing: 'cubicOut',
          animationDelay: function(idx) {
            return idx * 3500 // 每个柱子间隔3.5秒开始
          },
          itemStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [{
                offset: 0, color: 'rgba(55, 137, 255, 1)' // 顶部亮蓝色
              }, {
                offset: 1, color: 'rgba(55, 137, 255, 0.2)' // 底部深蓝色
              }]
            },
            // 添加阴影效果
            shadowColor: 'rgba(55, 137, 255, 0.4)',
            shadowBlur: 10,
            shadowOffsetY: 5
          },
          backgroundStyle: {
            color: 'rgba(7,62,119,0.5)'
          },
          showBackground: true,
          barWidth: '40%',
          label: {
            show: true,
            position: 'top',
            color: '#00ffff',
            fontSize: 12,
            fontWeight: 'bold',
            fontFamily: 'Arial, sans-serif',
            textShadow: '0 0 6px rgba(0, 255, 255, 0.8)',
            formatter: '{c}', // 显示数值
            // 标签动画
            animation: true,
            animationDuration: 800, // 数字出现动画时长
            animationEasing: 'elasticOut',
            animationDelay: function(idx) {
              return idx * 3500 + 2500 // 标签在柱子动画完成后出现
            }
          },
          // 添加强调效果
          emphasis: {
            itemStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [{
                  offset: 0, color: 'rgba(55, 137, 255, 1)'
                }, {
                  offset: 1, color: 'rgba(55, 137, 255, 0.4)'
                }]
              },
              shadowColor: 'rgba(55, 137, 255, 0.8)',
              shadowBlur: 20,
              shadowOffsetY: 8
            }
          }
        }
      ]
    }

    myChart.setOption(option)

    // 将图表实例和配置保存到全局管理器
    window.chartManager.scoreChart = {
      instance: myChart,
      option: option,
      emptyOption: {
        series: [{
          data: [0, 0, 0, 0, 0]
        }]
      }
    }

    // 响应式处理
    window.addEventListener('resize', function() {
      myChart.resize()
    })
    console.log('scoreChart created successfully')
  } catch (error) {
    console.error('Error creating scoreChart:', error)
  }
}

// 事件总数区域的简单粒子效果
class TotalEventsParticles {
  constructor() {
    this.canvas = document.getElementById('totalEventsParticles')
    if (!this.canvas) return

    this.ctx = this.canvas.getContext('2d')
    this.particles = []
    this.particleCount = 15

    this.init()
    this.createParticles()
    this.animate()
  }

  init() {
    const rect = this.canvas.parentElement.getBoundingClientRect()
    this.canvas.width = 169
    this.canvas.height = 141
  }

  createParticles() {
    this.particles = []
    for (let i = 0; i < this.particleCount; i++) {
      this.particles.push({
        x: Math.random() * this.canvas.width,
        y: Math.random() * this.canvas.height,
        vx: (Math.random() - 0.5) * 0.3,
        vy: (Math.random() - 0.5) * 0.3,
        size: Math.random() * 1.5 + 0.5,
        opacity: Math.random() * 0.4 + 0.2,
        life: Math.random() * 100 + 50
      })
    }
  }

  updateParticles() {
    this.particles.forEach((particle, index) => {
      particle.x += particle.vx
      particle.y += particle.vy
      particle.life--

      // 边界检测
      if (particle.x < 0 || particle.x > this.canvas.width) particle.vx *= -1
      if (particle.y < 0 || particle.y > this.canvas.height) particle.vy *= -1

      // 保持在画布内
      particle.x = Math.max(0, Math.min(this.canvas.width, particle.x))
      particle.y = Math.max(0, Math.min(this.canvas.height, particle.y))

      // 重生粒子
      if (particle.life <= 0) {
        particle.x = Math.random() * this.canvas.width
        particle.y = Math.random() * this.canvas.height
        particle.life = Math.random() * 100 + 50
        particle.opacity = Math.random() * 0.4 + 0.2
      }
    })
  }

  drawParticles() {
    this.particles.forEach(particle => {
      this.ctx.beginPath()
      this.ctx.arc(particle.x, particle.y, particle.size, 0, Math.PI * 2)
      this.ctx.fillStyle = `rgba(134, 216, 245, ${particle.opacity})`
      this.ctx.fill()

      // 添加发光效果
      this.ctx.shadowColor = 'rgba(134, 216, 245, 0.8)'
      this.ctx.shadowBlur = 3
    })
  }

  animate() {
    this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height)
    this.ctx.shadowColor = 'transparent'
    this.ctx.shadowBlur = 0

    this.updateParticles()
    this.drawParticles()

    requestAnimationFrame(() => this.animate())
  }
}

// 数字递增动画函数
function animateNumber(element, targetValue, duration = 2000) {
  const startValue = 0
  const startTime = performance.now()

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

    // 使用缓动函数让动画更自然
    const easeOutQuart = 1 - Math.pow(1 - progress, 4)
    const currentValue = Math.floor(startValue + (targetValue - startValue) * easeOutQuart)

    element.textContent = currentValue

    if (progress < 1) {
      requestAnimationFrame(updateNumber)
    } else {
      element.textContent = targetValue
    }
  }

  requestAnimationFrame(updateNumber)
}

// 为所有数字元素添加递增动画
function initNumberAnimations() {
  // 获取所有数字元素（现在查找 .number 类）
  const numberElements = document.querySelectorAll('.data-value .number')
  const totalNumber = document.querySelector('.total-number')

  // 存储原始数值
  const originalValues = []
  numberElements.forEach(element => {
    originalValues.push(parseInt(element.textContent))
  })
  const totalOriginalValue = totalNumber ? parseInt(totalNumber.textContent) : 0

  // 执行一次动画的函数
  function runAnimationCycle() {
    // 为每个数字元素添加动画
    numberElements.forEach((element, index) => {
      const targetValue = originalValues[index]

      if (!isNaN(targetValue)) {
        // 延迟动画，创建交错效果
        setTimeout(() => {
          animateNumber(element, targetValue, 2500 + index * 150)
        }, index * 250)
      }
    })

    // 为事件总数添加动画
    if (totalNumber) {
      setTimeout(() => {
        animateNumber(totalNumber, totalOriginalValue, 3500)
      }, 800)
    }
  }

  // 立即执行第一次动画
  runAnimationCycle()


}

// 动态时间显示函数
function updateDateTime() {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  const seconds = String(now.getSeconds()).padStart(2, '0')

  const dateTimeString = `${year}年${month}月${day}日${hours}:${minutes}:${seconds}`

  const datetimeElement = document.getElementById('datetime')
  if (datetimeElement) {
    // 保留图标，只更新时间文本
    const img = datetimeElement.querySelector('img')
    if (img) {
      datetimeElement.innerHTML = img.outerHTML + dateTimeString
    } else {
      datetimeElement.textContent = dateTimeString
    }
  }
}

// 页面加载完成后初始化所有图表和动画
document.addEventListener('DOMContentLoaded', function() {
  // 添加页面加载动画
  document.body.style.opacity = '0'
  document.body.style.transform = 'scale(0.98)'
  document.body.style.transition = 'all 0.8s cubic-bezier(0.4, 0, 0.2, 1)'

  // 页面淡入动画
  setTimeout(() => {
    document.body.style.opacity = '1'
    document.body.style.transform = 'scale(1)'
  }, 100)

  // 初始化动态时间
  updateDateTime()
  // 每秒更新时间
  setInterval(updateDateTime, 1000)

  setTimeout(() => {
    createUrgencyChart()
    createReportingChart()
    createReportingCharts()
    createTrendChart()
    initStatusTable()
    // 初始化数字动画
    initNumberAnimations()

    // 添加数字计数动画
    animateNumbers()

    // 初始化事件总数区域的粒子效果
    new TotalEventsParticles()

    // 隐藏加载指示器
    setTimeout(() => {
      const loadingOverlay = document.getElementById('loadingOverlay')
      if (loadingOverlay) {
        loadingOverlay.classList.add('hidden')
        setTimeout(() => {
          loadingOverlay.style.display = 'none'
        }, 500)
      }
    }, 1500)

    // 添加窗口大小变化监听器
    window.addEventListener('resize', resizeCharts)
    // 添加全屏变化监听器
    document.addEventListener('fullscreenchange', resizeCharts)
    document.addEventListener('webkitfullscreenchange', resizeCharts)
    document.addEventListener('mozfullscreenchange', resizeCharts)
    document.addEventListener('MSFullscreenChange', resizeCharts)

    // 启动统一的动画循环（15秒一次）
    setTimeout(() => {
      console.log('启动统一动画循环...')
      setInterval(playAllAnimations, 15000)
    }, 2000) // 等待所有图表初始化完成后再开始循环

  }, 100)
})

// 数字计数动画函数
function animateNumbers() {
  const numberElements = document.querySelectorAll('.data-value .number, .total-number')

  numberElements.forEach((element, index) => {
    const finalValue = parseInt(element.textContent)
    if (isNaN(finalValue)) return

    const duration = 2000 // 2秒动画
    const startTime = Date.now() + (index * 100) // 交错开始

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

      // 使用缓动函数
      const easeOutQuart = 1 - Math.pow(1 - progress, 4)
      const currentValue = Math.floor(finalValue * easeOutQuart)

      element.textContent = currentValue

      if (progress < 1) {
        requestAnimationFrame(updateNumber)
      } else {
        element.textContent = finalValue
      }
    }

    // 延迟开始动画
    setTimeout(() => {
      element.textContent = '0'
      updateNumber()
    }, index * 100 + 800) // 等待页面动画完成后开始
  })
}

// 统一动画管理器
function playAllAnimations() {
  console.log('开始播放所有图表动画...')

  // 遍历所有图表并播放动画
  Object.keys(window.chartManager || {}).forEach(chartKey => {
    const chart = window.chartManager[chartKey]

    if (chart.playAnimation) {
      // 特殊动画函数（如日志图表）
      chart.playAnimation()
    } else if (chart.emptyOption && chart.option) {
      // 标准动画（清空 -> 恢复）
      chart.instance.setOption(chart.emptyOption, false)
      setTimeout(() => {
        chart.instance.setOption(chart.option, false)
      }, 100)
    }
  })
}

// 图表大小调整函数
function resizeCharts() {
  setTimeout(() => {
    // 获取所有ECharts实例并重新调整大小
    const chartElements = document.querySelectorAll('[id$="Chart"]')
    chartElements.forEach(element => {
      const chart = echarts.getInstanceByDom(element)
      if (chart) {
        chart.resize()
      }
    })
  }, 100)
}

// 数据更新动画
function animateDataUpdate(element) {
  element.style.animation = 'pulse 0.3s ease-in-out'
  setTimeout(() => {
    element.style.animation = ''
  }, 300)
}

// 模拟数据更新


// 全屏模式检测和自适应
function handleFullscreenChange() {
  console.log('Fullscreen change detected')

  // 延迟执行以确保DOM更新完成
  setTimeout(() => {
    resizeCharts()
    adjustStatsGridForFullscreen()
    console.log('Charts resized and stats grid adjusted after fullscreen change')
  }, 200)
}

// 调整stats-grid以适应全屏模式
function adjustStatsGridForFullscreen() {
  const statsGrid = document.querySelector('.stats-grid')
  const widget = document.querySelector('.widget')
  const leftColumn = document.querySelector('.left-column')

  if (!statsGrid || !widget || !leftColumn) return

  const isFullscreen = document.fullscreenElement ||
    document.webkitFullscreenElement ||
    document.mozFullScreenElement ||
    document.msFullscreenElement

  if (isFullscreen) {
    console.log('Adjusting stats-grid for fullscreen mode')

    // 强制刷新布局
    setTimeout(() => {
      // 计算可用高度
      const leftColumnHeight = leftColumn.clientHeight
      const widgetTitle = widget.querySelector('.widget-title')
      const titleHeight = widgetTitle ? widgetTitle.offsetHeight + 20 : 60
      const availableHeight = leftColumnHeight - titleHeight - 40

      // 设置stats-grid高度和布局
      statsGrid.style.height = `${availableHeight}px`
      statsGrid.style.gridTemplateRows = 'repeat(3, 1fr)'
      statsGrid.style.gridTemplateColumns = 'repeat(3, 1fr)'
      statsGrid.style.alignContent = 'stretch'
      statsGrid.style.alignItems = 'stretch'
      statsGrid.style.gap = '0'
      statsGrid.style.padding = '10px 0'

      // 设置每个stat-item的高度
      const statItems = statsGrid.querySelectorAll('.stat-item')
      const itemHeight = Math.floor((availableHeight - 20) / 3) - 16

      statItems.forEach(item => {
        item.style.height = `${itemHeight}px`
        item.style.margin = '8px'
        item.style.display = 'flex'
        item.style.alignItems = 'center'
        item.style.justifyContent = 'flex-start'
        item.style.border = '1px solid rgba(134, 216, 245, 0.3)'
        item.style.borderRadius = '8px'
        item.style.background = 'rgba(7, 62, 119, 0.4)'
        item.style.padding = '15px'
      })

      console.log(`Stats grid height set to: ${availableHeight}px, item height: ${itemHeight}px`)
    }, 100)

  } else {
    // 退出全屏时恢复默认样式
    statsGrid.style.height = ''
    statsGrid.style.gridTemplateRows = ''
    statsGrid.style.gridTemplateColumns = ''
    statsGrid.style.alignContent = ''
    statsGrid.style.alignItems = ''
    statsGrid.style.gap = ''
    statsGrid.style.padding = ''

    // 恢复stat-item样式
    const statItems = statsGrid.querySelectorAll('.stat-item')
    statItems.forEach(item => {
      item.style.height = ''
      item.style.margin = ''
      item.style.display = ''
      item.style.alignItems = ''
      item.style.justifyContent = ''
      item.style.border = ''
      item.style.borderRadius = ''
      item.style.background = ''
      item.style.padding = ''
    })

    console.log('Stats grid restored to normal mode')
  }
}

// 窗口大小改变时的处理
function handleResize() {
  // 延迟执行以确保DOM更新完成
  setTimeout(() => {
    resizeCharts()
    adjustStatsGridForFullscreen()
  }, 100)
}


// 监听窗口大小变化
window.addEventListener('resize', handleResize)

// 监听F11按键
document.addEventListener('keydown', function(event) {
  if (event.key === 'F11') {
    // F11被按下，延迟检查全屏状态
    setTimeout(handleFullscreenChange, 100)
  }
})

// 强制全屏布局函数
function forceFullscreenLayout() {
  const body = document.body
  const html = document.documentElement
  const dashboard = document.querySelector('.dashboard')

  console.log('Before layout - Body height:', body.style.height, 'Dashboard height:', dashboard ? dashboard.style.height : 'N/A')
  console.log('Window size:', window.innerWidth, 'x', window.innerHeight)
  console.log('Screen size:', screen.width, 'x', screen.height)

  // 强制设置body和html高度，保留底部20px间距
  body.style.height = 'calc(100vh - 20px)'
  body.style.minHeight = 'calc(100vh - 20px)'
  body.style.maxHeight = 'calc(100vh - 20px)'
  body.style.overflow = 'hidden'
  body.style.margin = '0'
  body.style.padding = '0 0 20px 0'

  html.style.height = 'calc(100vh - 20px)'
  html.style.minHeight = 'calc(100vh - 20px)'
  html.style.maxHeight = 'calc(100vh - 20px)'
  html.style.overflow = 'hidden'
  html.style.paddingBottom = '20px'

  // 强制设置dashboard高度，保留底部20px间距
  if (dashboard) {
    dashboard.style.height = 'calc(100vh - 20px)'
    dashboard.style.minHeight = 'calc(100vh - 20px)'
    dashboard.style.maxHeight = 'calc(100vh - 20px)'
    dashboard.style.width = '100vw'
    dashboard.style.overflow = 'hidden'

    // 强制设置三列高度
    const columns = dashboard.querySelectorAll('.left-column, .center-column, .right-column')
    columns.forEach(column => {
      column.style.height = 'calc(100vh - 120px)'
      column.style.maxHeight = 'calc(100vh - 120px)'
    })
  }

  console.log('After layout - Body height:', body.style.height, 'Dashboard height:', dashboard ? dashboard.style.height : 'N/A')
  console.log('Forced fullscreen layout applied with 20px bottom margin')
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
  // 强制应用全屏布局
  forceFullscreenLayout()

  // 初始化时检查是否已经是全屏状态
  handleFullscreenChange()

  // 确保所有图表正确显示
  setTimeout(() => {
    resizeCharts()
    adjustStatsGridForFullscreen()
  }, 500)
})

// 窗口加载完成后再次强制布局
window.addEventListener('load', function() {
  setTimeout(() => {
    forceFullscreenLayout()
    resizeCharts()
    adjustStatsGridForFullscreen()
  }, 100)
})


// 初始化状态表格
function initStatusTable() {
  const tableBody = document.getElementById('statusTableBody')
  if (!tableBody) return
  let statusData = []
  fetchReq.get('/system/bigScreen/getValueByKey', { key: 'inen_project_items' }).then(res => {
    if (res.success) {
      statusData = res.result
      // 复制数据以实现无缝滚动
      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>`
        // 添加鼠标悬停效果
        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'
          }
        })
      }
    }
  })

}