<template>
  <div class='wrapper' :id="id">
  </div>
</template>

<script>
import echarts from 'echarts'
export default {
  props: {
    id: {
      type: String,
      default: ''
    },
    list: {
      type: Array,
      default() {
        return []
      }
    }
  },
  data() {
    return {}
  },
  watch: {
    list: function(val) {
      this.drawChart()
    }
  },
  mounted() {
    this.drawChart()
  },
  methods: {
    drawChart() {
      // 基于准备好的dom，初始化echarts实例
      const chart = echarts.init(document.getElementById(this.id))
      // 监听屏幕变化自动缩放图表
      window.addEventListener('resize', function() {
        chart.resize()
      })
      const data = []
      const numList = []
      if (this.list.length > 0) {
        this.list.forEach(row => {
          data.push(row.type)
          numList.push(row.count)
        })
      }
      chart.setOption(
        {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: [{
            type: 'category',
            data: data,
            axisLine: {
              show: true,
              lineStyle: {
                color: '#efefef',
                width: 1,
                type: 'solid'
              }
            },
            axisTick: {
              show: false
            },
            axisLabel: {
              show: true,
              textStyle: {
                color: '#5b5d5d'
              }
            }
          }],
          yAxis: [{
            type: 'value',
            axisLabel: {
              formatter: '{value}'
            },
            axisTick: {
              show: false
            },
            axisLine: {
              show: false,
              lineStyle: {
                color: '#5b5d5d',
                width: 1,
                type: 'solid'
              }
            },
            splitLine: {
              lineStyle: {
                color: '#efefef'
              }
            }
          }],
          series: [{
            cursor: 'inherit',
            clickable: false,
            name: '数量',
            type: 'bar',
            data: numList,
            barWidth: 10, // 柱子宽度
            barGap: 1, // 柱子之间间距
            itemStyle: {
              normal: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                  offset: 0,
                  color: '#008cff'
                }, {
                  offset: 1,
                  color: '#005193'
                }]),
                opacity: 1
              }
            }
          }]
        }
      )
    }
  }
}
</script>

<style scoped>
  .wrapper {
    width: 100%;
    height: 100%;
  }
</style>
