<script setup>
import {ref, onMounted, watch, onUnmounted} from 'vue'
import {useNavStore} from '@/store/nav'
import {storeToRefs} from 'pinia'

// Store 相关
const navStore = useNavStore()
const {navIndex} = storeToRefs(navStore)

// 响应式数据
const navList = ref([])
const activeIndex = ref('/')

// 处理导航选择
const handleSelect = (key) => {
  navStore.changeNavIndex(key)
}

// 监听 store 中的 navIndex 变化
const stopWatch = watch(
  navIndex,
  (newValue) => {
    activeIndex.value = newValue
  },
  {
    immediate: true,
  }
)

// 生命周期
onMounted(() => {
  navList.value = window.nav.header || []
})

onUnmounted(() => {
  stopWatch()
})
</script>

<template>
  <div class="page">
    <el-menu
      :default-active="activeIndex"
      class="el-menu-demo"
      mode="horizontal"
      @select="handleSelect"
      active-text-color="#FFFFFF"
      text-color="#999999"
      background-color="$bg_color"
      router
    >
      <template v-for="nav in navList" :key="nav.id">
        <!-- 有子菜单的情况 -->
        <el-sub-menu
          v-if="nav.hasChildren || nav?.children?.length > 0"
          :index="nav.url"
          popper-class="pepper"
        >
          <template #title>
            <span>{{ nav.label }}</span>
          </template>
          <el-menu-item
            v-for="child in nav.children"
            :key="child.id"
            :index="child.url"
          >
            {{ child.label }}
          </el-menu-item>
        </el-sub-menu>

        <!-- 无子菜单的情况 -->
        <el-menu-item
          v-else
          :index="nav.url"
          :class="{'is-active': activeIndex === nav.url}"
        >
          {{ nav.label }}
        </el-menu-item>
      </template>
    </el-menu>
  </div>
</template>

<style lang="scss" scoped>
/* 菜单容器样式 */
.el-menu--horizontal {
  --el-menu-horizontal-height: 81px;
}

::v-deep(.el-sub-menu__title) {
  font-size: $nav_font_size !important;
  font-family: 'PingFang SC' !important;
  font-weight: 400 !important;
  padding: 0px 25px !important;
  box-sizing: border-box !important;
  text-align: center !important;

  i {
    display: none !important;
  }
}

/* 菜单项基础样式 */
.el-menu-item {
  padding: 0 25px;
  font-family: 'PingFang SC';
  font-weight: 400;
  font-size: $nav_font_size !important;
  line-height: 100%;
  letter-spacing: 0.06em;
  border-bottom: none !important;
  transition: border-bottom 0.3s ease;

  /* 激活状态样式 */
  &.is-active {
    border-bottom: 2px solid #ffffff !important;
  }

  /* 悬停效果 */
  &:hover {
    background-color: rgba(255, 255, 255, 0.1) !important;
  }
}

.pepper {
  background-color: #ffffff;
  .el-menu-item {
    width: 246px !important;
    height: 50px !important;
    line-height: 50px !important;
    box-sizing: border-box !important;
    font-size: 14px !important;
    color: $black !important;
    padding: 5px 0 !important;
    padding-left: 20px !important;
    &:hover {
      background-color: #f4f4f4 !important;
    }
  }
}
</style>
