<template>
  <div :id="id" :style="style"></div>
</template>

<script>
import Factory from "./util/factory";
import echarts from "echarts";
import {isEmptyObject,isDef} from './util/util'
export default {
  name: "chart",
  data: () => {
    return {
      legend: [],
      isNodata: false,
      id:
        "echart" + Math.floor(Math.random() * 10000 + 1) + new Date().getTime()
    };
  },
  props: {
    // 父组件需要传递的参数：width，height，option
    type: {
      required: true,
      type: String
    },
    width: {
      type: String,
      default: "100%"
    },
    height: {
      type: String,
      default: "100%"
    },
    dataList: {
      required: true
    },
    icon: String
  },
  computed: {
    style() {
      return {
        height: this.height,
        width: this.width,
        marginBottom: "5px"
      };
    }
  },
  watch: {
    // 观察option的变化
    dataList: {
      handler(newVal) {
        if (newVal) {
          this.init();
        }
      },
      deep: true // 对象内部属性的监听，关键。
    }
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      if (!isDef(this.chart)) {
        this.chart = echarts.init(document.getElementById(this.id));
      }
      if (isEmptyObject(this.dataList) ||
        this.dataList.yList[0].data.length == 0
      ) {
        this.isNodata = true;
      } else {
        try {
          this.dataList.optionSet.downloadImageName = this.title;
          var f = new Factory(this.type, this.dataList);
          this.legend = f.option.legend.data;
        } catch (e) {
          this.legend = "";
        }
        this.isNodata = false;
        // 清除画布
        this.chart.clear();
        this.chart.setOption(f.option, true);      
        this.chart.resize();
        window.addEventListener("resize", () => {
          this.chart.resize();
        });
      }
      // this.chart.off('click')// 防止多次重复执行
      this.chart.on("click", params => {
        this.$emit("click", params.name);
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.nodata {
  vertical-align: middle;
  text-align: center;
}
</style>
