<script setup>
import LineChart from "@/components/chart/LineChart.vue";
import { ref, onMounted, watch, onUnmounted } from "vue";
import DashboardElectricityModal from "./DashboardElectricityModal.vue";
import { getDemand, getRealTimeDemand } from "@/apis/energy";
import { useI18n } from "vue-i18n";
import useBuildingStore from "@/stores/useBuildingStore";
import dayjs from "dayjs";

const store = useBuildingStore();
const { t } = useI18n();

const demandData = ref(null);
const realTimeDemand = ref([]);
const demand_chart = ref(null);
const intervalId = ref(null);
// 預設為空，避免 `null` 造成 `ECharts` 失敗
const defaultChartOption = ref({
  tooltip: { trigger: "axis" },
  legend: {
    data: [],
    textStyle: { color: "#ffffff", fontSize: 16 },
    top: "0%",
  },
  grid: {
    top: "20%",
    left: "0%",
    right: "0%",
    bottom: "0%",
    containLabel: true,
  },
  xAxis: {
    type: "category",
    splitLine: { show: false },
    axisLabel: { color: "#ffffff" },
    data: [], // 預設空值，避免 undefined
  },
  yAxis: {
    type: "value",
    splitLine: { show: false },
    axisLabel: { color: "#ffffff" },
  },
  series: [],
});

// 取得契約數據
const getData = async () => {
  if (store.selectedBuilding.building_guid) {
    const res = await getDemand(store.selectedBuilding.building_guid);
    demandData.value = res.data[0];
    updateChart();
  }
};

// 取得即時數據
const getRealTime = async () => {
  if (store.selectedBuilding.building_guid) {
    const res = await getRealTimeDemand(store.selectedBuilding.building_guid);
    realTimeDemand.value = Array.isArray(res.data) ? res.data.reverse() : [];
    updateChart();
  }
};

// 更新圖表資料
const updateChart = () => {
  if (!demandData.value || !realTimeDemand.value.length) return;

  defaultChartOption.value = {
    ...defaultChartOption.value,
    legend: {
      ...defaultChartOption.value.legend,
      data: [
        t("energy.real_time_Trend"),
        t("energy.contract_capacity"),
        t("energy.alert_capacity"),
        t("energy.reset_value"),
      ],
    },
    xAxis: {
      ...defaultChartOption.value.xAxis,
      data: realTimeDemand.value.map(({ time }) =>
        dayjs(time).format("HH:mm:ss")
      ),
    },
    series: [
      {
        name: t("energy.real_time_Trend"),
        type: "line",
        data: realTimeDemand.value.map((d) => d.value / 1000),
        smooth: true,
        lineStyle: { width: 3 },
        itemStyle: { color: "#17CEE3" },
      },
      {
        name: t("energy.contract_capacity"),
        type: "line",
        data: Array(realTimeDemand.value.length).fill(
          demandData.value.contract
        ),
        smooth: true,
        lineStyle: { width: 3 },
        itemStyle: { color: "#E4EA00" },
      },
      {
        name: t("energy.alert_capacity"),
        type: "line",
        data: Array(realTimeDemand.value.length).fill(demandData.value.alert),
        smooth: true,
        lineStyle: { width: 3 },
        itemStyle: { color: "#62E39A" },
      },
      {
        name: t("energy.reset_value"),
        type: "line",
        data: Array(realTimeDemand.value.length).fill(demandData.value.reset),
        smooth: true,
        lineStyle: { width: 3 },
        itemStyle: { color: "#E9971F" },
      },
    ],
  };

  // 確保 `chart` 有更新
  if (demand_chart.value?.chart) {
    // demand_chart.value.chart.clear();
    demand_chart.value.chart.setOption(defaultChartOption.value);
  }
};

// 監聽建築變更時重新抓取數據
watch(
  () => store.selectedBuilding,
  (newBuilding) => {
    if (newBuilding) {
      getData();
      getRealTime();
      // 每 30 秒重新取得即時數據
      if (intervalId.value) {
        clearInterval(intervalId.value);
      }
      // 設置新的定時器
      intervalId.value = setInterval(getRealTime, 30000);
    }
  },
  { immediate: true }
);

onUnmounted(() => {
  // 清除定時器
  clearInterval(intervalId.value); // 使用 intervalId.value
  intervalId.value = null; // 清空 intervalId
  console.log("Interval cleared!");
});
</script>

<template>
  <div class="mb-3 relative">
    <h3 class="text-info text-xl text-center">
      {{ $t("energy.immediate_demand") }}
      {{
        realTimeDemand.length > 0
          ? realTimeDemand[realTimeDemand.length - 1].value / 1000
          : "---"
      }}
      kw
    </h3>
    <DashboardElectricityModal :demandData="demandData" :getData="getData" />
  </div>
  <LineChart
    id="immediate_demand_chart"
    class="min-h-[300px] max-h-fit"
    :option="defaultChartOption"
    ref="demand_chart"
  />
</template>

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