<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";

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: "chart",
    },
    width: {
      type: String,
      default: "100%",
    },
    height: {
      type: String,
      default: "350px",
    },
    autoResize: {
      type: Boolean,
      default: true,
    },
    chartData: {
      type: Object,
      required: true,
    },
  },
  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() {
      this.chart = echarts.init(this.$el, "macarons");
      this.setOptions(this.chartData);
    },
    setOptions({
      expertData,
      patentData,
      achievementsData,
      demandData,
      dockingData,
    } = {}) {
      this.chart.setOption({
        legend: {},
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
          },
          padding: [5, 10],
        },
        dataset: {
          source: [
            ["product", "模拟数量", "真实数量"],
            ["专家数量", ...expertData],
            ["专利数量", ...patentData],
            ["科技成果数量", ...achievementsData],
            ["需求数量", ...demandData],
            ["对接数量", ...dockingData],
          ],
        },
        xAxis: {
          type: "category",
          axisTick: {
            show: false,
          },
        },
        yAxis: {
          axisTick: {
            show: false,
          },
          splitLine: {
            show: true,
          },
        },
        series: [
          {
            type: "bar",
            barMaxWidth: "60",
            itemStyle: {
              normal: {
                color: "#49a9ee",
                lineStyle: {
                  color: "#49a9ee",
                  width: 2,
                },
              },
            },
          },
          {
            type: "bar",
            barMaxWidth: "60",
            itemStyle: {
              normal: {
                color: "#98d87d",
                lineStyle: {
                  color: "#98d87d",
                  width: 2,
                },
              },
            },
          },
        ],
      });
    },
  },
};
</script>
