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

<script>

import echarts from 'echarts'
import resize from './mixins/resize'

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    id: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '600px'
    },
    height: {
      type: String,
      default: '400px'
    },
    title: {
      type: String,
      default: ''
    },
    desc: {
      type: String,
      default: ''
    },
    showTitle: {
      type: String,
      default: ''
    },
    seriesData: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data() {
    return {
      chart: null
    }
  },
  computed: {
    legendData() {
      let data = Object.assign([], this.seriesData)
      if (data.length < 1) {
        data = [0, 0]
      }
      const out = []
      data.map(item => {
        out.push([item.date || 0, item.value || 0])
      })
      return out
    }
  },
  watch: {
    seriesData: {
      handler(newVal, oldVal) {
        this.initChart()
      },
      deep: true
    }
  },
  mounted() {
    this.initChart()
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.$nextTick(() => {
        this.chart = echarts.init(document.getElementById(this.id))
        this.chart.clear()
        this.chart.setOption({
          title: {
            text: this.title
          },
          tooltip: {
            trigger: 'axis'
          },
          xAxis: {
            data: this.legendData.length > 0 ? this.legendData.map(function(item) {
              return item[0]
            }) : [0]
          },
          yAxis: {
            splitLine: {
              show: false
            }
          },
          dataZoom: [{
            startValue: this.changeTime()
          }, {
            type: 'inside'
          }],
          visualMap: {
            top: 10,
            right: 10,
            outOfRange: {
              color: '#999'
            }
          },
          series: {
            name: this.showTitle,
            type: 'line',
            data: this.legendData.length > 0 ? this.legendData.map(function(item) {
              return item[1]
            }) : [0]
          }
        })
        window.onresize = this.chart.resize
      })
    },
    changeTime() {
      const date = new Date()
      return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`
    }
  }
}
</script>
