<template>
  <div class="main">
    <div
      class="chart"
      ref="chart"
    >
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
export default {
  props: {
    dataList: {
      type: Array,
      default: []
    },
    title: {
      type: String,
      default: ''
    },
    areaList: {
      type: Array,
      default: []
    }
  },
  watch: {
    dataList: function(val) {
      if (val.length > 0) {
        this.init()
      }
    }
  },
  data() {
    return {
      chart: null
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      const myChart = this.chart || echarts.init(this.$refs.chart);
      const data = this.dataList.map(item => {
        return [item.name || item.areaName, item.value || item.count]
      })
      let option = {
        title: {
          text: this.title + '数',
          textStyle: {
            fontSize: 14,
            fontWeight: 400,
            color: '#444444'
          },
          top: 0,
          left: 30
        },
        grid: {
          left: '60',
          right: '30',
          bottom: '65',
          top: '48'
        },
        legend: {
          data: [this.title + '总数'],
          top: 0,
          right: 30
        },
        xAxis: [
          {
            type: 'category',
            nameLocation: 'center',
            axisLabel: {
              formatter: function(value) {
                if (value.length > 5) {
                  let i = 0
                  const strList = []
                  while (i < value.length) {
                    strList.push(value.slice(i, i + 5))
                    i += 5
                  }
                  return strList.join("\n");
                } else {
                  return value
                }

              }
            },
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: [{
          data: data,
          type: 'bar',
          name: this.title + '总数',
          label: {
            show: true,
            position: 'top'
          },
          itemStyle: {
            color: '#4495E6'
          },
          barWidth: 28
        }]
      };

      myChart.setOption(option);
      this.chart = myChart
    }
  }
}
</script>

<style lang="scss" scoped>
.main {
  height: 300px;
  width: 100%;
  .chart {
    width: 100%;
    height: 100%;
  }
}
</style>