<template>
  <div id="pie">
    <div :id="gid"></div>
    <download :gid="gid" :canvas="canvas"></download>
  </div>
</template>

<script>
import download from '@frame/parts/statistics/to-download';
import { Pie } from '@antv/g2plot';
import { mapState, createNamespacedHelpers } from 'vuex';
export default {
  name: 'pie',
  props: {
    data: { type: [Object, Array], default: () => [] },
    axis: { type: Object, default: () => {} },
    gid: { type: String, default: `${new Date().getTime()}` },
  },
  components: { download },
  data: function() {
    return {
      chart: null,
      list: [],
      canvas: undefined,
    };
  },
  created() {},
  mounted() {
    this.init();
  },
  methods: {
    async init() {
      let { x, y, xAlias, yAlias } = this.axis;
      let meta = {};
      meta[x] = { alias: xAlias };
      meta[y] = { alias: yAlias };
      this.chart = new Pie(this.gid, {
        pixelRatio: 4,
        data: this.list,
        colorField: x,
        angleField: y,
        // meta: meta,
        point: {
          visible: true,
        },
        label: {
          visible: true,
          type: 'spider',
          formatter: (text, item) => `${item._origin[x]}: ${item._origin[y]}`,
        },
        //stackField + legend 一起使用,前者确定以哪个字段作为选项,后者是显示与否,位置
        stackField: x,
        legend: {
          visible: true,
          position: 'right-top',
        },
        events: {
          onPieClick: e => this.gclick(e),
        },
      });
      this.chart.render();
      this.prepaid();
    },
    gclick(data) {
      console.log('in function:gclick');
      console.log(data);
    },
    prepaid() {
      let doc = document.getElementById(this.gid);
      let cav = doc.getElementsByTagName('canvas');
      if (cav.length <= 0) {
        console.warn('没有找到图表');
        return;
      }
      this.$set(this, `canvas`, cav[0]);
    },
  },
  computed: {
    ...mapState(['user']),
    pageTitle() {
      return `${this.$route.meta.title}`;
    },
  },
  watch: {
    data: {
      immediate: true,
      deep: true,
      handler(val) {
        if (val) this.$set(this, `list`, val);
      },
    },
  },
  metaInfo() {
    return { title: this.$route.meta.title };
  },
};
</script>

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