<script setup>
import { ref, onMounted, inject, watch } from "vue";
const { elecMonth_data } = inject("energy_data");

const totalElecBills = ref(0);
const totalElecDegree = ref(0);
const IntervalElecBills = ref(0);
const IntervalElecDegree = ref(0);
const totalDate = ref(null);
const IntervalDate = ref(null);

const daysInMonth = (month) => {
  const [year, monthNumber] = month.split("-");
  return new Date(year, monthNumber, 0).getDate(); // 返回該月份的天數
};

watch(
  () => elecMonth_data.value,
  (newData) => {
    // 🔍 Log 1：整個資料
    console.log("📦 elecMonth_data 原始資料：", newData);
    const latestData = newData[newData.length - 1];
    // 🔍 Log 2：最新一筆資料
    console.log("🧾 latestData（用於 IntervalElecBills 的來源）:", latestData);

    // 🔍 Log 3：各段電費
    console.log("💰 各時段費用：", {
      costPeak: latestData.costPeak,
      costHalfPeak: latestData.costHalfPeak,
      costOffPeak: latestData.costOffPeak,
      costBase: latestData.costBase,
    });

    // 🔍 Log 4：總電費計算（原始值）
    const rawIntervalElec =
      latestData.costPeak +
      latestData.costHalfPeak +
      latestData.costOffPeak +
      latestData.costBase;
    console.log("💵 IntervalElecBills 原始總額（未格式化）:", rawIntervalElec);

    // 計算總電費與用電度數
    totalElecBills.value = newData
      .reduce((sum, item) => {
        const monthlyBill =
          item.costPeak + item.costHalfPeak + item.costOffPeak + item.costBase;
        return sum + monthlyBill;
      }, 0)
      .toFixed(2)
      .replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    totalElecDegree.value = newData
      .reduce((sum, item) => {
        const monthlyBill =
          item.degreePeak + item.degreeHalfPeak + item.degreeOffPeak;
        return sum + monthlyBill;
      }, 0)
      .toFixed(2)
      .replace(/\B(?=(\d{3})+(?!\d))/g, ",");

    // 計算區間電費與用電度數，取最新一筆數據

    IntervalElecBills.value = (
      latestData.costPeak +
      latestData.costHalfPeak +
      latestData.costOffPeak +
      latestData.costBase
    )
      .toFixed(2)
      .replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    IntervalElecDegree.value = (
      latestData.degreePeak +
      latestData.degreeHalfPeak +
      latestData.degreeOffPeak
    )
      .toFixed(2)
      .replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    const today = new Date();
    const todayStr = today.toISOString().split("T")[0];
    IntervalDate.value = latestData.time
      ? `${latestData.time}-01 ~ ${todayStr}`
      : "";

    // totalDate 還是顯示從 1 月 1 日起
    const startYear = newData[0]?.time?.split("-")[0] ?? "";
    totalDate.value = startYear ? `${startYear}-01-01 ~ ${todayStr}` : "";
  },
  { deep: true }
);
</script>

<template>
  <div
    class="stats w-full h-[48%] p-2 mb-4 bg-slate-900 rounded-lg border border-cyan-200/20 shadow-md shadow-cyan-500/20"
  >
    <!-- 電壓資訊 -->
    <div class="stat place-items-start">
      <div class="stat-title text-gray-200 3xl:text-[2rem]">
        {{ $t("energy.elec_bills") }}
      </div>
      <div class="stat-value text-success text-5xl 3xl:text-[6rem]">
        {{ totalElecBills }}
      </div>
      <div class="stat-desc text-gray-400 3xl:text-[2rem]">
        {{ totalDate }}
      </div>
    </div>
    <div class="stat place-items-start">
      <div class="stat-title text-gray-200 3xl:text-[2rem]">
        {{ $t("energy.interval_elec_charges") }}
      </div>
      <div class="stat-value text-success text-5xl 3xl:text-[6rem]">
        {{ IntervalElecBills }}
      </div>
      <div class="stat-desc text-gray-400 3xl:text-[2rem]">
        {{ IntervalDate }}
      </div>
    </div>
  </div>

  <div
    class="stats w-full h-[48%] p-2 mb-4 bg-slate-900 rounded-lg border border-cyan-200/20 shadow-md shadow-cyan-500/20"
  >
    <!-- 電流資訊 -->
    <div class="stat place-items-start">
      <div class="stat-title text-gray-200 3xl:text-[2rem]">
        {{ $t("energy.year_elec_consumption") }}
      </div>
      <div class="stat-value text-success text-5xl 3xl:text-[6rem]">
        {{ totalElecDegree }}
      </div>
      <div class="stat-desc text-gray-400 3xl:text-[2rem]">
        {{ totalDate }}
      </div>
    </div>
    <div class="stat place-items-start">
      <div class="stat-title text-gray-200 3xl:text-[2rem]">
        {{ $t("energy.interval_elec_consumption") }}
      </div>
      <div class="stat-value text-success text-5xl 3xl:text-[6rem]">
        {{ IntervalElecDegree }}
      </div>
      <div class="stat-desc text-gray-400 3xl:text-[2rem]">
        {{ IntervalDate }}
      </div>
    </div>
  </div>
</template>

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