<template>
  <div :id="id" :class="className" :style="{height:height,minWidth:width}" />
</template>

<script>
import echarts from 'echarts'
import moment from 'moment'
import resize from './mixins/resize'

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    id: {
      type: String,
      default: 'chart'
    },
    title: {
      type: String,
      default: 'line'
    },
    width: {
      type: String,
      default: '500px'
    },
    height: {
      type: String,
      default: '400px'
    },
    lineData: {
      type: Array,
      default: () => {
        return []
      }
    },
    description: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    lineData: function(val) {
      this.updateChart(val)
    }
  },
  mounted() {
    this.initChart()
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    updateChart(data) {
      const xAxis = []
      const series = []
      data.forEach(v => {
        xAxis.push(moment(v.time).format('HH:mm:ss'))
        series.push(v.value)
      })
      this.chart.setOption({
        xAxis: {
          data: xAxis
        },
        series: [{
          name: this.title,
          data: series
        }]
      })
    },
    initChart() {
      this.chart = echarts.init(document.getElementById(this.id))

      this.chart.setOption({
        title: {
          text: `${this.title}监控图表`,
          subtext: `单位为: ${this.description}`
        },
        tooltip: {},
        legend: {
          data: [this.title]
        },
        xAxis: {
          data: []
        },
        yAxis: {},
        series: [{
          name: this.title,
          type: 'line',
          data: []
        }]
      })
    }
  }
}
</script>
