<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { useRoute } from 'vue-router';
import { SimpleScrollbar } from '@sa/materials';
import { GLOBAL_SIDER_MENU_ID } from '@/constants/app';
import { useAppStore } from '@/store/modules/app';
import { useThemeStore } from '@/store/modules/theme';
import { useRouteStore } from '@/store/modules/route';
import { useRouterPush } from '@/hooks/common/router';
import { useMenu } from '../context';

defineOptions({
  name: 'VerticalMenu'
});

const route = useRoute();
const appStore = useAppStore();
const themeStore = useThemeStore();
const routeStore = useRouteStore();
const { routerPushByKeyWithMetaQuery } = useRouterPush();
const { selectedKey } = useMenu();

const inverted = computed(() => !themeStore.darkMode && themeStore.sider.inverted);

const expandedKeys = ref<string[]>([]);

function updateExpandedKeys() {
  if (appStore.siderCollapse || !selectedKey.value) {
    expandedKeys.value = [];
    return;
  }
  expandedKeys.value = routeStore.getSelectedMenuKeyPath(selectedKey.value);
}

watch(
  () => route.name,
  () => {
    updateExpandedKeys();
  },
  { immediate: true }
);
</script>

<template>
  <Teleport :to="`#${GLOBAL_SIDER_MENU_ID}`">
    <SimpleScrollbar>
      <NMenu
        v-model:expanded-keys="expandedKeys"
        mode="vertical"
        :value="selectedKey"
        :collapsed="appStore.siderCollapse"
        :collapsed-width="themeStore.sider.collapsedWidth"
        :collapsed-icon-size="22"
        :options="routeStore.menus"
        :inverted="inverted"
        :indent="18"
        @update:value="routerPushByKeyWithMetaQuery"
      />
    </SimpleScrollbar>
  </Teleport>
</template>

<style scoped lang="scss">
:deep(.n-menu) {
  --n-item-text-color: #fff !important;
  --n-item-icon-color: #fff !important;
  --n-item-active-background-color: #2196f3 !important;
  --n-item-border-radius: 6px !important; /* 添加圆角 */
  --n-menu-item-border-radius: 6px !important; /* 确保菜单项有圆角 */
}

:deep(.n-menu:hover) {
  background-color: transparent !important;
}

:deep(.n-base-icon svg) {
  color: white;
}

:deep(.n-submenu-children) {
  background-color: #082c66 !important;
}

/* 确保选中项有圆角和正确的颜色 */
:deep(.n-menu-item.n-menu-item--active) {
  background-color: #2196f3 !important;
  border-radius: 6px !important;
  margin: 0 10px !important;
  width: calc(100% - 20px) !important;
}

/* 确保子菜单项选中时也有相同的样式 */
:deep(.n-submenu-children .n-menu-item.n-menu-item--active) {
  background-color: #2196f3 !important;
  border-radius: 6px !important;
  margin: 0 10px !important;
  width: calc(100% - 20px) !important;
}
</style>
