<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();
const { tableData } = inject("energy_table_data");
const history_chart = ref(null);

// 預設圖表選項
const defaultChartOption = {
  tooltip: {
    trigger: "axis",
  },
  legend: {
    data: [],
    textStyle: {
      color: "#ffffff",
      fontSize: 16,
    },
  },
  grid: {
    top: "25%",
    left: "0%",
    right: "0%",
    bottom: "0%",
    containLabel: true,
  },
  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 },
    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" },
    // interval: 100, //Y 軸的刻度間隔
    min: "dataMin",
    max: "dataMax",
    // splitArea: { show: false },
  },
  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);

      const series = Object.keys(formattedData).map((seriesKey, index) => {
        const { maxValue, minValue, averageValue } = formattedData[seriesKey];
        return {
          name: seriesKey,
          type: "line",
          data: formattedData[seriesKey].values,
          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:
              Object.keys(formattedData).length > 0
                ? formattedData[Object.keys(formattedData)[0]].timestamps
                : [],
          },
          series,
        },
        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>
