<template>
  <div class="panel-box safety-level">
    <div class="corner-deco tl"></div><div class="corner-deco tr"></div>
    <div class="corner-deco bl"></div><div class="corner-deco br"></div>
    <div class="panel-title">实验室安全分级统计</div>
    <div class="panel-content">
      <div ref="chart" class="chart-area"></div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { getSafetyLevelStats } from '@/api'

export default {
  name: 'SafetyLevel',
  data() {
    return { chart: null, scrollTimer: null, timer: null }
  },
  async mounted() {
    await this.loadData()
    this.timer = setInterval(this.loadData, 5 * 60 * 1000)
  },
  beforeDestroy() {
    if (this.chart) this.chart.dispose()
    if (this.scrollTimer) clearInterval(this.scrollTimer)
    clearInterval(this.timer)
  },
  methods: {
    async loadData() {
      try {
        const res = await getSafetyLevelStats()
        const { departments, levelCfg } = res.data
        const levelKeys = ['level1', 'level2', 'level3', 'level4']
        const xData = departments.map(d => {
          const total = levelCfg.reduce((sum, _, i) => sum + (d[levelKeys[i]] || 0), 0)
          return d.name + '\n(' + total + ')'
        })
        if (this.chart) {
          this.chart.setOption({
            legend: { data: levelCfg.map(l => l.name) },
            xAxis: { data: xData },
            series: levelCfg.map((l, i) => ({ name: l.name, data: departments.map(d => d['level' + (i + 1)]) }))
          })
        } else {
          this.$nextTick(() => this.initChart(departments, levelCfg, xData))
        }
      } catch (e) {
        console.error('SafetyLevel:', e)
      }
    },
    initChart(departments, levelCfg, xData) {
      this.chart = echarts.init(this.$refs.chart)
      const levelKeys = ['level1', 'level2', 'level3', 'level4']

      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'shadow' },
          backgroundColor: 'rgba(6,22,56,0.9)',
          borderColor: 'rgba(72,180,255,0.3)',
          textStyle: { color: '#d8f4ff' }
        },
        legend: {
          data: levelCfg.map(l => l.name),
          top: 0,
          textStyle: { color: '#7eacc8', fontSize: 11 },
          itemWidth: 10,
          itemHeight: 10
        },
        grid: { left: 40, right: 10, top: 35, bottom: 50 },
        xAxis: {
          type: 'category',
          data: xData,
          axisLabel: {
            color: '#7eacc8',
            fontSize: 10,
            interval: 0
          },
          axisLine: { lineStyle: { color: 'rgba(72,180,255,0.2)' } },
          axisTick: { show: false }
        },
        yAxis: {
          type: 'value',
          axisLabel: { color: '#7eacc8', fontSize: 10 },
          axisLine: { lineStyle: { color: 'rgba(72,180,255,0.2)' } },
          splitLine: { lineStyle: { color: 'rgba(72,180,255,0.08)' } }
        },
        dataZoom: [{ type: 'slider', show: false, xAxisIndex: 0, startValue: 0, endValue: 5 }],
        series: levelCfg.map((l, i) => ({
          name: l.name,
          type: 'bar',
          stack: 'total',
          barWidth: i === 0 ? 20 : undefined,
          data: departments.map(d => d[levelKeys[i]]),
          itemStyle: { color: l.color, borderRadius: i === levelCfg.length - 1 ? [3, 3, 0, 0] : undefined }
        }))
      }
      this.chart.setOption(option)

      // 自动滚动X轴
      if (departments.length > 6) {
        let idx = 0
        this.scrollTimer = setInterval(() => {
          idx++
          if (idx > departments.length - 5) idx = 0
          this.chart.dispatchAction({ type: 'dataZoom', startValue: idx, endValue: idx + 5 })
        }, 5000)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.safety-level {
  display: flex;
  flex-direction: column;
}

.chart-area {
  flex: 1;
  min-height: 0;
  width: 100%;
}
</style>
