<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.name);
          seriesData.push(item.value);
        });
      }
      this.chart.setOption({
        title: {
          text: this.title,
          left: "center",
        },
        color: ["rgba(37, 97, 239, 1)"],
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow", // 默认为直线，可选为：'line' | 'shadow'
          },
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: [
          {
            type: "category",
            data: xAxisData,
            axisTick: {
              alignWithLabel: true,
            },
          },
        ],
        yAxis: [
          {
            type: "value",
            data: xAxisData,
          },
        ],
        series: [
          {
            // showBackground: true,
            // backgroundStyle: {
            //   color: "rgba(180, 180, 180, 0.05)",
            // },
            name: this.itemName,
            type: "bar",
            barWidth: "60%",
            data: seriesData,
            animationDuration,
            itemStyle: {
              normal: {
                color: function () {
                  return (
                    "#" +
                    Math.floor(Math.random() * (256 * 256 * 256 - 1)).toString(
                      16
                    )
                  );
                },
              },
            },
          },
        ],
      });
    },
  },
};
</script>
