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

@Component
export default class LineChart extends Vue {
  name='lineChart';
  @Prop()
  propConfig:any
  id = '';
  chart:any = null;
  created(){
    this.id = this.randomString();
  }
  mounted(){
    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,
        height: h,
        autoFit: true,
        width:w,
        padding:config.padding?config.padding:[20, 0, 20, 30]
      });
    }
    if(config.tooltip == false){
      this.chart.tooltip(false);
    }else if(config.tooltip){
      this.chart.tooltip(config.tooltip);
    }
    this.chart.legend(config.legend);
    if(config.axis){
      for(const item of config.axis){
        this.chart.axis(item.field,item.config)
      }
    }
    this.chart.data(config.data);
    if(config.scale){
      if(config.scale.field){
        this.chart.scale(this.chart.scale.field,config.scale.config)
      }else{
        this.chart.scale(config.scale)
      }
    }

    let initchart=this.chart.line();
    if(config.position){
      
      initchart.position(config.position)
      if(!config.pointClose){
        this.chart.point().position(config.position);
      }
    }
    if(config.size){
      initchart.size(config.size)
    }
    if(config.shape){
      initchart.shape(config.shape)
    }
    if(config.style){
      initchart.style(config.style)
    }
    if(config.label){
      initchart.label(config.label.field,config.label.config)
    }
    if(config.color){
      initchart.color(config.color)
    }
    if (config.color) {
      if(config.color.lists){
        initchart.color(config.color.field, config.color.lists)
      }else if(config.color.formatter){
        initchart.color(config.color.field, config.color.formatter)
      }else{
        initchart.color(config.color)
      }
      
    }
    this.chart.render();
  }

  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>