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

<script>
import * as echarts from 'echarts'

export default {
  name: 'OeeTrendChart',
  props: {
    data: {
      type: Array,
      default: () => []
    }
  },
  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 : []
      const x = list.map(d => d.statDate)
      const oee = list.map(d => Number(d.oee || 0))
      const a = list.map(d => Number(d.availability || 0))
      const p = list.map(d => Number(d.performanceTon || 0))
      const q = list.map(d => Number(d.quality || 0))
      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: params => {
            const title = (params && params[0] && params[0].axisValue) || ''
            const lines = (params || []).map(p0 => `${p0.marker}${p0.seriesName}：${this.toFixed3(p0.value)} %`)
            return [title, ...lines].join('<br/>')
          }
        },
        legend: { top: 0, left: 'center' },
        grid: { left: 40, right: 20, top: 30, bottom: 40 },
        xAxis: { type: 'category', data: x },
        yAxis: {
          type: 'value',
          name: '百分比 (%)',
          axisLabel: { formatter: v => this.toFixed3(v) }
        },
        series: [
          { name: 'OEE', type: 'line', data: oee, smooth: true },
          { name: 'A', type: 'line', data: a, smooth: true },
          { name: 'P_ton', type: 'line', data: p, smooth: true },
          { name: 'Q', type: 'line', data: q, smooth: true }
        ]
      }
      this.chart.setOption(option)
    },
    handleResize() {
      this.chart && this.chart.resize()
    }
  }
}
</script>

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