<script setup lang="ts">
import { ref, computed, watch, type Ref } from "vue";
import { useAppStoreHook } from "@/store/modules/app";
import {
  delay,
  useDark,
  useECharts,
  type EchartOptions,
  randomColor
} from "@pureadmin/utils";
import * as echarts from "echarts/core";
import { bar } from "@/api/welcome";

const { isDark } = useDark();

const theme: EchartOptions["theme"] = computed(() => {
  return isDark.value ? "dark" : "light";
});

const barChartRef = ref<HTMLDivElement | null>(null);
const { setOptions, resize } = useECharts(barChartRef as Ref<HTMLDivElement>, {
  theme
});

let barxList = [];
let nameList = [];
function getList() {
  bar()
    .then((data) => {
      if (data.status == '1') {
        data.data.forEach((item) => {
          const colort = randomColor({ type: "hex" }) as string;
          const colorb = randomColor({ type: "hex" }) as string;
          nameList.push(item.name)
          barxList = item.date
          item.type = "bar"
          item.barWidth = "15%";
          item.itemStyle = {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color: colort
              },
              {
                offset: 1,
                color: colorb
              }
            ])
          }
        });
        setOptions(
          {
            tooltip: {
              trigger: "axis",
              axisPointer: {
                type: "shadow"
              }
            },
            grid: {
              bottom: "20px",
              right: "10px"
            },
            legend: {
              //@ts-expect-error
              right: true,
              data: nameList
            },
            xAxis: [
              {
                type: "category",
                axisTick: {
                  alignWithLabel: true
                },
                axisLabel: {
                  interval: 0
                  // width: "70",
                  // overflow: "truncate"
                },
                data: barxList,
                triggerEvent: true
              }
            ],
            yAxis: [
              {
                type: "value",
                triggerEvent: true
              }
            ],
            series: data.data,
            addTooltip: true
          },
          {
            name: "click",
            callback: params => {
              console.log("click", params);
            }
          }
        );
      } else {
        console.log(data.message);
      };
    }).catch(err => {
      console.log(err);
    })
}

getList();
watch(
  () => useAppStoreHook().getSidebarStatus,
  () => {
    delay(600).then(() => resize());
  }
);
</script>

<template>
  <div ref="barChartRef" style="width: 100%; height: 35vh" />
</template>
