<script setup>
import { inject, onMounted, onUnmounted, ref, nextTick, watch } from "vue";
import { getHistoryData } from "@/apis/history";
import LineChart from "@/components/chart/LineChart.vue";
import { SECOND_CHART_COLOR } from "@/constant";
import dayjs from "dayjs";
import { useI18n } from "vue-i18n";
const { t } = useI18n();

const { selectedDevice: data } = inject("system_selectedDevice");
const pointsList = ref([]);
const timeList = ref([
  { value: 1, name: t("dashboard.one_hour") },
  { value: 4, name: t("dashboard.four_hour") },
  { value: 8, name: t("dashboard.eight_hour") },
]);
const chartData = ref([]);
const forge_chart = ref(null);
const loading = ref(false);

// 預設圖表選項
const defaultChartOption = {
  tooltip: {
    trigger: "axis",
  },
  legend: {
    data: [],
    textStyle: {
      color: "#ffffff",
      fontSize: 16,
    },
  },
  grid: {
    top: "25%",
    left: "0%",
    right: "0%",
    bottom: "0%",
    containLabel: true,
  },
  xAxis: {
    type: "category",
    splitLine: { show: false },
    axisLabel: {
      color: "#ffffff",
      formatter: (value) => dayjs(value).format("HH:mm"), // 格式化為時間
    },
    data: [],
  },
  yAxis: {
    type: "value",
    splitLine: { show: false },
    axisLabel: { color: "#ffffff" },
  },
  series: [],
};

const formState = ref({
  Cumulant: 1,
  Type: 2,
  Points: [],
  Start_date: dayjs().format("YYYY-MM-DD"),
  Start_time: dayjs().format("HH:00"),
  End_date: dayjs().format("YYYY-MM-DD"),
  End_time: dayjs().format("HH:00"),
  Device_list: [],
});

const updateTimeRange = (hours) => {
  const now = dayjs();
  const startTime = now.subtract(hours, "hour");
  formState.value.Start_date = startTime.format("YYYY-MM-DD");
  formState.value.Start_time = startTime.format("HH:00");
  formState.value.End_date = now.format("YYYY-MM-DD");
  formState.value.End_time = now.format("HH:00");
};

const onSearch = async () => {
  loading.value = true;
  const res = await getHistoryData(formState.value);
  if (res.isSuccess) {
    if (res.data.items.length > 0) {
      chartData.value = res.data.items
        .map((d) => ({
          timestamp: d.timestamp,
          value: parseFloat(d.value),
        }))
        .sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp));

      // 更新圖表
      await nextTick();
      if (forge_chart.value?.chart) {
        forge_chart.value.chart.setOption({
          xAxis: {
            data: chartData.value.map((d) => d.timestamp),
          },
          series: [
            {
              name: data?.value?.value.full_name,
              type: "line",
              data: chartData.value.map((d) => d.value),
              showSymbol: false,
              itemStyle: {
                color: SECOND_CHART_COLOR[0], // 使用預設顏色
              },
            },
          ],
        });
      }
    } else {
      chartData.value = [];
      if (forge_chart.value?.chart) {
        forge_chart.value.chart.clear(); // 清空圖表
      }
    }
  } else {
    console.error("API Error:", res.msg);
  }
  loading.value = false;
};

onMounted(() => {
  console.log("Initial data:", data?.value?.value);
  if (data?.value?.value.device_number) {
    formState.value.Device_list = [data?.value?.value.device_number];
  }
  if (data?.value?.value.points) {
    pointsList.value = data?.value?.value?.points.map((item) => ({
      name: item.full_name,
      value: item.points,
    }));
  }
});

onUnmounted(() => {
  formState.value = {};
  chartData.value = [];
});

watch(
  () => formState.value.Points,
  (newPoints) => {
    if (newPoints.includes("Total")) {
      formState.value.Cumulant = 2;
    } else {
      formState.value.Cumulant = 1;
    }
  },
  { immediate: true }
);
</script>

<template>
  <div class="flex items-center gap-4">
    <Select
      :value="formState"
      class=""
      selectClass="border-info focus-within:border-info"
      name="Points"
      Attribute="name"
      :options="pointsList"
    ></Select>
    <Select
      :value="formState"
      class=""
      selectClass="border-info focus-within:border-info"
      name="time"
      Attribute="name"
      :options="timeList"
      :onChange="updateTimeRange"
    ></Select>
    <button class="btn btn-search" @click.stop.prevent="onSearch">
      <font-awesome-icon :icon="['fas', 'search']" />
      {{ $t("button.search") }}
    </button>
  </div>
  <div class="min-h-[300px] relative">
    <span
      v-if="loading"
      className="loading loading-spinner loading-lg text-info absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 z-20"
    ></span>
    <LineChart
      v-if="chartData.length > 0"
      id="forge_chart"
      class="min-h-[300px] max-h-fit"
      :option="defaultChartOption"
      ref="forge_chart"
    />
    <p class="text-center text-xl" v-if="!loading && chartData.length === 0">
      {{ $t("table.no_data") }}
    </p>
  </div>
</template>

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