<template>
  <div ref="chart" :style="{ width: '100%', height: '100%' }"></div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: 'MiniLine',
  props: {
    data: {
      type: Array,
      required: true
    },
    color: {
      type: String,
      default: '#409EFF'
    },
    title: {
      type: String,
      default: ''
    },
    prefix: {
      type: String,
      default: ''
    },
    suffix: {
      type: String,
      default: ''
    },
    tooltipFormatter: {
      type: Function,
      default: null
    }
  },
  data() {
    return {
      chart: null
    }
  },
  mounted() {
    this.initChart()
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose()
      this.chart = null
    }
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$refs.chart)
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'none'
          },
          backgroundColor: 'rgba(50, 50, 50, 0.8)',
          borderWidth: 0,
          padding: [5, 10],
          textStyle: {
            color: '#fff',
            fontSize: 12
          },
          formatter: (params) => {
            if (this.tooltipFormatter) {
              return this.tooltipFormatter(params[0]);
            }
            return params[0].value;
          },
          position: function (pos, params, el, elRect, size) {
            // 将 tooltip 固定在数据点上方
            return {
              top: pos[1] - 40,
              left: pos[0] - 50
            };
          }
        },
        grid: {
          left: 0,
          right: 0,
          top: 0,
          bottom: 0
        },
        xAxis: {
          type: 'category',
          show: false,
          boundaryGap: false
        },
        yAxis: {
          type: 'value',
          show: false
        },
        series: [{
          data: this.data,
          type: 'line',
          smooth: true,
          symbol: 'circle',
          symbolSize: 6,
          showSymbol: false,
          emphasis: {
            scale: false,
            focus: 'series'
          },
          lineStyle: {
            color: this.color,
            width: 2
          },
          itemStyle: {
            color: this.color,
            borderWidth: 2,
            borderColor: '#fff'
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
              offset: 0,
              color: this.color
            }, {
              offset: 1,
              color: 'rgba(255, 255, 255, 0)'
            }])
          }
        }]
      }
      
      this.chart.setOption(option)
    }
  },
  watch: {
    data: {
      handler(newValue) {
        this.chart && this.chart.setOption({
          series: [{
            data: newValue
          }]
        })
      },
      deep: true
    }
  }
}
</script>