<template>
  <div :class="[b(),className]"
       element-loading-spinner="el-icon-loading"
       element-loading-background="rgba(255,255,255,0)"
       v-loading="loading"
       :style="styleSizeName">
    <div :ref="id"
         :style="styleChartName"></div>
  </div>
</template>

<script>
import create from "../../create";
import { getFunction } from '@/utils/utils';
import { getObj } from '@/api/components'
export default create({
  name: "common",
  data () {
    return {
      loading: false,
      timeout: null
    }
  },
  computed: {
    ids () {
      return this.option.id
    },
    src () {
      return this.option.src;
    },
    remote () {
      return this.option.remote;
    }
  },
  watch: {
    ids () {
      this.debounce(this.updateChart)()
    },
    src () {
      this.debounce(this.updateChart)()
    },
    remote () {
      this.debounce(this.updateChart)()
    }
  },
  methods: {
    debounce (func, wait = 600) {
      let that = this;
      return function () {
        const context = this;
        const args = arguments;
        clearTimeout(that.timeout);
        that.timeout = setTimeout(function () {
          func.apply(context, args);
        }, wait);
      };
    },
    getTemplate () {
      return new Promise((resolve, reject) => {
        if (this.remote && (this.src || this.ids)) {
          this.loading = true
          let axiosObj = this.ids ? getObj(this.ids) : this.$axios.get(this.src)
          axiosObj.then(res => {
            resolve(this.ids ? res.data.data.content : res.data)
          }).catch(() => {
            resolve()
          })
        } else {
          resolve(this.echartFormatter)
        }
      })
    },
    updateChart () {
      const optionData = this.deepClone(this.dataChart) || [];
      let option
      const callback = (res) => {
        this.loading = false;
        this.myChart.resize();
        this.myChart.setOption(option, this.initialize);
        this.bindEvent()
      }
      this.getTemplate().then(res => {
        if (this.remote) {
          let result = getFunction(res)
          option = result && result(optionData, this.dataParams);
        } else {
          option = this.echartFormatter && this.echartFormatter(optionData, this.dataParams) || {};
        }
        this.$emit('remote-change', {
          id: this.component,
          content: option
        })
        callback()
      }).finally(() => {
        this.loading = false;
      });

    }
  }
});
</script>



