<template>
  <div :class="className"/>
</template>

<script>
import * as echarts from 'echarts'
import resize from './mixins/resize'

export default {
  mixins: [resize],
  props: {
    refName: {
      type: String,
      default: 'chart'
    },
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '365px'
    },
    smooth: {
      type: Boolean,
      default: true
    },
    autoResize: {
      type: Boolean,
      default: true
    },
    chartData: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      chart: null
    }
  },
  // watch: {
  //   chartData: {
  //     deep: true,
  //     handler(val) {
  //       // this.setOptions(val)
  //     }
  //   }
  // },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')
      this.renewOption(this.chartData)
    },
    renewOption(chart_data) {
      var series = []
      for (let i = 0; i < chart_data.legend.length; i++) {
        series[i] = {
          name: chart_data.legend[i], itemStyle: {
            normal: {
              color: chart_data.color[i],
              lineStyle: {
                color: chart_data.color[i],
                width: 2
              }
            }
          },
          smooth: this.smooth,
          type: 'line',
          data: chart_data.dataY[i],
          animationDuration: 2800,
          animationEasing: 'cubicInOut'
        }
      }
      this.setOptions(series)
    },
    setOptions(series) {
      this.chart.setOption({
        xAxis: {
          data: this.chartData.dataX,
          type: 'category',
          axisLabel: {
            // x轴文字的配置
            show: true,
            interval: 0// 使x轴文字显示全
          }
        },
        grid: {
          left: 10,
          right: 10,
          bottom: 20,
          top: 30,
          containLabel: true
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          },
          padding: [5, 10]
        },
        yAxis: {
          axisTick: {
            show: false
          }
        },
        legend: {
          data: this.chartData.legend
        },
        series: series
      })
    }
  }
}
</script>
