<template>
  <div class="panel safety-compliance">
    <div class="border-beam"></div>
    <div class="panel-header">
      <div class="panel-header-icon">📊</div>
      <span class="panel-title">实验室安全分级统计</span>
    </div>
    <div class="chart-wrap">
      <div ref="chart" class="chart"></div>
    </div>
  </div>
</template>

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

export default {
  name: 'SafetyCompliance',
  data() {
    return {
      chart: null,
      scrollTimer: null,
      scrollIndex: 0,
      pollTimer: null
    }
  },
  mounted() {
    this.fetchData()
    this.pollTimer = setInterval(this.fetchData, 5 * 60 * 1000)
  },
  beforeDestroy() {
    if (this.pollTimer) clearInterval(this.pollTimer)
    if (this.scrollTimer) {
      clearInterval(this.scrollTimer)
      this.scrollTimer = null
    }
    if (this.chart) {
      this.chart.dispose()
      this.chart = null
    }
  },
  methods: {
    async fetchData() {
      try {
        const res = await getLabBasicStatistics()
        if (res.code === 200) {
          const list = res.data.labLevelVOList || []
          const chartData = {
            levels: ['I级', 'II级', 'III级', 'IV级'],
            colors: ['#cc0000', '#ff8000', '#ffcc00', '#0066cc'],
            units:  list.map(i => i.deptName),
            totals: list.map(i => i.levelOneCount + i.levelTwoCount + i.levelThreeCount + i.levelFourCount),
            series: [
              list.map(i => i.levelOneCount),
              list.map(i => i.levelTwoCount),
              list.map(i => i.levelThreeCount),
              list.map(i => i.levelFourCount)
            ]
          }
          if (this.chart) {
            this.chart.dispose()
            this.chart = null
          }
          this.$nextTick(() => this.initChart(chartData))
        }
      } catch (e) {
        // 错误已由拦截器处理
      }
    },
    /** 初始化堆叠柱状图 - 展示各单位实验室安全分级统计 */
    initChart(data) {
      this.chart = echarts.init(this.$refs.chart, null, {
        renderer: 'canvas',
        devicePixelRatio: 2
      })

      const { levels, colors, units, totals, series: seriesData } = data

      // X-axis labels: "unitName\n(total)"
      const xLabels = units.map((u, i) => `${u}\n(${totals[i]})`)

      const TOOLTIP_CFG = {
        backgroundColor: 'rgba(3,14,42,0.92)',
        borderColor: 'rgba(30,144,255,0.3)',
        textStyle: { color: '#a8cce8', fontSize: 28 }
      }

      const option = {
        backgroundColor: 'transparent',
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'shadow' },
          ...TOOLTIP_CFG
        },
        legend: {
          data: levels,
          top: 0,
          right: 0,
          textStyle: { color: '#a8cce8', fontSize: 25 },
          icon: 'rect',
          itemWidth: 25,
          itemHeight: 15
        },
        grid: {
          left: 30,
          right: 8,
          top: 55,
          bottom: 110,
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: xLabels,
          axisLabel: {
            color: '#5890b8',
            fontSize: 22,
            interval: 0,
            lineHeight: 35
          },
          axisLine: { lineStyle: { color: 'rgba(30,144,255,0.2)' } },
          axisTick: { show: false }
        },
        yAxis: {
          type: 'value',
          name: '间',
          nameTextStyle: { color: '#5890b8', fontSize: 25 },
          axisLabel: { color: '#5890b8', fontSize: 25 },
          axisLine: { show: false },
          splitLine: { lineStyle: { color: 'rgba(30,144,255,0.1)' } }
        },
        dataZoom: [{
          type: 'inside',
          startValue: 0,
          endValue: 5
        }],
        series: levels.map((name, i) => ({
          name: name,
          type: 'bar',
          stack: 'total',
          barMaxWidth: 55,
          data: seriesData[i].map(v => ({
            value: v,
            itemStyle: { color: colors[i], opacity: 0.88 }
          })),
          emphasis: { itemStyle: { opacity: 1 } }
        }))
      }

      this.chart.setOption(option)

      // Auto-scroll dataZoom every 5 seconds
      this.scrollIndex = 0
      this.scrollTimer = setInterval(() => {
        this.scrollIndex++
        if (this.scrollIndex >= units.length - 5) {
          this.scrollIndex = -1
        }
        if (this.chart) {
          this.chart.dispatchAction({
            type: 'dataZoom',
            startValue: this.scrollIndex,
            endValue: this.scrollIndex + 5
          })
        }
      }, 5000)
    }
  }
}
</script>

<style lang="scss" scoped>
.safety-compliance {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.chart-wrap {
  flex: 1;
  min-height: 0;
  padding: 15px 20px;

  .chart {
    width: 100%;
    height: 100%;
  }
}
</style>
