<script setup>
import { defineProps, ref, watch, computed, onBeforeUnmount } from "vue";
import { useRouter } from "vue-router";
import useNavDataStore from "@/stores/useNavDataStore";
const router = useRouter();
const props = defineProps({
  showSidebar: {
    type: Boolean,
  },
  toggleSidebar: {
    type: Function,
  },
});
const navStore = useNavDataStore();
// const selectedKeys = ref([]); // 用於儲存選中的 menu item
const openKeys = ref([]); // 用於儲存展開的 submenu
const preOpenKeys = ref([]); // 用於儲存之前展開的 submenu

const filteredItems = computed(() => {
  if (navStore.menuList && navStore.menuList.length > 0) {
    return navStore.menuList[0].children;
  }
  return [];
});

const handleClick = (ord) => {
  if (ord) {
    router.push({
      name: "baja",
      query: { ord: encodeURIComponent(ord) },
    });
  }
};

// 監聽 openKeys 的變化
watch(
  () => openKeys.value,
  (_val, oldVal) => {
    preOpenKeys.value = oldVal;
  },
  { deep: true }
);
</script>

<template>
  <a-drawer
    :open="showSidebar"
    @close="toggleSidebar"
    :closable="false"
    placement="left"
    width="300"
    bodyStyle="padding: 0"
  >
    <a-menu mode="inline" theme="light">
      <template v-for="(item, index) in filteredItems" :key="index">
        <a-menu-item
          v-if="!item.children"
          :key="item.key"
          @click="handleClick(item.ord)"
        >
          {{ item.label }}
        </a-menu-item>
        <a-sub-menu v-else :title="item.label" :key="`submenu-${item.key}`">
          <template v-for="child in item.children" :key="child.key">
            <a-menu-item
              v-if="!child.children"
              :key="child.key"
              @click="handleClick(child.ord)"
            >
              {{ child.label }}
            </a-menu-item>
            <a-sub-menu
              v-else
              :title="child.label"
              :key="`submenu-item-${child.key}`"
            >
              <a-menu-item
                v-for="kid in child.children"
                :key="kid.key"
                @click="handleClick(kid.ord)"
              >
                {{ kid.label }}
              </a-menu-item>
            </a-sub-menu>
          </template>
        </a-sub-menu>
      </template>
    </a-menu>
  </a-drawer>
</template>
