<script setup>
import { ref, onMounted, watch } from "vue";
import useSearchParam from "@/hooks/useSearchParam";
import useActiveBtn from "@/hooks/useActiveBtn";
import { getAlertSubList } from "@/apis/alert";
import useBuildingStore from "@/stores/useBuildingStore";
const store = useBuildingStore();
const { searchParams, changeParams } = useSearchParam();
const { items, changeActiveBtn, setItems, selectedBtn } = useActiveBtn();

const getSubSystems = async () => {
  const res = await getAlertSubList(store.selectedBuilding.building_guid);
  const history_Sub_systems = res.data.history_Main_Systems.flatMap(
    (mainSystem) => {
      return mainSystem.history_Sub_systems;
    }
  );
  const subSystems = history_Sub_systems.map((subSystem, index) => ({
    title: subSystem.full_name,
    key: subSystem.sub_system_tag,
    active: searchParams.value?.subSys_id
      ? searchParams.value.subSys_id === subSystem.sub_system_tag
      : index == 0,
  }));
  setItems(subSystems);
};

watch(
  () => store.selectedBuilding,
  (newBuilding) => {
    if (newBuilding) {
      getSubSystems();
    }
  },
  { immediate: true }
);

watch(selectedBtn,
  (newValue) => {
  if (newValue) {
    changeParams({ subSys_id: newValue.key });
  }
  }
);
</script>

<template>
  <div class="mt-4">
    <ButtonConnectedGroup :items="items" 
      :onclick="(e, item) => {changeActiveBtn(item)}"
      :className="`flex flex-wrap w-full mt-4`" size="sm" color="info">
      <template #buttonContent="{ item }">
        <span class="text-base">{{ item.title }}</span>
      </template>
    </ButtonConnectedGroup>
  </div>
</template>

<style lang="scss" scoped></style>