<script setup>
import { useRoute, useRouter } from 'vue-router';
import { getAssetFloorList } from "@/apis/asset";
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 getAssetFloorList()
  let data = res.data.find(d => d.building_tag === store.selectedBuilding?.building_tag)
  data = [
    {
      title: "All",
      key: "main",
      active: route.params.floor_id === "main",
    },
    ...data.floors.map((d, idx) => ({
      title: d.full_name,
      key: d.floor_guid,
      active: route.params.floor_id === d.floor_guid,
      map_url: d.floor_map_url + ".svg"
    }))
  ]
  setItems(data);

  updateCurrentFloor(data)
}

const onClick = (item) => {
  changeActiveBtn(item)

  router.push({
    name: 'sub_system', params: {
      ...route.params, floor_id: item.key
    }, query: { ...route.query, gas: route.query.gas, mode: route.params.floor_id === "main" ? "3D" : route.query.mode }
  })

}

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

}, {
  deep: true
})

watch(() => store.selectedBuilding, (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>