import { defineStore } from "pinia";
import { ref, computed } from "vue";
import { useRoute } from "vue-router";

const useBuildingStore = defineStore("buildingInfo", () => {
  // 所有棟別
  const buildings = ref([]);

  const selectedBuilding = ref(null);

  // 所有大小類系統
  const mainSubSys = 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;
  });

  return {
    buildings,
    selectedBuilding,
    mainSubSys,
    mainSys,
    subSys,
    selectedSystem,
  };
});

export default useBuildingStore;
