<script setup>
import { inject, computed, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import LineChart from "@/components/chart/LineChart.vue";
import { SECOND_CHART_COLOR } from "@/constant";
import useSearchParam from "@/hooks/useSearchParam";
import dayjs from "dayjs";

const { searchParams } = useSearchParam();
const { t } = useI18n();

// 從上層 inject 接收歷史圖表資料
const { tableData } = inject("history_table_data");
const history_chart = ref(null); // 用來存取圖表元件實例

// 預設圖表設定物件
const defaultChartOption = {
  tooltip: {
    trigger: "axis", // 滑鼠移動到 X 軸會觸發 tooltip
  },
  legend: {
    data: [],
    textStyle: {
      color: "#ffffff",
      fontSize: 16,
    },
  },
  grid: {
    top: "25%",
    left: "0%",
    right: "0%",
    bottom: "0%",
    containLabel: true, // 保留 label 顯示空間
  },
  toolbox: {
    show: true,
    feature: {
      saveAsImage: {
        type: "png",
        name: "Energy_management_chart",
        backgroundColor: "rgba(29, 36, 44, 1)",
        iconStyle: {
          borderColor: "rgba(53,237,237, 1)",
        },
      },
    },
  },
  xAxis: {
    type: "category",
    splitLine: { show: false },
    axisTick: { alignWithLabel: true }, 
    axisLabel: {
      color: "#ffffff",
      formatter: (value) =>
        searchParams.value.Type == 2
          ? dayjs(value).format("HH:mm")
          : dayjs(value).format("MM-DD"),
    },
    data: [],
  },

  yAxis: {
    type: "value",
    splitLine: { show: false },
    axisLabel: { color: "#ffffff" },
    // Y 軸最小值 -1，並無條件捨去小數，最大值 +1，無條件進位
    min: (value) => Math.floor(value.min - 1),
    max: (value) => Math.ceil(value.max + 1),
  },
  series: [],
};

// 格式化資料為圖表所需格式
const formatChartData = (data) => {
  return data.reduce((acc, item) => {
    const seriesKey = `${item.device_name || ""}_${item.item_name || ""}`;
    acc[seriesKey] = {
      // 時間戳記與對應的數值陣列
      timestamps: item.data.map((d) =>
        dayjs(d.time).format("YYYY-MM-DD HH:mm")
      ),
      values: item.data.map((d) =>
        d.value == "無資料" ? null : parseFloat(d.value)
      ),
      maxValue: parseFloat(item.maxValue),
      minValue: parseFloat(item.minValue),
      averageValue: parseFloat(item.averageValue),
    };
    return acc;
  }, {});
};

// 當 tableData 變動時更新圖表
watch(
  tableData,
  (newData) => {
    if (newData?.length > 0) {
      const formattedData = formatChartData(newData);

      // 取得原始 X 軸時間資料並做抽樣
      const xDataRaw = formattedData[Object.keys(formattedData)[0]].timestamps;
      const totalPoints = xDataRaw.length;
      const tickCount = 30; // 目標最多顯示 30 個刻度
      const interval = Math.max(1, Math.floor(totalPoints / (tickCount - 1)));
      const sampledTime = xDataRaw.filter((_, idx) => idx % interval === 0);

      // 確保最後一筆時間有包含
      if (sampledTime[sampledTime.length - 1] !== xDataRaw[totalPoints - 1]) {
        sampledTime.push(xDataRaw[totalPoints - 1]);
      }

      // 組裝每一筆 series 資料（每條折線）
      const series = Object.keys(formattedData).map((seriesKey, index) => {
        const { timestamps, values, maxValue, minValue, averageValue } =
          formattedData[seriesKey];

        const timeToValue = Object.fromEntries(
          timestamps.map((t, i) => [t, values[i]])
        );

        return {
          name: seriesKey,
          type: "line",
          data: sampledTime.map((t) => timeToValue[t] ?? null),
          showSymbol: false, // 不顯示每個資料點的圓點
          itemStyle: {
            color: SECOND_CHART_COLOR[index % SECOND_CHART_COLOR.length],
          },
          markPoint: {
            // 最大值與最小值標記
            data: [
              maxValue !== null
                ? { type: "max", name: "Max", value: maxValue }
                : null,
              minValue !== null
                ? { type: "min", name: "Min", value: minValue }
                : null,
            ].filter(Boolean),
          },
          markLine: {
            // 平均值虛線
            data:
              averageValue !== null
                ? [
                    {
                      yAxis: averageValue,
                      name: "Avg",
                    },
                  ]
                : [],
          },
        };
      });

      // 更新圖表內容
      history_chart.value?.chart.setOption(
        {
          ...defaultChartOption,
          legend: {
            ...defaultChartOption.legend,
            data: Object.keys(formattedData), // 圖例顯示每一組設備名稱
          },
          xAxis: {
            ...defaultChartOption.xAxis,
            data: sampledTime, // 更新 X 軸資料
          },
          series, // 更新 Y 軸系列資料
        },
        true
      );
    }
  },
  { deep: true } // 深層監聽資料變動
);
</script>

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

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