<script setup lang="ts">
import { useDark, useECharts } from "@pureadmin/utils";
import { type PropType, ref, computed, watch, nextTick } from "vue";

const props = defineProps({
  dates: {
    type: Array as PropType<Array<string>>,
    default: () => []
  },
  successData: {
    type: Array as PropType<Array<number>>,
    default: () => []
  },
  failData: {
    type: Array as PropType<Array<number>>,
    default: () => []
  }
});

const { isDark } = useDark();

const theme = computed(() => (isDark.value ? "dark" : "light"));

const chartRef = ref();
const { setOptions } = useECharts(chartRef, {
  theme
});

watch(
  () => props,
  async () => {
    await nextTick(); // 确保DOM更新完成后再执行
    setOptions({
      container: ".bar-card",
      color: ["#28a745", "#dc3545"], // 绿色成功，红色失败
      title: {
        text: "近14天内查询统计",
        left: "center", // 标题居中
        top: 10, // 标题放在顶部
        textStyle: {
          fontSize: 16,
          fontWeight: "bold",
          color: "#333"
        }
      },
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "line"
        }
      },
      grid: {
        top: "60px", // 预留空间给标题
        left: "50px",
        right: "20px",
        bottom: "50px"
      },
      legend: {
        data: ["成功查询", "失败查询"],
        textStyle: {
          color: "#606266",
          fontSize: "0.875rem"
        },
        top: 10, // 放置在右上角
        right: 20 // 靠右
      },
      xAxis: {
        type: "category",
        data: props.dates, // 横坐标，日期数据
        axisLabel: {
          fontSize: "0.875rem",
          rotate: 30 // 避免重叠
        },
        axisPointer: {
          type: "shadow"
        }
      },
      yAxis: {
        type: "value",
        axisLabel: {
          fontSize: "0.875rem"
        },
        splitLine: {
          show: true,
          lineStyle: {
            type: "dashed"
          }
        }
      },
      series: [
        {
          name: "成功查询",
          type: "line",
          smooth: true,
          itemStyle: {
            color: "#28a745" // 绿色
          },
          label: {
            show: true, // 在折线上显示数值
            position: "top",
            color: "#28a745"
          },
          data: props.successData
        },
        {
          name: "失败查询",
          type: "line",
          smooth: true,
          itemStyle: {
            color: "#dc3545" // 红色
          },
          label: {
            show: true, // 在折线上显示数值
            position: "top",
            color: "#dc3545"
          },
          data: props.failData
        }
      ]
    });
  },
  {
    deep: true,
    immediate: true
  }
);
</script>

<template>
  <div ref="chartRef" style="width: 100%; height: 560px" />
</template>
