<template>
  <div id="e-bar">
    <div :id="gid" class="" style="height:450px;"></div>
  </div>
</template>

<script>
import { mapState, createNamespacedHelpers } from 'vuex';
import echarts from 'echarts/lib/echarts';
import 'echarts/lib/chart/bar';
import 'echarts/lib/component/title';
import 'echarts/lib/component/legend';
import 'echarts/lib/component/toolbox';
import 'echarts/lib/component/markPoint';
import 'echarts/lib/component/tooltip';
export default {
  name: 'e-bar',
  props: {
    data: { type: [Object, Array], default: () => [] },
    axis: { type: Object, default: () => {} },
    gid: { type: String, default: `${new Date().getTime()}` },
    horizontal: { type: Boolean, default: true },
  },
  components: {},
  data: function() {
    return {
      chart: null,
      list: undefined,
    };
  },
  created() {},
  mounted() {
    this.init();
  },
  methods: {
    async init() {
      let e = document.getElementById(this.gid);
      if (!e) {
        console.warn('没有找到指定渲染容器');
        return;
      }
      if (!this.list) {
        //未获得数据
        return;
      }
      let { x, y, xAlias, yAlias } = this.axis;
      let legend = this.list.map(i => i[x]);
      this.chart = echarts.init(document.getElementById(this.gid));
      let xAxis = {};
      let yAxis = {};
      let data = this.list.map(i => i[y]);
      if (this.horizontal) {
        xAxis = { data: legend };
        yAxis = { type: y };
      } else {
        yAxis = { data: legend };
        xAxis = { type: y };
      }
      const option = {
        title: {},
        tooltip: {
          trigger: 'item',
          formatter: '{a}<br/>{b} : {c} ',
          axisPointer: {
            type: 'shadow',
          },
        },
        legend: {
          data: [yAlias],
        },
        xAxis: xAxis,
        yAxis: yAxis,
        barMaxWidth: '30%',
        series: [
          {
            name: yAlias,
            type: 'bar',
            data: data,
            label: {
              show: true,
              position: 'top',
              textStyle: {
                color: '#939393',
              },
            },
          },
        ],
      };
      this.chart.setOption(option);
    },
  },
  watch: {
    data: {
      handler(val) {
        if (val.length > 0) this.$set(this, `list`, val);
      },
      immediate: true,
      deep: true,
    },
    list: {
      handler(val) {
        if (val) this.$nextTick(() => this.init());
      },
    },
  },
  computed: {
    ...mapState(['user']),
    pageTitle() {
      return `${this.$route.meta.title}`;
    },
  },
  metaInfo() {
    return { title: this.$route.meta.title };
  },
};
</script>

<style lang="less" scoped></style>
