<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: "100%"
      },
      height: {
        type: String,
        default: "400px"
      },
      data: {
        type: Object,
        default: {}
      },
    },
    data() {
      return {
        chart: null
      };
    },
    mounted() {
        this.$nextTick(() => {
            this.initChart();
        })
    },
    beforeDestroy() {
      if (!this.chart) {
        return;
      }
      this.chart.dispose();
      this.chart = null;
    },
    methods: {
      initChart() {
        let that = this;
        this.chart = echarts.init(document.getElementById(this.id));
        let seriesData = [], legendData = [];
        that.data.seriesData.forEach(function(item,index){
          let series = {
            name: '',
            type: 'bar',
            barWidth: '40%',
            data:[]
          }
          item.stack ? series.stack = item.stack : '';
          item.data ? series.data = [].concat(item.data) : '';
          if(item.name){
             series.name = item.name;
             legendData.push(item.name);
          }
          seriesData.push(series)
        })
        let option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: { // 坐标轴指示器，坐标轴触发有效
              type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
            }
          },
          color:that.data.color,
          legend: {
            left: "center",
            top: 10,
            data: legendData
          },
          grid: {
            top: '25%',
            left: '2%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: [{
            type: 'category',
            data: that.data.xAxisData,
            axisTick: {
              show:false
            },
            axisLine: {
              show: false
            },
          }],
          yAxis: [{
            type: 'value',
            name: that.data.yAxisName,
            axisTick: {
              show: false
            },
            axisLine: {
              show: false
            },
            splitLine: {
              lineStyle:{
                color:'#EFEFEF',
              },
            },
          }],
          series: seriesData,
        };
        this.chart.setOption(option);
      }
    }
  };
</script>
