<script setup>
import { onMounted, ref, watch, onUnmounted } from "vue";
import Forge from "@/components/forge/Forge.vue";
import DashboardProduct from "./components/DashboardProduct.vue";
import DashboardTarget from "./components/DashboardTarget.vue";
import DashboardImmediateTemp from "./components/DashboardImmediateTemp.vue";
import DashboardFrozenTemp from "./components/DashboardFrozenTemp.vue";
import DashboardElectricity from "./components/DashboardElectricity.vue";
import DashboardAlert from "./components/DashboardAlert.vue";
import DashboardForgeOptionButton from "./components/DashboardForgeOptionButton.vue";
import DashboardForgeOptionCard from "./components/DashboardForgeOptionCard.vue";
import DashboardMoreModal from "./components/DashboardMoreModal.vue";
import {
  getDashboardInit,
  getDashboardOptionRealTimeData,
} from "@/apis/dashboard";
import { getAssetFloorList } from "@/apis/asset";
import { getOperationCompanyList } from "@/apis/operation";
import useSearchParams from "@/hooks/useSearchParam";
import useSystemHeatmap from "@/hooks/baja/useSystemHeatmap";
import dayjs from "dayjs";

const initialData = ref(null);
const realTimeData = ref(null);
const pipeData = ref([]);
const realTime = ref(null);
// 電表列表
const meterList = ref([]);
const selectedMeter = ref(null);
// 冷藏室及時溫度
const heatmapDevices = ref([]);
// 樓層列表
const floors = ref([]);
// 廠商列表
const companyOptions = ref([]);

const { changeParams, searchParams } = useSearchParams();
let intervalId = null;

const init = async () => {
  try {
    const res = await getDashboardInit();
    initialData.value = res.data;
  } catch (err) {
    console.error("初始化失敗:", err);
  }
};

const getDevice = async (option = 1) => {
  try {
    const res = await getDashboardOptionRealTimeData({
      option: parseInt(option),
    });
    realTimeData.value = res.data;
    if (res.data?.meterData) {
      // 先複製 meterList
      let meters = (res.data?.meterData || []).sort();
      // 取得 dbid_list
      const dbidList = initialData.value?.dbid_list || [];
      // 對每個 meter 做 forge_dbid 對應
      meters = meters.map((meter) => {
        const dbidItem = dbidList.find(
          (d) => d.forge_dbid === meter.forge_dbid
        );
        return {
          ...meter,
          device_coordinate_3d:
            JSON.parse(dbidItem?.device_coordinate_3d) || null,
        };
      });
      meterList.value = meters;
      // 如果 selectedMeter 沒有值，且 meterList 有資料，預設選擇第一個
      if (
        selectedMeter.value == null &&
        meterList.value[0]?.main_id !== undefined
      ) {
        selectedMeter.value = meterList.value[0].main_id;
        changeParams({
          option: 5,
          camera_position: meterList.value[0].camera_position,
          target_position: meterList.value[0].target_position,
        });
      }
    } else if (res.data?.refrigerationData) {
      heatmapDevices.value = res.data.refrigerationData;
    } else {
      meterList.value = [];
      heatmapDevices.value = [];
    }
    // 水管數據
    pipeData.value = res.data?.pipeData || [];
    // 更新熱點圖數據時間
    realTime.value = dayjs().format("YYYY-MM-DD HH:mm:ss");
    console.log("實時數據:", realTimeData.value);
  } catch (err) {
    console.error("獲取實時數據失敗:", err);
  }
};

const getFloors = async () => {
  const res = await getAssetFloorList();
  floors.value = res.data[0]?.floors.map((d) => ({ ...d, key: d.floor_guid }));
};

const getCompany = async () => {
  const res = await getOperationCompanyList();
  companyOptions.value = res.data.map((d) => ({ ...d, key: d.id }));
};

const currentIntervalType = ref("");

const openModal = (type) => {
  currentIntervalType.value = type;
  dashboard_more.showModal();
};

// 開始定時器
const startInterval = (option) => {
  // 清除之前的定時器
  if (intervalId) {
    clearInterval(intervalId);
  }

  // 立即執行一次
  getDevice(option);

  // 設定每5秒執行一次
  intervalId = setInterval(() => {
    getDevice(option);
  }, 10 * 1000);
};

// 停止定時器
const stopInterval = () => {
  if (intervalId) {
    clearInterval(intervalId);
    intervalId = null;
  }
};

watch(
  () => searchParams.value.option,
  (newValue) => {
    if (newValue) {
      startInterval(newValue);
    }
  },
  {
    immediate: true,
    deep: true,
  }
);

onMounted(() => {
  init();
  getFloors();
  getCompany();
});

onUnmounted(() => {
  stopInterval();
});
</script>

<template>
  <DashboardMoreModal :currentIntervalType="currentIntervalType" />
  <div class="flex justify-between">
    <div class="w-1/4 h-full flex flex-col justify-start border-dashboard z-20">
      <div class=""><DashboardProduct /></div>
      <div class="mt-5">
        <DashboardTarget />
      </div>
      <div class="mt-5">
        <DashboardAlert />
      </div>
    </div>
    <Forge
      :fullScreen="true"
      :initialData="initialData"
      :pipeData="pipeData"
      :realTime="realTime"
      :meterList="meterList"
      :heatmapDevices="heatmapDevices"
    />
    <DashboardForgeOptionButton
      :initialData="initialData"
      :meterList="meterList"
      :selectedMeter="selectedMeter"
      @update:selectedMeter="selectedMeter = $event"
    />
    <DashboardForgeOptionCard
      :realTimeData="realTimeData"
      :selectedMeter="selectedMeter"
      :floors="floors"
      :companyOptions="companyOptions"
    />
    <div class="w-1/4 flex flex-col justify-start border-dashboard z-20">
      <div class="">
        <DashboardImmediateTemp @open-modal="openModal" />
      </div>
      <div class="mt-5">
        <DashboardFrozenTemp  @open-modal="openModal"/>
      </div>
      <div class="mt-5">
        <DashboardElectricity />
      </div>
    </div>
  </div>
</template>

<style lang="css" scoped>
.border-dashboard {
  @apply border border-light-info bg-dark-info bg-opacity-70 p-3  first:mt-0 last:mb-0;
}
</style>
