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

<script>
import { mapState, createNamespacedHelpers } from 'vuex';
import { Rose } from '@antv/g2plot';
export default {
  name: 'rose',
  props: {
    data: { type: Array, default: () => [] },
    axis: { type: Object, default: () => {} }, //{x:x轴字段名; xAlias:x轴名称; y:y轴字段名; yAlias:y轴名称}
    gid: { type: String, default: `${new Date().getTime()}` },
    headTitle: { type: String, default: '' },
  },
  components: {},
  data: function() {
    return {
      chart: null,
      list: undefined,
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    async init() {
      let e = document.getElementById(this.gid);
      if (!e) {
        console.warn('没有找到指定渲染容器');
        return;
      }
      if (!this.list) {
        //未获得数据
        return;
      }
      if (this.chart) {
        this.chart.updateConfig({ data: this.list });
      } else {
        let { x, y, xAlias, yAlias } = this.axis;
        let meta = {};
        meta[x] = { alias: xAlias };
        meta[y] = { alias: yAlias };
        this.chart = new Rose(this.gid, {
          title: { visible: true, text: this.headTitle },
          pixelRatio: 4,
          data: this.list,
          radiusField: y,
          categoryField: x,
          colorField: x,
          // angleField: y,
          meta: meta,
          point: {
            visible: true,
          },
          label: {
            visible: true,
            type: 'spider',
            formatter: (text, item) => `${item[x]}: ${item[y]}`,
          },
          //stackField + legend 一起使用,前者确定以哪个字段作为选项,后者是显示与否,位置
          stackField: x,
          legend: {
            visible: true,
            position: 'right-top',
          },
          events: {
            // onPieClick: e => this.gclick(e),
          },
        });
      }

      this.chart.render();
    },
  },
  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>
