<template>
  <section ref='chart' class='vue-echarts'></section>
</template>

<script lang="ts">
import echarts from 'echarts/lib/echarts';
import 'echarts/lib/component/title';
import 'echarts/lib/component/tooltip';
import EchartsChain from './EchartsChain';
import { Vue, Component, Prop, Watch } from 'vue-property-decorator';

/**
 * @author: wukangjun
 * @since: 2018-12-06
 * @router('/Example')
 */
@Component
export default class BaseEcharts extends Vue {
  public static NAME: string = 'BaseEcharts';
  // 图表的默认配置参数
  public defaultConfig: any = {};
  public echartsChain: any = null;
  public echartInstance: any = null;
  public emptyText: string = '暂无数据';
  public emptyElem: any = null;

  @Prop() public data!: any;
  @Prop({
    type: Function
  }) public setConfig!: (chain: any, data: any) => void;
  
  @Watch('data')
  public onDataChange(newVal: any) {
    const chain = this.echartsChain;
    this.setPlaceholder(false);
    if(this.setConfig) {
      this.setConfig(chain, newVal);
    }
    this.echartInstance.setOption(chain.toConfig());
  }

  public created() {
    this.echartsChain = new EchartsChain(this.defaultConfig, echarts);
  }

  public mounted() {
    this.echartInitial();
  }

  /**
   * 图表初始化准备
   */
  public echartInitial() {
    const echartElement = this.$refs.chart as any;
    this.echartInstance = echarts.init(echartElement);
    this.setPlaceholder();
  }

  /**
   * 设置占位空数据位置
   * @param {Boolean} visible: 是否存在占位符位置
   */
  public setPlaceholder(visible: boolean = true) {
    const echartElement = this.$refs.chart as any;
    if(!echartElement) {
      return;
    }

    if(visible) {
      this.emptyElem = document.createElement('div');
      this.emptyElem.className = 'vue-echarts-empty';
      this.emptyElem.innerText = this.emptyText;
      echartElement.appendChild(this.emptyElem);
    }else {
      if(this.emptyElem) {
        echartElement.removeChild(this.emptyElem);
        this.emptyElem = null;
      }
    }
  }
}

</script>

<style lang="scss">
.vue-echarts {
  position: relative;
  height: 100px;
}
.vue-echarts > .vue-echarts-empty {
  position: absolute;
  top: 50%;
  left: 50%;
  margin-top: -15px;
  margin-left: -50px;
  width: 100px;
  height: 30px;
  text-align: center;
  color: #ccc;
}
</style>