<template>
  <div id="bar-chart" ref="barChart" class="chart" :style="{ height: props.height }"></div>
</template>

<script setup lang="ts">
  import * as echarts from 'echarts/core';
  import {
    TooltipComponent,
    TooltipComponentOption,
    GridComponent,
    GridComponentOption,
  } from 'echarts/components';
  import { BarChart, BarSeriesOption } from 'echarts/charts';
  import { CanvasRenderer } from 'echarts/renderers';
  import { onMounted, watch } from 'vue';

  echarts.use([TooltipComponent, GridComponent, BarChart, CanvasRenderer]);
  type EChartsOption = echarts.ComposeOption<
    TooltipComponentOption | GridComponentOption | BarSeriesOption
  >;

  const props = withDefaults(
    defineProps<{
      chartData: number[];
      chartLable: string[];
      height?: string;
    }>(),
    {
      height: '372px',
    },
  );

  onMounted(() => {
    const bar: echarts.ECharts = echarts.init(document.getElementById('bar-chart')!);

    initBarChart(bar);

    watch(
      () => props.chartData,
      () => {
        drawBarChart(bar);
      },
    );
  });

  const initBarChart = (bar: echarts.ECharts) => {
    const barOption: EChartsOption = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow',
        },
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true,
      },
      xAxis: [
        {
          type: 'category',
          data: props.chartLable,
          axisTick: {
            alignWithLabel: true,
          },
        },
      ],
      yAxis: [
        {
          name: '访问次数',
          type: 'value',
        },
      ],
      series: [
        {
          // name: props.chartCategory,
          type: 'bar',
          barWidth: '60%',
          data: props.chartData,
        },
      ],
    };
    bar.setOption(barOption);
  };

  const drawBarChart = (bar: echarts.ECharts) => {
    const barOption: EChartsOption = {
      xAxis: [
        {
          data: props.chartLable,
        },
      ],
      series: [
        {
          data: props.chartData,
        },
      ],
    };
    bar.setOption(barOption);
  };
</script>

<style scoped lang="scss">
  #bar-chart {
    width: 968px;
  }
</style>
