<script setup>
import { ref, computed, watch, onUnmounted } from "vue";
import { useRouter } from "vue-router";
import { getAlarmOperationInfo } from "@/apis/dashboard";
import useBuildingStore from "@/stores/useBuildingStore";
import DashboardSysProgressModal from "./DashboardSysProgressModal.vue";
import { useI18n } from "vue-i18n";

const { t } = useI18n();
const router = useRouter();
const store = useBuildingStore();
const equipmentData = ref({
  title: t("dashboard.system_status"),
  items: [],
});
const orderData = ref({
  title: t("dashboard.work_order"),
  items: [],
});
const modalData = ref({});
let intervalId = null;

const getAlarmsInfos = async () => {
  try {
    const res = await getAlarmOperationInfo(
      store.selectedBuilding.building_guid
    );
    const apiData = res.data;

    // 轉換 equipmentData 的資料格式
    if (apiData && apiData.alarm) {
      equipmentData.value.items = apiData.alarm.map((item) => ({
        label: item.name,
        online: item.online || 0,
        offline: item.offline || 0,
        alarm: item.alarm || 0,
      }));
    }

    // 轉換 orderData 的資料格式
    if (apiData && apiData.operation) {
      orderData.value.items = [
        {
          label: t("operation.repair"),
          complete: apiData.operation.repair.complete || 0,
          incomplete: apiData.operation.repair.incomplete || 0,
        },
        {
          label: t("operation.maintenance"),
          complete: apiData.operation.upkeep.complete || 0,
          incomplete: apiData.operation.upkeep.incomplete || 0,
        },
      ];
    }
  } catch (error) {
    console.error("Error fetching alarm info:", error);
  }
};

const navigateToMaintenance = (item) => {
  router.push({
    name: "operation",
    query: {
      work_type: item == "Repair" ? "2" : "1",
    },
  });
};

const openModal = (item) => {
  modalData.value = item;
  system_status_modal.showModal();
};

const onCancel = () => {
  modalData.value = {};
  system_status_modal.close();
};

watch(
  () => store.selectedBuilding,
  (newBuilding) => {
    if (newBuilding) {
      getAlarmsInfos();

      if (intervalId) {
        clearInterval(intervalId);
      }
      intervalId = setInterval(() => {
        getAlarmsInfos();
      }, 30000);
    }
  },
  { immediate: true }
);

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

<template>
  <DashboardSysProgressModal :onCancel="onCancel" :modalData="modalData" />
  <div class="flex flex-wrap">
    <div class="w-full sm:w-2/5 state-box-col relative ps-2">
      <div class="state-box">
        <div class="title">
          <img class="state-title01" src="@ASSET/img/state-title01.svg" />
          <span>{{ orderData.title }}</span>
          <img class="state-title02" src="@ASSET/img/state-title02.svg" />
        </div>
        <table class="table table-sm text-center">
          <thead>
            <tr class="border-cyan-400 text-cyan-100">
              <th></th>
              <th>{{ $t("operation.complete") }}</th>
              <th>{{ $t("operation.incomplete") }}</th>
            </tr>
          </thead>
          <tbody>
            <tr
              v-for="(item, index) in orderData.items"
              :key="index"
              class="border-cyan-400 cursor-pointer hover:text-info"
              @click.stop.prevent="navigateToMaintenance(item.label)"
            >
              <th class="px-0 text-start">
                <span>{{ item.label }}</span>
              </th>
              <td>{{ item.complete }}</td>
              <td>{{ item.incomplete }}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
    <div class="w-full sm:w-3/5 state-box-col relative ps-2">
      <div class="state-box">
        <div class="title">
          <img class="state-title01" src="@ASSET/img/state-title01.svg" />
          <span class="">{{ equipmentData.title }}</span>
          <img class="state-title02" src="@ASSET/img/state-title02.svg" />
        </div>
        <table class="table table-sm text-center">
          <thead>
            <tr class="border-cyan-400 text-cyan-100">
              <th></th>
              <th>{{ $t("alert.online") }}</th>
              <th>{{ $t("alert.offline") }}</th>
              <th>{{ $t("alert.alarm") }}</th>
            </tr>
          </thead>
          <tbody>
            <tr
              v-for="(item, index) in equipmentData.items"
              :key="index"
              class="border-cyan-400 cursor-pointer hover:text-info"
              @click.stop.prevent="openModal(item)"
            >
              <th class="px-0 text-start">{{ item.label }}</th>
              <td>
                {{ item.online.length }}
              </td>
              <td>
                {{ item.offline.length }}
              </td>
              <td>
                {{ item.alarm.length }}
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.state-box-col:before {
  @apply absolute left-0 right-0 -top-0.5 m-auto h-2 w-36 bg-no-repeat bg-center z-10;
  content: "";
  background-image: url(@ASSET/img/state-box-top.png);
}

.state-box-col:after {
  @apply absolute left-0 right-0 -bottom-0.5 m-auto h-2 w-36 bg-no-repeat bg-center z-10;
  content: "";
  background-image: url(@ASSET/img/state-box-bottom.png);
}

.state-box {
  @apply h-[22rem] border-2 border-light-info rounded-sm py-2 px-6 text-white relative;
}

.state-box:after {
  @apply absolute right-3 top-3 w-4 h-4 bg-no-repeat bg-center z-10;
  content: "";
  background-image: url(@ASSET/img/state-title01.svg);
}

.state-box:before {
  @apply absolute right-0.5 bottom-5 w-4 h-32 bg-no-repeat bg-center z-10;
  content: "";
  background-image: url(@ASSET/img/state-ul-background02.svg);
}

.state-box .title {
  @apply relative flex items-center mb-1;
}

.state-box .title .state-title01 {
  @apply w-4 mr-1.5;
}

.state-box .title .state-title02 {
  @apply w-5 ml-1.5;
}
</style>
