<template>
  <div class="oee-chart" ref="chartRef"></div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: 'OeeStoppageTop',
  props: {
    data: {
      type: Array,
      default: () => []
    },
    topN: {
      type: Number,
      default: 10
    }
  },
  data() {
    return {
      chart: null
    }
  },
  mounted() {
    this.initChart()
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
    if (this.chart) {
      this.chart.dispose()
      this.chart = null
    }
  },
  watch: {
    data: {
      deep: true,
      immediate: true,
      handler() {
        this.render()
      }
    }
  },
  methods: {
    toFixed3(val) {
      const n = Number(val)
      return Number.isFinite(n) ? n.toFixed(3) : '-'
    },
    initChart() {
      if (!this.$refs.chartRef) return
      this.chart = echarts.init(this.$refs.chartRef)
    },
    render() {
      if (!this.chart) this.initChart()
      if (!this.chart) return
      const list = Array.isArray(this.data) ? this.data.slice() : []
      list.sort((a, b) => (b.duration || 0) - (a.duration || 0))
      const top = list.slice(0, this.topN)
      const names = top.map((d, idx) => `${idx + 1}. ${d.stopType || '未知'}`)
      const mins = top.map(d => Number(((d.duration || 0) / 60).toFixed(3)))
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'shadow' },
          formatter: params => {
            const p = params && params[0]
            if (!p) return ''
            return `${p.name}<br/>${p.marker}${p.seriesName}：${this.toFixed3(p.value)} min`
          }
        },
        grid: { left: 140, right: 20, top: 20, bottom: 20 },
        xAxis: {
          type: 'value',
          name: '停机时间 (min)',
          axisLabel: { formatter: v => this.toFixed3(v) }
        },
        yAxis: {
          type: 'category',
          data: names,
          axisLabel: { fontSize: 11 }
        },
        series: [
          {
            name: '停机时间 (min)',
            type: 'bar',
            data: mins,
            itemStyle: { color: '#67C23A' }
          }
        ]
      }
      this.chart.setOption(option)
    },
    handleResize() {
      this.chart && this.chart.resize()
    }
  }
}
</script>

<style scoped>
.oee-chart {
  width: 100%;
  height: 260px;
}
</style>