<!--
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2020-07-02 16:48:49
 * @LastEditors: 无尘
 * @LastEditTime: 2020-07-07 14:46:04
-->
<!--
  <active-chart :charData="charData" id="active-chart"></active-chart>
  import activeChart from '@/components/login-data/active-chart.vue';
-->
<template>
  <div :id="id"></div>
</template>

<script>
import * as G2 from '@antv/g2';

export default {
  data() {
    return {
      chart: null
    };
  },
  props: {
    charData: {
      type: Array,
      default() {
        return [];
      }
    },
    id: String,
    width: {
      type: Number,
      default: 800
    }
  },
  mounted() {
    setTimeout(() => {
      this.drawChart(); // 第一步是创建的时候更新图表，但是这个不适用于异步请求接口获取相关数据，采用下面的监听的方式
    }, 30);
  },
  beforeUpdate() {
    this.drawChart();
  },
  watch: {
    charData() {
      this.drawChart();
    }
  },
  methods: {
    drawChart() {
      // 更新的时候要移除先
      this.chart && this.chart.destroy();

      this.chart = new G2.Chart({
        container: this.id,
        width: this.width,
        autoFit: true,
        height: 420,
        padding: [50, 30, 60, 60]
      });
      this.chart.source(this.charData);
      this.chart.scale({
        value: {
          min: 0,
          nice: true
        },
        date: {}
      });
      this.chart.tooltip({
        // crosshairs: {
        //   type: 'line'
        // }
        showCrosshairs: true,
        shared: true
      });
      this.chart
        .line()
        .position('date*value')
        .color('active');
      this.chart
        .point()
        .position('date*value')
        .color('active');
      this.chart.legend({
        position: 'top-left', // 设置图例的显示位置
        offsetX: 40,
        itemGap: 20 // 图例项之间的间距
      });
      this.chart.render();
    }
  }
};
</script>

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