<script setup>
import ImmediateDemandChart from "./components/ImmediateDemandChart.vue";
import CurrentInformation from "./components/CurrentInformation.vue";
import UsageInformation from "./components/UsageInformation.vue";
import ElectricityBillChart from "./components/ElectricityBillChart.vue";
import BillingDegreeChart from "./components/BillingDegreeChart.vue";
import { getRealTimeData, getElecUseMonth, getElecUseofDay } from "@/apis/energy";
import { ref, onMounted, provide, onBeforeUnmount } from "vue";

const realTime_data = ref([]);
const interval = ref(null);
const elecMonth_data = ref([]);
const elecDay_data = ref([]);
const getRealTime = async () => {
  const res = await getRealTimeData();
  if (res.isSuccess) {
    realTime_data.value = res.data[0];
  }
};
const getElecMonth = async () => {
  const res = await getElecUseMonth();
  if (res.isSuccess) {
    elecMonth_data.value = res.data.sort((a, b) => a.time.localeCompare(b.time));
  }
};
const getElecDay = async () => {
  const res = await getElecUseofDay();
  if (res.isSuccess) {
    elecDay_data.value = res.data;
  }
};

const getRealtimeIntervalData = () => {
  interval.value = setInterval(() => {
    getRealTime();
  }, 1000 * 60);
};

onMounted(() => {
  getRealTime();
  getRealtimeIntervalData();
  getElecMonth();
  getElecDay();
});

onBeforeUnmount(() => {
  clearInterval(interval.value);
});

provide("energy_data", { realTime_data, elecMonth_data, elecDay_data });
</script>

<template>
  <div class="grid gap-4 md:grid-cols-5 grid-cols-1 h-[47%] my-4">
    <div class="md:col-span-3 col-span-1">
      <ImmediateDemandChart />
    </div>
    <div class="md:col-span-2 col-span-1">
      <CurrentInformation />
    </div>
  </div>
  <div class="grid gap-4 md:grid-cols-3 grid-cols-1 h-[47%]">
    <div class="col-span-1">
      <UsageInformation />
    </div>
    <div class="col-span-1">
      <ElectricityBillChart />
    </div>
    <div class="col-span-1">
      <BillingDegreeChart />
    </div>
  </div>
</template>

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