<template>
  <div class="grid-chart" :id="id">

  </div>
</template>

<script>

import {copyObj, uuid} from '@/utils';
import * as echarts from 'echarts';

const basicSerie = {
  type: 'bar',
  label: {
    show: true,
  },
  stack: '总量',
  data: [],
};
const opts = {
  toolbox: {
    itemGap: 10,
    itemSize: 16,
    right: 10,
    top: 0,
    show: true,
    feature: {
      magicType: {
        show: true,
        type: ['bar', 'line']
      },
      saveAsImage: {
        show: true
      }
    }
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow',
    },
  },
  legend: {
    data: [],
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true,
  },
  xAxis: {
    type: 'category',
    boundaryGap: true,
    data: [],
    axisTick: {
      alignWithLabel: true,
    },
  },
  yAxis: {
    type: 'value',
    minInterval: 1,
  },
  series: [],
};
export default {
  props: {
    optCfg: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  watch: {
    optCfg: {
      handler(val) {
        this.initChart();
      },
      deep: true,
    },
  },
  data() {
    return {
      id: uuid(),
      refCharts: null,
    };
  },
  mounted() {
    this.$nextTick(this.initChart);
  },
  created() {
  },
  methods: {
    initChart() {
      this.refCharts && this.refCharts.clear();
      const chartDom = document.getElementById(this.id);
      this.refCharts = echarts.init(chartDom);
      const {series, ...rest} = this.optCfg
      const option = Object.assign({}, copyObj(opts), rest);
      const legend = [];
      series.forEach((item, index) => {
        const serie = copyObj(basicSerie);
        Object.assign(serie, item);
        option.series.push(serie);
        legend.push(item.name);
      });
      option.legend.data = legend;
      option.xAxis = this.optCfg.xAxis;
      option && this.refCharts && this.refCharts.setOption(option);
      this.refCharts.resize();
    },
  },
};
</script>
<style src="./index.scss" lang="scss"/>
