<template>
  <div>
    <div class="cmp-title">各区域统计</div>
    <div ref="chart" :class="className" :style="{height:height,width:width}" />
  </div>
</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: '400px'
    },
    chartData: {
      type: Array,
      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.$refs['chart'], 'macarons')
    },
    setOptions(data = []) {
      this.chart.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: { // 坐标轴指示器，坐标轴触发有效
            type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        grid: {
          top: 40,
          left: '2%',
          right: 45,
          bottom: '3%',
          containLabel: true
        },
        yAxis: [{
          name: '市',
          type: 'category',
          data: data.map(item => `${item.province_name}${item.city_name || ''}`),
          axisTick: {
            alignWithLabel: true
          }
        }],
        xAxis: [{
          name: '数量',
          type: 'value',
          axisTick: {
            show: false
          }
        }],
        series: [{
          type: 'bar',
          // stack: 'vistors',
          // barWidth: '60%',
          data: data.map(item => item.nums),
          animationDuration
        }]
      })
    }
  }
}
</script>

<style scoped>
.cmp-title{
  box-sizing: border-box;
  padding: 15px;
  font-size: 16px;
}
</style>
