import { defineStore } from "pinia";
import { ref, computed, watch } from "vue";
import { useRoute } from "vue-router";
import { getBuildings } from "@/apis/building";
import { getDashboard2D3D } from "@/apis/dashboard";
import { getAssetFloorList, getDepartmentList } from "@/apis/asset";

const useBuildingStore = defineStore("buildingInfo", () => {
  // 狀態定義
  const buildings = ref([]);
  const selectedBuilding = ref(null);
  const floorList = ref([]);
  const deptList = ref([]);
  const mainSubSys = ref([]);
  // 控制顯示2D/3D切換與內容
  const showForgeArea = ref(true);
  const previewImageExt = ref("");

  // 計算屬性
  const mainSys = computed(() =>
    mainSubSys.value.map(({ main_system_tag, full_name }) => ({
      main_system_tag,
      full_name,
    }))
  );

  const subSys = computed(() => {
    let subPages = [];
    mainSubSys.value.forEach(({ main_system_tag, history_Sub_systems }) => {
      subPages = [
        ...subPages,
        ...history_Sub_systems.map((Sub) => ({
          ...Sub,
          main_system_tag,
          key: Sub.sub_system_tag,
        })),
      ];
    });
    return subPages;
  });

  const route = useRoute();
  const selectedSystem = computed(() => {
    if (route.params.sub_system_id && subSys.value.length > 0) {
      return subSys.value.find((s) => s.key === route.params.sub_system_id);
    }
    return null;
  });

  // 獲取所有建築物
  const fetchBuildings = async () => {
    // const res = await getBuildings();
    buildings.value = JSON.parse(localStorage.getItem("CviBuildingList")) || [];
    const storedBuilding = JSON.parse(localStorage.getItem("CviBuilding"));
    if (buildings.value.length > 0) {
      selectedBuilding.value = storedBuilding || buildings.value[0]; // 預設選第一個建築
    } else {
      selectedBuilding.value = null; // 如果沒有建築物，清空選擇
    }
  };

  // 獲取樓層資料
  const fetchFloorList = async (building_guid) => {
    const res = await getAssetFloorList(building_guid);
    floorList.value =
      res.data[0]?.floors.map((d) => ({
        ...d,
        title: d.full_name,
        key: d.floor_guid,
      })) || [];
  };

  // 獲取部門資料
  const fetchDepartmentList = async () => {
    const res = await getDepartmentList();
    deptList.value =
      res.data.map((d) => ({
        ...d,
        title: d.name,
        key: d.id,
      })) || [];
  };

  // 獲取2D、3D顯示與否
  const fetchDashboard2D3D = async (BuildingId) => {
    const res = await getDashboard2D3D(BuildingId);
    showForgeArea.value = res.data?.is3DEnabled || false;
    previewImageExt.value = res.data?.previewImageExt || "";
  };

  // 清除localStorage建築物
  const deleteBuilding = () => {
    localStorage.removeItem("CviBuildingList");
    localStorage.removeItem("CviBuilding");
    buildings.value = [];
    selectedBuilding.value = null;
  };

  // 當 selectedBuilding 改變時，更新 floorList 和 deptList
  watch(selectedBuilding, async (newBuilding) => {
    if (newBuilding) {
      localStorage.setItem("CviBuilding", JSON.stringify(newBuilding));
      await Promise.all([
        fetchFloorList(newBuilding.building_guid),
        fetchDepartmentList(),
        fetchDashboard2D3D(newBuilding.building_guid),
      ]);
    }
  });

  // 初始化資料
  const initialize = async () => {
    await fetchBuildings();
  };

  return {
    buildings,
    selectedBuilding,
    floorList,
    deptList,
    mainSubSys,
    mainSys,
    subSys,
    selectedSystem,
    showForgeArea,
    previewImageExt,
    deleteBuilding,
    fetchBuildings,
    fetchFloorList,
    fetchDepartmentList,
    fetchDashboard2D3D,
    initialize,
  };
});
export default useBuildingStore;
