<template>
  <div class="box">
    <div :id="id"></div>
  </div>
</template>
<script lang="ts">
import { Component, Prop, Vue, Watch } from 'vue-property-decorator'
import { Chart,Util } from '@antv/g2'
// declare const G2: any

@Component
export default class PieChart extends Vue {
  name = 'pieChart'
  @Prop()
  propConfig: any
  id = ''
  chart:any=null;
  created() {
    this.id = this.randomString()
  }
  mounted() {
    this.$nextTick(() => {
      this.setConfig(this.propConfig)
    })
  }
  randomString() {
    const str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    let result = ''
    for (let i = 10; i > 0; --i) result += str[Math.floor(Math.random() * str.length)]
    return result
  }
  setConfig(config:any) {
    if(this.chart){
      this.chart.destroy();
      this.chart = null;
    }
    const w = (document.getElementById(this.id) as any).offsetWidth
    const h = (document.getElementById(this.id) as any).offsetHeight
    if(!this.chart){
      this.chart = new Chart({
        container: this.id,
        autoFit: true,
        padding:config.padding?config.padding:null,
        height: h,
        width: w
      })
    }
    this.chart.legend(config.legend)
    
    this.chart.data(config.data)
    if(config.guide){
      this.chart.guide().html(config.guide.html);
    }

    const interval = this.chart
      .interval()
      .adjust('stack')
      this.chart.interaction('element-single-selected');
    if (config.coord) {
      this.chart.coordinate('theta', config.coord.config)
    } 
    else {
      this.chart.coordinate('theta', {
        radius: 1
      })
    }

    if(config.tooltip == false){
      this.chart.tooltip(false);
    }else if(config.tooltip){
      this.chart.tooltip(config.tooltip);
    }

    if (config.position) {
      interval.position(config.position)
    }
    if (config.color) {
      if(config.color.lists){
        interval.color(config.color.field, config.color.lists)
      }else if(config.color.formatter){
        interval.color(config.color.field, config.color.formatter)
      }else{
        interval.color(config.color.field)
      }
    }
    if (config.label) {
      if(config.label.formatter){
        interval.label(config.label.field, config.label.formatter, config.label.config)
      }else{
        interval.label(config.label.field, config.label.config)
      }
    }
    if (config.style) {
      interval.style(config.style)
    }
    this.chart.render(true)
  }

  setData(data:Array<any>){
    if(this.chart){
      this.chart.changeData(data)
    }
  }
}
</script>

<style lang="scss" scoped>
.box {
  height: 100%;
  width: 100%;
  > div {
    height: 100%;
    width: 100%;
  }
}
</style>

<style lang="scss">

</style>
