<template>
  <div ref="chart" class="user-type-bar-chart"></div>
</template>

<script>
export default {
  name: "UserTypeBarChart",
  props: {
    categories: {
      type: Array,
      default() {
        return ["白芨屯", "七树庄", "王浒圳", "新罕电", "小张各庄", "欢喜庄", "李朝庄"];
      },
    },
    residential: {
      type: Array,
      default() {
        return [26, 34, 18, 22, 24, 28, 10];
      },
    },
    industrial: {
      type: Array,
      default() {
        return [18, 24, 8, 18, 20, 26, 22];
      },
    },
  },
  data() {
    return {
      chart: null,
    };
  },
  mounted() {
    this.initChart();
    window.addEventListener("resize", this.handleResize);
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.handleResize);
    if (this.chart) {
      this.chart.dispose();
      this.chart = null;
    }
  },
  watch: {
    categories() {
      this.updateChart();
    },
    residential() {
      this.updateChart();
    },
    industrial() {
      this.updateChart();
    },
  },
  methods: {
    initChart() {
      if (!this.$refs.chart) {
        return;
      }
      this.chart = this.$echarts.init(this.$refs.chart);
      this.updateChart();
    },
    handleResize() {
      if (this.chart) {
        this.chart.resize();
      }
    },
    updateChart() {
      if (!this.chart) {
        return;
      }
      this.chart.setOption({
        grid: {
          left: 8,
          right: 8,
          top: 30,
          bottom: 0,
          containLabel: true,
        },
        legend: {
          top: 0,
          right: 10,
          itemWidth: 16,
          itemHeight: 8,
          textStyle: {
            color: "#ffffff",
            fontSize: 12,
          },
        },
        xAxis: {
          type: "category",
          data: this.categories,
          axisLine: { lineStyle: { color: "rgba(255,255,255,0.2)" } },
          axisTick: { show: false },
          axisLabel: {
            color: "#ffffff",
            fontSize: 11,
          },
        },
        yAxis: {
          type: "value",
          axisLine: { show: false },
          axisTick: { show: false },
          axisLabel: { show: false },
          splitLine: {
            lineStyle: { color: "rgba(255,255,255,0.2)" },
          },
        },
        series: [
          {
            name: "居民用户",
            type: "bar",
            data: this.residential,
            barWidth: 10,
            itemStyle: {
              borderRadius: [2, 2, 0, 0],
              color: "#2fd6ff",
            },
          },
          {
            name: "工商业用户",
            type: "bar",
            data: this.industrial,
            barWidth: 10,
            itemStyle: {
              borderRadius: [2, 2, 0, 0],
              color: "#42ff9d",
            },
          },
        ],
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.user-type-bar-chart {
  width: 100%;
  height: 200px;
}
</style>
