<script setup>
import { ref, computed, watch, onUnmounted } from "vue";
import SysProgress from "./components/SysProgress.vue";
import ElecRank from "./components/ElecRank.vue";
import ElecTrends from "./components/ElecTrends.vue";
import ElecCompare from "./components/ElecCompare.vue";
import { getEnergyCost } from "@/apis/dashboard";
import useBuildingStore from "@/stores/useBuildingStore";

const store = useBuildingStore();
let intervalId = null;
const energyCostData = ref({});
const formState = ref({
  building_guid: null,
  floor_guid: "all",
  department_id: "all",
});

const getEnergyCostData = async (params) => {
  const res = await getEnergyCost(params);
  energyCostData.value = res.data;
};

watch(
  () => store.selectedBuilding,
  (newBuilding) => {
    if (newBuilding) {
      formState.value.building_guid = newBuilding.building_guid;
    }
  },
  { immediate: true, deep: true }
);

watch(
  () => formState.value,
  (newVal) => {
    if (newVal) {
      const params = { ...newVal };

      if (params.floor_guid === "all") {
        delete params.floor_guid;
      }
      if (params.department_id === "all") {
        delete params.department_id;
      }

      if (params.building_guid) {
        getEnergyCostData(params);
      }

      if (intervalId) {
        clearInterval(intervalId);
      }
      intervalId = setInterval(() => {
        getEnergyCostData(params);
      }, 3600000);
    }
  },
  { immediate: true, deep: true }
);

onUnmounted(() => {
  clearInterval(intervalId);
});
</script>

<template>
  <div class="flex gap-4">
    <div class="w-full xl:w-1/4 mt-2">
      <div class="area-img-box">
        <img
          alt="build"
          src="/build_img.jpg"
          class="w-full h-48 object-cover border-cyan-400 shadow-cyan-500/40"
        />
        <p
          class="p-4 text-gray-100 text-base font-light bg-gray-800/60 rounded-b-xl backdrop-blur-md border-t border-cyan-400/30 shadow-inner"
        >
          深耕電子精密連接器、光通信元件、軟性排線、線纜組件、PCBA電子機板、電子成品專業製造廠並代理電子零組件做為整合行銷。公司創立於1990年，產品行銷全球以穩定，快速以及高品質知名;
          未來，瀚荃會持續精進提供更快、更好以及高附加價值的產品與服務來滿足您的需求。
        </p>
      </div>
      <!--狀態、進度-->
      <SysProgress />
    </div>
    <div class="w-full xl:w-2/4 mt-2"></div>
    <div class="w-full xl:w-1/4 mt-2">
      <ElecRank :energyCostData="energyCostData" />
      <ElecTrends
        :formState="formState"
        :energyCostData="energyCostData"
        :getEnergyCostData="getEnergyCostData"
      />
      <ElecCompare :energyCostData="energyCostData" />
    </div>
  </div>
</template>

<style lang="scss" scoped>
.area-img-box {
  @apply border border-light-info bg-gray-900/80 backdrop-blur-lg relative overflow-hidden shadow-md shadow-blue-300 mb-3;
}
</style>
