<script setup>
import LineChart from "@/components/chart/LineChart.vue";
import { SECOND_CHART_COLOR } from "@/constant";
import dayjs from "dayjs";
import { ref, onMounted, watch, onUnmounted } from "vue";
import { getDashboardTemp } from "@/apis/dashboard";
import useSearchParams from "@/hooks/useSearchParam";

const { searchParams } = useSearchParams();
const intervalType = "frozen";

const defaultChartOption = ref({
  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: [],
  },
  yAxis: {
    type: "value",
    boundaryGap: [0, "100%"],
    splitLine: {
      show: false,
    },
    axisLabel: {
      color: "#ffffff",
    },
  },
  series: [],
});

const frozen_temp_chart = ref(null);


const data = ref([]);

const getData = async () => {
  const res = await getDashboardTemp({
    timeInterval: 1, // 時間間隔=>1.4.8
    tempOption: 2, // 1:即時溫度;2:冷藏溫度
  });
  if (res.isSuccess) {
    data.value = res.data || [];
  }
};

watch(data, (newValue) => {
  if (newValue?.length > 0) {
    frozen_temp_chart.value.chart.setOption({
      legend: {
        data: newValue.map(({ full_name }) => full_name),
      },
      xAxis: {
        data: newValue[0]?.data.map(({ time }) => dayjs(time).format("HH:mm")),
      },
      series: newValue.map(({ full_name, data: seriesData }, index) => ({
        name: full_name,
        type: "line",
        data: seriesData.map(({ value }) => value),
        showSymbol: false,
        itemStyle: {
          color: SECOND_CHART_COLOR[index],
        },
      })),
    });
  }
});

let timer = null;

onMounted(() => {
  getData();
  timer = setInterval(() => {
    getData();
  }, 60 * 1000);
});

onUnmounted(() => {
  if (timer) {
    clearInterval(timer);
    timer = null;
  }
});
</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_frozen_temp"
    class="min-h-[250px] max-h-fit"
    :option="defaultChartOption"
    ref="frozen_temp_chart"
  />
</template>

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