<script setup>
import LineChart from "@/components/chart/LineChart.vue";
import { SECOND_CHART_COLOR } from "@/constant";
import dayjs from "dayjs";
import { ref, inject, onMounted, onUnmounted, watch } from "vue";
import { getDashboardTemp } from "@/apis/dashboard";
import useSearchParams from "@/hooks/useSearchParam";
import useBuildingStore from "@/stores/useBuildingStore";
import { useI18n } from "vue-i18n";
import { max, min } from "date-fns";

const { t } = useI18n();
const { searchParams } = useSearchParams();
const buildingStore = useBuildingStore();

const defaultChartOption = ref({
  tooltip: {
    trigger: "axis",
  },
  legend: {
    data: [],
    textStyle: {
      color: "#ffffff",
      fontSize: 16,
    },
  },
  grid: {
    top: "10%",
    left: "0%",
    right: "0%",
    bottom: "0%",
    containLabel: true,
  },
  xAxis: {
    // type: "time",
    type: "category",
    splitLine: {
      show: false,
    },
    axisLabel: {
      color: "#ffffff",
    },

    data: [],
  },
  yAxis: {
    type: "value",
    splitLine: {
      show: false,
    },
    axisLabel: {
      color: "#ffffff",
    },
    // 移除固定的 min/max，讓 ECharts 自動計算範圍
  },
  series: [],
});

const timeoutTimer = ref("");
const frozen_temp_chart = ref(null);
const data = ref([]);
const getData = async (timeInterval) => {
  const res = await getDashboardTemp({
    building_guid: buildingStore.selectedBuilding.building_guid,
    timeInterval, // 時間間隔=>1.4.8
    tempOption: 2, // 1：室溫 2:冷藏
  });
  if (res.isSuccess) {
    console.log("冷藏溫度資料:", res.data["冷藏溫度"]);

    data.value = res.data["冷藏溫度"];
  }
};

watch(
  data,
  (newValue) => {
    newValue.length > 0 &&
      frozen_temp_chart.value.chart.setOption({
        legend: {
          data: newValue.map(({ full_name }) => full_name),
        },
        xAxis: {
          data: newValue[0]?.data.map(({ time }) => time), // 使用 time
        },
        yAxis: {
          min:
            Math.floor(
              Math.min(
                ...newValue[0]?.data
                  .filter((data) => data.value !== null)
                  .map(({ value }) => value)
              )
            ),
          max:
            Math.ceil(
              Math.max(
                ...newValue[0]?.data
                  .filter((data) => data.value !== null)
                  .map(({ value }) => value)
              )
            ),
        },
        series: newValue.map(({ full_name, data }, index) => ({
          name: full_name,
          type: "line",
          data: data.map(({ value }) => value),
          showSymbol: false,
          itemStyle: {
            color: SECOND_CHART_COLOR[index],
          },
        })),
      });
  },
  { deep: true }
);

// 監聽建築物選擇變化
watch(
  () => buildingStore.selectedBuilding?.building_guid,
  (newBuildingGuid) => {
    if (newBuildingGuid) {
      getData(1);
      timeoutTimer.value = setInterval(() => {
        getData(1);
      }, 60 * 1000);
    } else {
      // 清除定時器
      if (timeoutTimer.value) {
        clearInterval(timeoutTimer.value);
      }
    }
  },
  {
    immediate: true,
  }
);

onUnmounted(() => {
  // 清除定時器
  if (timeoutTimer.value) {
    clearInterval(timeoutTimer.value);
  }
});
</script>

<template>
  <h3 class="text-info font-bold text-xl text-center mb-3 relative">
    <span>{{ $t("dashboard.refrig_chart") }}</span>
  </h3>

  <LineChart
    id="dashboard_frozen_temp"
    class="min-h-[300px] max-h-fit"
    :option="defaultChartOption"
    ref="frozen_temp_chart"
  />
</template>

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