<script setup>
import { useRoute, useRouter } from "vue-router";
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 onClick = (item) => {
  changeActiveBtn(item);

  router.push({
    name: "sub_system",
    params: {
      ...route.params,
      floor_id: item.key,
    },
    query: {
      ...route.query,
      gas: route.query.gas,
      mode: item.key === "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.floorList,
  (newValue) => {
    if (newValue) {
      console.log('newValue',newValue);
      
      const floorList = [
        {
          title: "All",
          key: "main",
          active: route.params.floor_id === "main",
        },
        ...store.floorList.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 ? d.floor_map_url + ".svg" : null,
        })),
      ];
      setItems(floorList);
      updateCurrentFloor(floorList);
    }
  },
  {
    deep: true,
    immediate: true,
  }
);
</script>

<template>
  <div class="flex flex-wrap items-center gap-3">
    <span class="text-md font-extrabold">{{ $t("energy.floor") }} :</span>
    <ButtonGroup
      :items="items"
      :withLine="true"
      className="btn-xs rounded-md"
      :onclick="(e, item) => onClick(item)"
    />
  </div>
</template>

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