<script setup>
import { ref, watch, onUnmounted } from "vue";
import { getAlertLogList } from "@/apis/alert";
import useBuildingStore from "@/stores/useBuildingStore";
const store = useBuildingStore();

const dataSource = ref([]);
let intervalId = null; // 用來儲存 setInterval 的 ID

const getAlarmData = async (building_guid) => {
  const res = await getAlertLogList(building_guid);
  dataSource.value = res.data || [];
};

watch(
  () => store.selectedBuilding,
  (newBuilding) => {
    if (intervalId) {
      clearInterval(intervalId);
      intervalId = null;
    }
    if (newBuilding) {
      getAlarmData(newBuilding.building_guid);

      intervalId = setInterval(() => {
        getAlarmData(newBuilding.building_guid);
      }, 30 * 1000);
    }
  },
  { immediate: true }
);

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

<template>
  <h3 class="text-info text-xl text-center">
    {{ $t("dashboard.alerts_data") }} Top 5
  </h3>
  <div class="overflow-x-auto min-h-[300px]">
    <table class="table">
      <thead>
        <tr class="border-b-2 border-info text-base">
          <th>{{ $t("operation.date") }}</th>
          <th>{{ $t("operation.time") }}</th>
          <th>{{ $t("operation.device_name") }}</th>
          <th>{{ $t("operation.remark") }}</th>
        </tr>
      </thead>
      <tbody class="text-base">
        <tr v-for="alarm in dataSource" :key="alarm.id">
          <td>{{ alarm.year }}</td>
          <td>{{ alarm.time }}</td>
          <td>{{ alarm.device_number }}</td>
          <td>{{ alarm.remark }}</td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<style lang="scss" scoped>
th,
td {
  @apply whitespace-nowrap;
}
</style>
