<template>
  <div :class="className" :style="{ height: height, width: width }" />
</template>

<script>
import echarts from "echarts";
require("echarts/theme/macarons"); // echarts theme
import resize from "./mixins/resize";

const animationDuration = 6000;

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: "chart",
    },
    width: {
      type: String,
      default: "100%",
    },
    chartData: {
      type: Array,
      required: true,
    },
    height: {
      type: String,
      default: "400px",
    },
    title: {
      type: String,
      default: "",
    },
    itemName: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      chart: null,
    };
  },
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        this.setOptions(val);
      },
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart();
    });
  },
  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    this.chart.dispose();
    this.chart = null;
  },
  methods: {
    initChart() {
      setTimeout(() => {
        this.chart = echarts.init(this.$el, "macarons");
        this.setOptions(this.chartData);
      }, 300);
    },
    setOptions(chartData) {
      let xAxisData = [];
      let seriesData = [];
      if (chartData) {
        chartData.forEach((item, index) => {
          xAxisData.push(item.cbName);
          seriesData.push(item.colValue);
        });
      }
      this.chart.setOption({
        tooltip: {
          trigger: "axis",
        },

        xAxis: {
          type: "category",
          data: xAxisData,
          boundaryGap: true,
        },
        yAxis: {
          type: "value",
        },
        series: [
          {
            data: seriesData,
            type: "line",
            areaStyle: {}
          },
        ],
      });
    },
  },
};
</script>
