<template>
  <div :class="className" :style="{height:height,width:width}" />

</template>

<script>
  import echarts from 'echarts'
  require('echarts/theme/macarons') // echarts theme
  import resize from './mixins/resize'

  const animationDuration = 6000

  export default {
    mixins: [resize],
    props: {
      className: {
        type: String,
        default: 'chart'
      },
      width: {
        type: String,
        default: '100%'
      },
      height: {
        type: String,
        default: '350px'
      },
      chartData: {
        type: Object
      }
    },
    data() {
      return {
        chart: null
      }
    },
    mounted() {
      this.$nextTick(() => {
        this.initChart()
      })
    },
    watch: {
      chartData: {
        deep: true,
        handler(val) {
          this.setOptions(val)
        }
      }
    },
    beforeDestroy() {
      if (!this.chart) {
        return
      }
      this.chart.dispose()
      this.chart = null
    },
    methods: {
      initChart() {
        this.chart = echarts.init(this.$el, 'macarons');
        this.setOptions(this.chartData);
      },
      setOptions(chartdata) {
        console.log(chartdata.xArr)
        this.chart.setOption({
          legend: {},
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: [{
            type: 'value',
            boundaryGap: [0, 0.01]
          }],
          yAxis: [{
            type: 'category',
            data: chartdata.yArr,
          }],
          series: [{
            name: '借阅次数',
            type: 'bar',
            stack: 'vistors',
            barWidth: '10%',
            data: chartdata.xArr,
            animationDuration
          }]
        })

      }
    }
  }
</script>
