<script setup>
import { ref, watch, inject } from "vue";
import dayjs from "dayjs";
import { useI18n } from "vue-i18n";

const { t } = useI18n();
const { realTime_data } = inject("energy_data");

const voltage = ref([
  { point: `${t("energy.line_voltage")} V12`, value: 0 },
  { point: `${t("energy.line_voltage")} V23`, value: 0 },
  { point: `${t("energy.line_voltage")} V31`, value: 0 },
]);
const current = ref([
  { point: `${t("energy.electric_current")} 1`, value: 0 },
  { point: `${t("energy.electric_current")} 2`, value: 0 },
  { point: `${t("energy.electric_current")} 3`, value: 0 },
]);
const lastUpdated = ref("");

watch(
  () => realTime_data.value,
  (newData) => {
    newData.data.forEach(({ point, value }) => {
      switch (point) {
        case "U12":
          voltage.value[0].value = value;
          break;
        case "U23":
          voltage.value[1].value = value;
          break;
        case "U31":
          voltage.value[2].value = value;
          break;
        case "I1":
          current.value[0].value = value;
          break;
        case "I2":
          current.value[1].value = value;
          break;
        case "I3":
          current.value[2].value = value;
          break;
      }
    });
    lastUpdated.value = dayjs(newData.time).format("YYYY-MM-DD HH:mm:ss");
  },
  { 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
      v-for="(item, index) in voltage"
      :key="`voltage-${index}`"
      class="stat place-items-start"
    >
      <div class="stat-title text-gray-200 3xl:text-[2rem]">
        {{ item.point }} (V)
      </div>
      <div class="stat-value text-success text-5xl 3xl:text-[6rem]">
        {{ item.value }}
      </div>
      <div class="stat-desc text-gray-400 3xl:text-[2rem]">
        {{ lastUpdated }}
      </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
      v-for="(item, index) in current"
      :key="`current-${index}`"
      class="stat place-items-start"
    >
      <div class="stat-title text-gray-200 3xl:text-[2rem]">
        {{ item.point }} (A)
      </div>
      <div class="stat-value text-success text-5xl 3xl:text-[6rem]">
        {{ item.value }}
      </div>
      <div class="stat-desc text-gray-400 3xl:text-[2rem]">
        {{ lastUpdated }}
      </div>
    </div>
  </div>
</template>

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