<template>
  <div :class="className" :style="{height:phone?'300px':height,width:width}" />
</template>

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

export default {
  mixins: [resize],
  props: {
    className: { type: String, default: 'chart' },
    width: { type: String, default: '100%' },
    height: { type: String, default: '540px' },
    title: { type: String, default: '' },
    phone: { type: Boolean, default: false },
    chartData: {
      type: Object,
      default: () => ({ city: [], data: [] })
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    chartData: {
      handler() {
        this.initChart()
      },
      deep: true
    }
  },
  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.chart.setOption({
        color: ['#4C9ECD', '#D970D0', '#5AC4B6'].sort((a, b) => 0.5 - Math.random()),
        title: {
          text: this.title,
          x: 'center',
          top: 18,
          textStyle: {
            color: '#000000',
            fontWeight: 'bold'
          }
        },
        grid: {
          left: 0,
          right: 0,
          bottom: 8,
          containLabel: true
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        toolbox: { show: false },
        calculable: true,
        xAxis: [
          {
            name: '城市',
            nameTextStyle: {
              fontSize: 12
            },
            type: 'category',
            axisTick: { show: false },
            data: this.chartData.city
          }],
        yAxis: [
          {
            type: 'value',
            name: '人'
          }
        ],
        series: [
          {
            name: '参赛人数',
            type: 'bar',
            barGap: 0,
            data: this.chartData.data
          }
        ]
      })
    }
  }
}
</script>
