<script setup>
import Table from "@/components/customUI/Table.vue";
import { inject, computed, ref } from "vue";
import { useRoute } from "vue-router";
import { useI18n } from "vue-i18n";
import dayjs from "dayjs";
const { t } = useI18n();
const { tableData, loading } = inject("energy_table_data");
const route = useRoute();
// 預設的欄位
const defaultColumns = ref([
  {
    title: t("assetManagement.department"),
    key: "department_name",
  },
  {
    title: t("energy.floor"),
    key: "floor_name",
  },
  {
    title: t("energy.electricity_classification"),
    key: "elecType",
  },
  {
    title: t("history.device_name"),
    key: "device_name",
    filter: true,
  },
]);

// 動態計算欄位
const columns = computed(() => {
  const dynamicColumns = [...defaultColumns.value];

  if (tableData.value && tableData.value.length > 0) {
    const firstDataItem = tableData.value[0];
    if (firstDataItem && firstDataItem.data) {
      firstDataItem.data.forEach((item, index) => {
        let formatString = "MM/DD"; // 預設格式
        switch (route.params.type) {
          case "3":
            formatString = "YYYY/MM";
            break;
          case "4":
            formatString = "YYYY";
            break;
          default:
            formatString = "MM/DD"; // case 1 和 case 2 都是 "MM-DD"
            break;
        }
        const formattedTime = dayjs(item.time).format(formatString);
        // 為每個 data 欄位創建一個唯一的 key，例如 "data_0", "data_1" 等
        dynamicColumns.push({
          title: formattedTime,
          key: `data_${index}`,
        });
      });
    }
  }

  dynamicColumns.push({
    title: t("energy.subtotal"),
    key: "subtotal",
  });

  return dynamicColumns;
});

// 動態調整 subtotal 值和新增 data 屬性
const dataSource = computed(() => {
  if (!tableData.value || tableData.value.length === 0) return [];

  return tableData.value.map((item) => {
    let subtotalValue = 0;
    const newData = {}; // 用於儲存 data 的值，方便 Table 組件讀取
    if (item.data && item.data.length > 0) {
      item.data.forEach((dataItem, index) => {
        const value = parseFloat(dataItem.value || 0);
        subtotalValue += value;
        // 將值儲存在 newData 中，key 與 columns 中的 key 對應
        newData[`data_${index}`] = dataItem.value;
      });
    }
    return {
      ...item,
      ...newData, // 將 data 的值合併到 item 中
      subtotal: subtotalValue.toFixed(2),
    };
  });
});
</script>

<template>
  <Table :columns="columns" :dataSource="dataSource" :loading="loading"></Table>
</template>

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