<script setup>
import LineChart from "@/components/chart/LineChart.vue";
import { SECOND_CHART_COLOR } from "@/constant";
import { getDashboardEnergy } from "@/apis/dashboard";
import { twMerge } from "tailwind-merge";
import { ref, computed, onMounted, watch, onUnmounted } from "vue";
import dayjs from "dayjs";

const weeks = ["週日", "週一", "週二", "週三", "週四", "週五", "週六"];

const data = ref([]);
const getEnergyData = async () => {
  const res = await getDashboardEnergy();
  if (res.isSuccess) {
    data.value = res.data?.electric || [];
  } else {
    console.error("獲取用電量數據失敗:", res.message);
  }
};

let timer = null;

onMounted(() => {
  getEnergyData();
  timer = setInterval(() => {
    getEnergyData();
  }, 600000); // 每10分鐘
});

onUnmounted(() => {
  if (timer) {
    clearInterval(timer);
    timer = null;
  }
  if (electricity_chart.value && electricity_chart.value.chart) {
    electricity_chart.value.chart.dispose();
  }
});

const electricity_chart = ref(null);
const defaultChartOption = {
  tooltip: {
    trigger: "axis",
  },
  legend: {
    data: [],
    textStyle: {
      color: "#ffffff",
      fontSize: 14,
    },
    left: "center",
    bottom: "0%",
  },
  grid: {
    top: "10%",
    left: "0%",
    right: "0%",
    bottom: "10%",
    containLabel: true,
  },
  xAxis: {
    type: "category",
    splitLine: {
      show: false,
    },
    axisLabel: {
      color: "#ffffff",
    },
    data: weeks,
  },
  yAxis: {
    type: "value",
    splitLine: {
      show: false,
    },
    axisLabel: {
      color: "#ffffff",
    },
  },
  series: [],
};

watch(
  data,
  (newValue) => {
    electricity_chart.value.chart.setOption({
      legend: {
        data: newValue.map(({ full_name }) => full_name),
      },
      xAxis: {
        data: newValue[0].data.map(({ time }) => weeks[dayjs(time).get("day")]),
      },
      series: newValue.map(({ full_name }, index) => ({
        name: full_name,
        type: "line",
        data: newValue[index].data.map(({ value }) => value),
        showSymbol: false,
        itemStyle: {
          color: SECOND_CHART_COLOR[index],
        },
      })),
    });
  },
  {
    deep: true,
  }
);
</script>

<template>
  <div class="flex items-center justify-between mb-3">
    <h3 class="text-info font-bold text-xl text-center">用電量</h3>
  </div>
  <LineChart
    id="dashboard_electricity"
    class="min-h-[250px] max-h-fit"
    :option="defaultChartOption"
    ref="electricity_chart"
  />
</template>

<style lang="scss" scoped></style>
