<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: ''
    },
    seriesData: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data() {
    return {
      chart: null
    }
  },
  computed: {
    legendData() {
      const data = Object.assign([], this.seriesData)
      const out = []
      data.map(item => {
        out.push(item.name)
      })
      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,
            subtext: this.desc,
            left: 'left'
          },
          color: ['#003366', '#006699', '#4cabce', '#e5323e'],
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          legend: {
            data: this.legendData,
            type: 'scroll',
            orient: 'vertical',
            right: 0,
            top: 20,
            bottom: 20
          },
          xAxis: [
            {
              type: 'category',
              axisTick: { show: false },
              data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
            }
          ],
          yAxis: [
            {
              type: 'value'
            }
          ],
          series: this.seriesData
        })
        window.onresize = this.chart.resize
      })
    }
  }
}
</script>
