<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 []
      }
    },
    xAxisTitle: {
      type: Array,
      default: () => {
        return [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]
      }
    }
  },
  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'
          },
          tooltip: {
            trigger: 'axis'
          },
          legend: {
            type: 'scroll',
            orient: 'vertical',
            right: 10,
            top: 20,
            bottom: 20,
            data: this.legendData
          },
          xAxis: {
            type: 'category',
            boundaryGap: false,
            data: this.xAxisTitle
          },
          yAxis: {
            type: 'value'
          },
          series: this.seriesData
        })
        window.onresize = this.chart.resize
      })
    }
  }
}
</script>
