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

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

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

const { items, changeActiveBtn, setItems, selectedBtn } = useActiveBtn();

const data = ref([]);

onMounted(() => {
  setItems([
    {
      id: 1,
      title: "二重釜-溫度",
      key: 1,
      active: true,
    },
    {
      id: 2,
      title: "調理鍋-溫度",
      key: 2,
      active: false,
    },
    {
      id: 3,
      title: "調理鍋-糖度",
      key: 3,
      active: false,
    },
  ]);
});

const getData = async (timeInterval, typeOption) => {
  const res = await getDashboardTemp({
    timeInterval, // 時間間隔=>1.4.8
    tempOption: 1,
    typeOption, // 1:二重釜-溫度;2:調理鍋-溫度;3:二重釜-糖度
  });
  if (res.isSuccess) {
    data.value = res.data || [];
  }
};

const timeoutTimer = ref("");

watch(
  selectedBtn,
  (newValue) => {
    window.clearInterval(timeoutTimer.value);
    getData(parseInt(searchParams.value[intervalType] || 1), newValue.key);
    timeoutTimer.value = setInterval(() => {
      getData(parseInt(searchParams.value[intervalType] || 1), newValue.key);
    }, 60000);
  },
  {
    deep: true,
  }
);

watch(
  searchParams,
  (newValue, oldValue) => {
    if (
      newValue[intervalType] &&
      newValue[intervalType] !== oldValue[intervalType]
    ) {
      window.clearInterval(timeoutTimer.value);
      getData(parseInt(newValue[intervalType]), selectedBtn.value.key);
      timeoutTimer.value = setInterval(() => {
        getData(parseInt(newValue[intervalType]), selectedBtn.value.key);
      }, 60000);
    }
  },
  {
    deep: true,
  }
);

watch(data, (newValue) => {
  // clearChart(other_real_temp_chart.value.chart);
  if (newValue?.length > 0) {
    other_real_temp_chart.value.chart.setOption(
      {
        ...defaultChartOption.value,
        legend: {
          data: newValue.map(({ full_name }) => full_name),
          ...defaultChartOption.value.legend,
        },
        xAxis: {
          ...defaultChartOption.value.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],
          },
        })),
      },
      { notMerge: true }
    );
  }
  // other_real_temp_chart.value.chart.hideLoading();
});

onUnmounted(() => {
  if (timeoutTimer.value) {
    clearInterval(timeoutTimer.value);
    timeoutTimer.value = null;
  }
});
</script>

<template>
  <div class="flex items-center justify-between mb-3">
    <h3 class="text-info font-bold text-xl text-center">溫度-糖度</h3>
    <button
      class="btn-xs btn btn-info"
      @click="$emit('open-modal', intervalType)"
    >
      時間設定
    </button>
  </div>
  <div class="text-center">
    <ButtonConnectedGroup
      :items="items"
      :onclick="
        (e, item) => {
          changeActiveBtn(item);
        }
      "
      size="sm"
    />
  </div>

  <LineChart
    id="dashboard_other_real_temp"
    class="min-h-[250px] max-h-fit"
    :option="defaultChartOption"
    ref="other_real_temp_chart"
  />
</template>

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