<script setup>
import { ref, computed, inject, watch } from "vue";
import Table from "@/components/customUI/Table.vue";
import LineChart from "@/components/chart/LineChart.vue";
import dayjs from "dayjs";
import { SECOND_CHART_COLOR } from "@/constant";

// 注入數據
const { tableData, loading } = inject("history_table_data");

const history_chart = ref(null);
const groupedData = ref({});

// 預設圖表選項
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 columns = [
  { title: "類別", key: "points" },
  { title: "最大值", key: "max" },
  { title: "最小值", key: "min" },
  { title: "平均值", key: "avg" },
];

// 格式化數據
const formatChartData = (data) => {
  return data.reduce((acc, { building_name, device_name, points, timestamp, value }) => {
    // 檢查並轉換 "無資料" 為 null
    const numericValue = value == "無資料" ? null : parseFloat(value);

    // 濾掉 "true" 或 "false"，但不濾掉 null
    if (value === "true" || value === "false") return acc;

    // 構建唯一的 series key (building_name + device_name + points)
    const seriesKey = `${building_name || ''} ${device_name || ''} ${points}`;

    if (!acc[seriesKey]) {
      acc[seriesKey] = { timestamps: [], values: [] };
    }

    acc[seriesKey].timestamps.push(dayjs(timestamp).format("YYYY-MM-DD HH:mm"));
    acc[seriesKey].values.push(numericValue);

    return acc;
  }, {});
};

// 排序時間
const sortByTimestamp = (data) => {
  return data.sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp));
};

// 監聽 tableData，更新圖表
watch(
  tableData,
  (newData) => {
    if (newData?.length > 0) {
      groupedData.value = formatChartData(newData);

      // 排序時間
      Object.keys(groupedData.value).forEach((seriesKey) => {
        const sortedData = sortByTimestamp(
          groupedData.value[seriesKey].timestamps.map((timestamp, index) => ({
            timestamp,
            value: groupedData.value[seriesKey].values[index],
          }))
        );
        groupedData.value[seriesKey].timestamps = sortedData.map(
          (item) => item.timestamp
        );
        groupedData.value[seriesKey].values = sortedData.map((item) => item.value);
      });

      // 構建 series
      const series = Object.keys(groupedData.value).map((seriesKey, index) => ({
        name: seriesKey, // 使用 building_name + device_name + points 作為名稱
        type: "line",
        data: groupedData.value[seriesKey].values,
        showSymbol: false,
        itemStyle: { color: SECOND_CHART_COLOR[index % SECOND_CHART_COLOR.length] },
      }));

      // 更新圖表
      history_chart.value?.chart.setOption({
        legend: { data: Object.keys(groupedData.value) },
        xAxis: {
          data: groupedData.value[Object.keys(groupedData.value)[0]].timestamps,
        },
        series,
      });
    }
  },
  { deep: true }
);

// 計算最大值、最小值、平均值
const calculateStats = (values) => {
  const validValues = values.filter((val) => val !== null);
  const max = validValues.length ? Math.max(...validValues) : "N/A";
  const min = validValues.length ? Math.min(...validValues) : "N/A";
  const avg = validValues.length
    ? (
        validValues.reduce((sum, val) => sum + val, 0) / validValues.length
      ).toFixed(2)
    : "N/A";
  return { max, min, avg };
};

// 自動更新表格數據
const tableStats = computed(() =>
  Object.keys(groupedData.value).map((seriesKey) => {
    const values = groupedData.value[seriesKey].values;
    const { max, min, avg } = calculateStats(values);
    return { points: seriesKey, max, min, avg };
  })
);

// 關閉 Modal
const onCancel = () => {
  history_modal.close();
  history_chart.value.chart.setOption({ ...defaultChartOption }, true);
  groupedData.value = {};
};
</script>

<template>
  <Modal id="history_modal" :onCancel="onCancel" width="1500">
    <template #modalTitle>
      <p>統計圖表</p>
      <button class="fixed right-10 top-5" @click.prevent="onCancel">
        <font-awesome-icon
          :icon="['fas', 'times']"
          size="1x"
          class="text-[#a5abb1]"
        />
      </button>
    </template>
    <template #modalContent>
      <LineChart
        v-if="tableData.length > 0"
        id="history_chart"
        class="min-h-[350px] max-h-fit"
        :option="defaultChartOption"
        ref="history_chart"
      />
      <Table
        :loading="loading"
        :columns="columns"
        :dataSource="tableStats"
        :withStyle="false"
      ></Table>
    </template>
  </Modal>
</template>

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