<script setup>
import ButtonGroup from "@/components/customUI/ButtonGroup.vue";
import ElecPriceRes from "./ElecPriceRes.vue";
import ElecPriceStd from "./ElecPriceStd.vue";
import { computed, watch, onBeforeMount, ref, provide, markRaw } from "vue";
import useActiveBtn from "@/hooks/useActiveBtn";
import { useI18n } from "vue-i18n";
import { getTimeElec } from "@/apis/energy";
import useBuildingStore from "@/stores/useBuildingStore";
const store = useBuildingStore();
const { t, locale } = useI18n();
const sim2 = ref([]);
const sim3 = ref([]);
const stand2 = ref([]);
const stand3 = ref([]);

const changeComponent = (e, item) => {
  changeActiveBtn(item);
};

const { items, changeActiveBtn, setItems } = useActiveBtn();

const initializeItems = () => {
  setItems([
    {
      title: t("energy.residential"),
      key: "Residential",
      active: true,
      component: markRaw(ElecPriceRes),
    },
    {
      title: t("energy.standard"),
      key: "Standard",
      active: false,
      component: markRaw(ElecPriceStd),
    },
  ]);
};

onBeforeMount(() => {
  initializeItems();
});

const activeTab = computed(() => {
  return items.value.find(({ active }) => active);
});

const getData = async () => {
  if (store.selectedBuilding.building_guid) {
    const res = await getTimeElec(store.selectedBuilding.building_guid);

    // 重置 ref 變數
    sim2.value = [];
    sim3.value = [];
    stand2.value = [];
    stand3.value = [];

    res.data.forEach((item) => {
      switch (item.sheet) {
        case "sim2":
          sim2.value = item.data;
          break;
        case "sim3":
          sim3.value = item.data;
          break;
        case "stand2":
          stand2.value = item.data;
          break;
        case "stand3":
          stand3.value = item.data;
          break;
        default:
          console.warn(`Unknown sheet: ${item.sheet}`);
      }
    });
  }
};

watch(
  () => store.selectedBuilding,
  (newBuilding) => {
    if (newBuilding) {
      getData();
    }
  },
  { immediate: true }
);

provide("time_elec", { sim2, sim3, stand2, stand3, getData });
</script>

<template>
  <h1 class="text-2xl font-extrabold mb-2">
    {{ $t("energy.elec_price_list") }}
  </h1>
  <div class="content-box-background border-info border text-base p-4">
    <span class="font-semibold text-info">說明：</span>
    本系統使用「標準型時間電價二段式」來試算電費。<br />
    本系統所提供之時間電價計算結果，係以未超過契約容量為前提所進行之估算，僅供用電分析與管理參考之用。
  </div>
  <ButtonGroup
    :items="items"
    :withLine="true"
    class="my-6"
    :onclick="changeComponent"
  />
  <component :is="activeTab.component"></component>
</template>

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