<script setup>
import { ref, onMounted, onUnmounted } from "vue";
import { getAlertLog } from "@/apis/alert";
import dayjs from "dayjs";

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

const getAlarmData = async () => {
  const res = await getAlertLog({
    isRecovery: 1,
    Start_date: dayjs().format("YYYY-MM-DD"),
    End_date: dayjs().format("YYYY-MM-DD"),
  });
  dataSource.value = (res.data || []).map((d) => ({ ...d, key: d.id }));
};

onMounted(() => {
  getAlarmData();

  intervalId = setInterval(() => {
    getAlarmData();
  }, 30 * 1000); 
});

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

<template>
  <div>
    <ul class="pr-4 min-h-full text-base-content">
      <!-- Sidebar content here -->
      <li class="my-3" v-for="alarm in dataSource" :key="alarm.id">
        <div
          class="w-full shadow-xl border border-success bg-body bg-opacity-80"
        >
          <div class="p-5">
            <p class="text-base flex justify-between">
              <span>
                <font-awesome-icon
                  :icon="['fas', 'exclamation-triangle']"
                  class="text-warning mr-2"
                />
                <span>{{ $t("alarm.notify") }}</span></span
              >
              <small>
                <span class="mr-4"
                  >{{ alarm.created_at }}</span
                >
                <!-- <font-awesome-icon
                  :icon="['fas', 'times']"
                  size="lg"
                  class="text-white"
                /> -->
              </small>
            </p>
            <div class="divider my-2"></div>
            <div>
              <p>{{ $t("alarm.number") }}：{{ alarm.id }}</p>
              <p>{{ $t("alert.alarmClass") }}：{{ alarm.factor }}</p>
              <p>{{ $t("alarm.device_name") }}：{{ alarm.device_number }}</p>
              <p>{{ $t("alert.device_point_name") }}：{{ alarm.points }}</p>
              <p>{{ $t("alert.error_msg") }}：{{ alarm.reason }}</p>
            </div>
          </div>
        </div>
      </li>
    </ul>
  </div>
</template>

<style lang="scss" scoped>
.card::before {
  @apply absolute h-5 w-5 top-1 left-1 bg-no-repeat z-10 bg-[url('../../assets/img/table/content-box-background01.svg')] bg-center;
  content: "";
}

.card::after {
  @apply absolute bottom-1 right-1 h-5 w-5 bg-no-repeat z-10 bg-[url('../../assets/img/table/content-box-background05.svg')] bg-center;
  content: "";
}
</style>