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

const useBuildingStore = defineStore("buildingInfo", () => {
  // 狀態定義
  const buildings = ref([]);
  const selectedBuilding = ref(null);
  const floorList = ref([]);
  const deptList = ref([]);
  const mainSubSys = ref([]);
  const sysConfig = 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 = res.data;
    if (res.data.length > 0 ) {
      selectedBuilding.value = res.data[0]; // 預設選第一個建築
    }else{
      selectedBuilding.value = null; // 如果沒有建築物，則設為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,
      })) || [];
  };

  // 取得大小類
  const getSubMonitorPage = async (building_guid) => {
    const res = await getAllSysSidebar(building_guid);
    mainSubSys.value = res.data.history_Main_Systems;
  };

  // 取得系統設定
  const getSysConfig = async (building_guid) => {
    const res = await getSystemConfig(building_guid);
    sysConfig.value = res.data;
  };

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

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

  return {
    buildings,
    selectedBuilding,
    floorList,
    deptList,
    mainSubSys,
    mainSys,
    subSys,
    selectedSystem,
    sysConfig,
    fetchBuildings,
    fetchFloorList,
    fetchDepartmentList,
    getSubMonitorPage,
    initialize,
    getSysConfig,
  };
});
export default useBuildingStore;
