<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: ''
    },
    config: {
      type: Object,
      default: () => {
        return {}
      }
    },
    format: {
      type: String,
      default: 'HH:mm:ss'
    }
  },
  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(this.format))
        series.push(v.value)
      })
      this.chart.setOption({
        title: {
          text: `${this.title}监控图表`,
          subtext: `单位为: ${this.description}`
        },
        xAxis: {
          data: xAxis
        },
        series: [{
          name: this.title,
          data: series
        }]
      })
    },
    initChart() {
      this.chart = echarts.init(document.getElementById(this.id))
      let config = {
        title: {
          text: `${this.title}监控图表`,
          subtext: `单位为: ${this.description}`
        },
        tooltip: {},
        legend: {
          data: [this.title]
        },
        xAxis: {
          data: []
        },
        yAxis: {},
        series: [{
          name: this.title,
          type: 'line',
          data: []
        }]
      }
      config = {
        ...config,
        ...this.config
      }

      this.chart.setOption(config)
    }
  }
}
</script>
