<script setup>
import { useRoute, useRouter } from 'vue-router';
import { getSystemFloors } from "@/apis/system"
import { onMounted, ref, watch, inject } from 'vue';
import useBuildingStore from "@/stores/useBuildingStore";
import useActiveBtn from "@/hooks/useActiveBtn"

const route = useRoute()
const router = useRouter()
const store = useBuildingStore();

const { updateCurrentFloor } = inject("system_deviceList")


const { items, changeActiveBtn, setItems, selectedBtn } = useActiveBtn();
const getFloors = async () => {
  const res = await getSystemFloors(store.selectedBuilding?.building_tag, route.params.sub_system_id)
  setItems([
    {
      title: "總覽",
      key: "main",
      active: route.params.floor_id ? false : true,
    },
    ...res.data.map((d, idx) => ({
      title: d.floor_tag,
      key: d.floor_guid,
      active: route.params.floor_id === d.floor_guid,
      map_url: d.floor_map_name
    }))
  ]);
}

const onClick = (item) => {
  changeActiveBtn(item)
  updateCurrentFloor(item)
  if (item.key == "main") {
    router.push({
      name: 'sub_system', params: {
        ...route.params
      }
    })
  } else {
    router.push({
      name: 'floor', params: {
        ...route.params, floor_id: item.key
      }
    })
  }


}

watch(selectedBtn, (newValue) => {
  console.log(newValue);
})

watch(() => route.params.sub_system_id, (newValue, oldValue) => {
  console.log(newValue !== oldValue)
  if (newValue !== oldValue) {
    setItems(items.value.map((item, index) => ({ ...item, active: index === 0 })));
  }

}, {
  deep: true
})

watch(() => store.selectedBuilding, (newValue) => {
  console.log(newValue)
  newValue && getFloors()
}, {
  deep: true,
  immediate: true
})



</script>

<template>
  <div class="flex items-center border border-info px-4 py-2">
    <h5 class="text-md font-extrabold me-4">{{ store.selectedSystem?.full_name }}</h5>
    <ButtonGroup :items="items" :withLine="false" className="btn-xs rounded-md" :onclick="(e, item) => onClick(item)" />
  </div>
</template>

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