<script setup>
import Table from "@/components/customUI/Table.vue";
import HistoryDataCahrt from "./HistoryDataCahrt.vue";
import { ref, inject, computed, watch } from "vue";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
const { tableData, loading } = inject("history_table_data");
const processedTableData = ref([]);

const columns = computed(() => [
  {
    title: t("assetManagement.department"),
    key: "department_name",
  },
  {
    title: t("energy.floor"),
    key: "floor_name",
  },
  {
    title: t("history.device_name"),
    key: "device_name",
    width: "30%",
    filter: true,
    sort: true,
  },
  {
    title: t("assetManagement.point"),
    key: "item_name",
  },
  {
    title: t("history.value"),
    key: "value",
    sort: true,
    filter: true,
  },
  {
    title: t("history.date"),
    key: "timestamp",
    width: "20%",
    sort: true,
  },
]);

const columns2 = computed(() => [
  {
    title: t("assetManagement.department"),
    key: "department_name",
  },
  {
    title: t("energy.floor"),
    key: "floor_name",
  },
  {
    title: t("history.device_name"),
    key: "device_name",
    filter: true,
  },
  {
    title: t("assetManagement.point"),
    key: "item_name",
  },
  {
    title: t("energy.maximum"),
    key: "maxValue",
  },
  {
    title: t("energy.maximum_time"),
    key: "maxTime",
  },
  {
    title: t("energy.minimum"),
    key: "minValue",
  },
  {
    title: t("energy.minimum_time"),
    key: "minTime",
  },
  {
    title: t("energy.average_value"),
    key: "averageValue",
  },
]);

// 處理計算邏輯的函數
const processData = (data) => {
  if (!data || !Array.isArray(data) || data.length === 0) {
    return [];
  }
  // 攤平成每個 data 的每一筆都成為一行
  return data.flatMap((item) =>
    (item.data || []).map((d) => ({
      ...item,
      value: d.value,
      timestamp: d.time,
    }))
  );
};

watch(
  tableData,
  (newTableData) => {
    processedTableData.value = processData(newTableData);
  },
  { immediate: true } // 立即執行一次
);
</script>

<template>
  <Table :columns="columns2" :dataSource="tableData" :loading="loading"
    ><template #beforeTable> <HistoryDataCahrt class="mb-10" /></template
  ></Table>
  <Table :columns="columns" :dataSource="processedTableData" :loading="loading">
  </Table>
</template>

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