<template>
  <div :id="id"></div>
</template>

<script>
import G2 from "@antv/g2";
import { setTimeout } from 'timers';

export default {
  data() {
    return {
      chart: null
    };
  },
  props: {
    charData: {
      type: Array,
      default() {
        return []
      }
    },
    id: String,
    width: {
      type: Number,
      default: null
    },
    total: {
      type: Number,
      default: null
    }
  },
  mounted() {
    setTimeout(() => {
      this.drawChart();
    }, 100);
  },
  beforeUpdate() {
    this.drawChart();
  },
  watch: {
    charData() {
      this.drawChart();
    }
  },
  methods: {
    drawChart() {
      let that = this;
      // 更新的时候要移除先destroy
      this.chart && this.chart.destroy();
      
      this.chart = new G2.Chart({
        container: this.id,
        width: this.width
      });
      this.chart.source(this.charData, {
        新增会员: {
          min: 1
        },
        会员率: {
          min: 0,
          formatter: function formatter(val) {
            return ((Number(val) / that.total) * 100).toFixed(2) + '%';
          }
        }
      });
      this.chart.legend({
        items: [{
          value: '会员率',
          marker: {
            symbol: 'square',
            fill: '#3182bd',
            radius: 5
          }
        }, {
          value: '新增会员',
          marker: {
            symbol: 'hyphen',
            stroke: '#fdae6b',
            radius: 5,
            lineWidth: 4
          }
        }],
        onClick: function onClick(ev) {
          var item = ev.item;
          var value = item.value;
          var checked = ev.checked;
          var geoms = chart.getAllGeoms();
          for (var i = 0; i < geoms.length; i++) {
            var geom = geoms[i];
            if (geom.getYScale().field === value) {
              if (checked) {
                geom.show();
              } else {
                geom.hide();
              }
            }
          }
        }
      });
      this.chart.axis('新增会员', {
        grid: null,
        label: {
          textStyle: {
            fill: '#fdae6b',
            width: 5
          }
        }
      });
      this.chart.interval().position('keyword*会员率').color('#3182bd').size(40);
      this.chart.line().position('keyword*新增会员').color('#fdae6b').size(3).shape('smooth');
      this.chart.point().position('keyword*新增会员').color('#fdae6b').size(3).shape('circle');
      this.chart.render();
    }
  }
};
</script>

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