<script setup>
import { ref, onMounted, onUnmounted, watch } from "vue";
import DashboardStat from "@/components/dashboard/dashboardStat.vue";
import DashboardBuild from "@/components/dashboard/dashboardBuild.vue";
import DashboardElecChart from "@/components/dashboard/dashboardElecChart.vue";
import DashboardTag from "@/components/dashboard/dashboardTag.vue";
import DashboardAlert from "@/components/dashboard/dashboardAlert.vue";
import useElecTotalMeterStore from "@/stores/useElecTotalMeterStore";
import useElecDemandStore from "@/stores/useElecDemandStore";
import dayjs from "dayjs";

const elecDataStore = useElecTotalMeterStore();
const elecDemandStore = useElecDemandStore();
const elecStat = ref([
  {
    value: 0,
    label: "今日用電量",
    unit: "kWH",
    icon: "leaf",
  },
  {
    value: 0,
    label: "昨日用電量",
    unit: "kWH",
    icon: "leaf",
  },
  {
    value: 0,
    label: "即時功率",
    unit: "kW",
    icon: "bolt",
  },
  {
    value: 0,
    label: "契約容量佔比",
    unit: "%",
    icon: "charging-station",
  },
]);
const elecDemand_P = ref(0); // 即時趨勢
const elecDemand_Engel = ref(0); // 契約容量
const yesterdayTodayData = ref({
  categories: [],
  values: [
    {
      name: `${dayjs().format("YYYY-MM-DD")} 用電量`,
      value: [],
    },
    {
      name: `${dayjs().subtract(1, "day").format("YYYY-MM-DD")} 用電量`,
      value: [],
    },
  ],
});

const weekComparisonData = ref({
  categories: [],
  values: [
    {
      name: "本週用電量",
      value: [0, 0, 0, 0, 0, 0, 0],
    },
    {
      name: "上週用電量",
      value: [0, 0, 0, 0, 0, 0, 0],
    },
  ],
});

const generateWeekCategories = () => {
  const today = dayjs();
  const currentDay = today.day();
  const daysOfWeek = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
  const dynamicCategories = [];

  for (let i = 0; i < 7; i++) {
    const dayIndex = (currentDay - i + 7) % 7;
    dynamicCategories.unshift(daysOfWeek[dayIndex]);
  }

  return dynamicCategories;
};

weekComparisonData.value = {
  ...weekComparisonData.value,
  categories: generateWeekCategories(),
};

watch(
  () => elecDataStore.elecFlowCostSummary,
  (newElecData) => {
    console.log("elecStandCostSummary", newElecData);
    if (newElecData && newElecData.dailyResults) {
      const today = dayjs().format("YYYY-MM-DD");
      const yesterday = dayjs().subtract(1, "day").format("YYYY-MM-DD");

      const todayData = newElecData.dailyResults.find(
        (item) => item.dateStr === today
      );
      const yesterdayData = newElecData.dailyResults.find(
        (item) => item.dateStr === yesterday
      );

      const todayElecCost = todayData ? todayData.dailyEleCost : 0;
      const yesterdayElecCost = yesterdayData ? yesterdayData.dailyEleCost : 0;

      elecStat.value = [
        {
          ...elecStat.value[0],
          value: todayElecCost,
        },
        {
          ...elecStat.value[1],
          value: yesterdayElecCost,
        },
        {
          ...elecStat.value[2],
        },
        {
          ...elecStat.value[3],
        },
      ];

      const thisWeekData = newElecData.dailyResults
        .slice(-7)
        .map((item) => item.dailyEleCost || 0);
      const lastWeekData = newElecData.dailyResults
        .slice(-14, -7)
        .map((item) => item.dailyEleCost || 0);

      weekComparisonData.value = {
        ...weekComparisonData.value,
        values: [
          {
            name: "本週用電量",
            value: thisWeekData,
          },
          {
            name: "上週用電量",
            value: lastWeekData,
          },
        ],
      };
    }
  },
  { deep: true }
);

watch(
  () => [elecDataStore.todayelecdata, elecDataStore.yesterdayelecdata],
  ([newTodayData, newYesterdayData]) => {
    console.log("todayyesterday", newTodayData, newYesterdayData);

    const todayDate = dayjs().format("YYYY-MM-DD");
    const yesterdayDate = dayjs().subtract(1, "day").format("YYYY-MM-DD");

    const categories = [];
    const todayValues = [];

    for (const [timestamp, value] of newTodayData) {
      const hour = dayjs(timestamp).format("HH:00");
      categories.push(hour);
      todayValues.push(value);
    }

    categories.sort();

    const filledYesterdayValues = categories.map((hour) => {
      const timestamp = dayjs(
        `${yesterdayDate} ${hour}`,
        "YYYY-MM-DD HH:00"
      ).format("YYYY-MM-DDTHH:mm:ss.000+08:00");
      return newYesterdayData.get(timestamp) || 0;
    });

    console.log("todayValues", todayValues, filledYesterdayValues);
    yesterdayTodayData.value = {
      categories: categories,
      values: [
        {
          name: `${todayDate} 用電量`,
          value: todayValues,
        },
        {
          name: `${yesterdayDate} 用電量`,
          value: filledYesterdayValues,
        },
      ],
    };
  },
  { deep: true }
);

watch(
  () => elecDemandStore.elecData,
  (newElecData) => {
    console.log("elecDemandStore.elecData updated:", newElecData);

    const newElecDemand_P =
      newElecData.find((item) => item.name === "P")?.out || 0;
    const newElecDemand_Engel =
      newElecData.find((item) => item.name === "Engel")?.out || 0;

    elecDemand_P.value = newElecDemand_P;
    elecDemand_Engel.value = newElecDemand_Engel;

    elecStat.value = [
      ...elecStat.value.slice(0, 2),
      {
        ...elecStat.value[2],
        value: newElecDemand_P,
      },
      {
        ...elecStat.value[3],
        value: newElecDemand_Engel
          ? ((newElecDemand_P / newElecDemand_Engel) * 100).toFixed(2)
          : 0,
      },
    ];
  },
  { deep: true }
);

onMounted(async () => {
  await elecDataStore.getElecDataFromBaja();
  elecDataStore.startTimer();

  await elecDemandStore.getElecDemandFromBaja();
});

onUnmounted(() => {
  elecDataStore.stopTimer();
  elecDemandStore.clearAllSubscriber();
});
</script>
<template>
  <a-row :gutter="24" class="px-5 py-2">
    <a-col :span="8">
      <!-- 建築物 -->
      <DashboardBuild />
    </a-col>
    <a-col :span="16" class="">
      <!-- 用電數據 -->
      <DashboardStat :elecData="elecStat" />
      <!-- 用電圖表 -->
      <DashboardElecChart
        :yesterdayTodayData="yesterdayTodayData"
        :weekComparisonData="weekComparisonData"
      />
    </a-col>
  </a-row>

  <a-row :gutter="24" class="px-5">
    <a-col :span="14">
      <!-- 系統小類 -->
      <DashboardTag />
    </a-col>
    <a-col :span="10">
      <!-- 告警 -->
      <DashboardAlert />
    </a-col>
  </a-row>
</template>

<style scoped></style>
