<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: {
    item: {
      type: Object,
      default: null
    },
    option: {
      type: Object,
      default: () => { return {} }
    },
    className: {
      type: String,
      default: 'chart'
    },
    id: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '200px'
    },
    height: {
      type: String,
      default: '200px'
    },
    chartData: {
      type: Object,
      default: function() {
        return {
          xData: [],
          yData: []
        }
      }
    }
  },
  data() {
    return {
      chart: null,
      renderData: this.chartData
    }
  },
  watch: {
    chartData: {
      deep: true,
      handler(newVal, oldVal) {
        this.renderData = newVal
        this.initChart()
      }
    }
  },
  mounted() {
    this.chart = echarts.init(document.getElementById(this.id))
    this.initChart()
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      const option = {
        tooltip: {
          trigger: 'item'
        },
        grid: {
          top: '4%',
          left: '2%',
          right: '2%',
          bottom: '2%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: this.renderData.xData
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          type: 'line',
          smooth: 0.6,
          data: this.renderData.yData
        }, {
          type: 'bar',
          barMaxWidth: '45px',
          data: this.renderData.yData
        }]
      }
      Object.assign(option, this.option)
      if (this.renderData.xData) {
        this.option.xAxis.data = this.renderData.xData
      }
      if (this.item) {
        option.series.forEach(obj => Object.assign(obj, this.item))
      }
      this.chart.setOption(option)
    }
  }
}
</script>
