<template>
  <el-aside class="app-sidebar" :class="sidebarClasses" :width="sidebarWidth">
    <!-- 移动端遮罩层 -->
    <div
      v-if="appStore.isMobile && appStore.mobileSidebarOpen"
      class="mobile-overlay"
      @click="appStore.closeMobileSidebar"
    ></div>

    <div class="sidebar-container">
      <el-menu
        :default-active="$route.path"
        :openeds="openeds"
        :collapse="appStore.sidebarCollapsed && !appStore.isMobile"
        class="sidebar-menu"
        :class="themeClass"
        router
        @select="handleMenuSelect"
      >
        <template v-for="group in menuItems" :key="group.group">
          <el-sub-menu :index="group.group">
            <template #title>
              <el-icon class="menu-icon">
                <component :is="group.icon" />
              </el-icon>
              <span class="menu-title">{{ group.group }}</span>
            </template>
            <el-menu-item
              v-for="item in group.children"
              :key="item.path"
              :index="item.path"
              class="menu-item"
            >
              <el-icon class="menu-icon">
                <component :is="item.icon" />
              </el-icon>
              <template #title>
                <span class="menu-title">{{ item.name }}</span>
              </template>
            </el-menu-item>
          </el-sub-menu>
        </template>
      </el-menu>
      <!-- 返回官网链接 -->
      <div class="home-link-container">
        <a
          href="https://www.haiyudata.com/"
          target="_blank"
          rel="noopener"
          class="home-link"
          @click="handleMenuSelect"
        >
          <el-icon class="menu-icon">
            <HomeIcon />
          </el-icon>
          <span class="menu-title">返回官网</span>
        </a>
      </div>
    </div>
  </el-aside>
</template>

<script setup>
import { useAppStore } from '@/stores/app'
import { useUserStore } from '@/stores/user'
import { HomeIcon } from '@heroicons/vue/24/outline'
import { onMounted, onUnmounted, watch } from 'vue'
import { useRouter } from 'vue-router'

const props = defineProps({
  menuItems: {
    type: Array,
    required: true,
  },
  theme: {
    type: String,
    default: 'user', // 'user' | 'admin'
    validator: (value) => ['user', 'admin'].includes(value),
  },
})

const appStore = useAppStore()
const userStore = useUserStore()
const router = useRouter()
let bodyLockClassApplied = false

// 使用ref来控制菜单展开状态
const openeds = ref([])

// 根据用户类型和当前路由动态设置菜单展开状态
const updateOpeneds = () => {
  const openedGroups = []
  const currentPath = router.currentRoute.value.path

  props.menuItems.forEach((item) => {
    if (item.group === '管理后台') {
      // 只有管理员用户才默认展开管理后台菜单
      // 或者当前正在访问管理后台页面时也展开
      if (userStore.isAdmin || currentPath.startsWith('/admin/')) {
        openedGroups.push(item.group)
      }
    } else {
      // 其他菜单组默认展开
      openedGroups.push(item.group)
    }
  })

  openeds.value = openedGroups
}

// 监听路由变化和用户状态变化
watch(
  [() => router.currentRoute.value.path, () => userStore.isAdmin],
  () => {
    updateOpeneds()
  },
  { immediate: true },
)

// 计算侧边栏宽度
const sidebarWidth = computed(() => {
  if (appStore.isMobile) {
    return '240px'
  }
  return appStore.sidebarCollapsed ? '64px' : '240px'
})

// 主题样式类
const themeClass = computed(() => {
  return props.theme === 'admin' ? 'admin-theme' : 'user-theme'
})

// 侧边栏样式类
const sidebarClasses = computed(() => {
  const classes = []
  if (appStore.isMobile) {
    classes.push('mobile-sidebar')
    if (appStore.mobileSidebarOpen) {
      classes.push('sidebar-open')
    }
  }
  return classes
})

// 处理菜单选择
const handleMenuSelect = () => {
  // 移动端选择菜单项后自动关闭侧边栏
  if (appStore.isMobile) {
    appStore.closeMobileSidebar()
  }
}

// 当移动端侧边栏打开时，锁定页面点击与滚动，确保其他区域点击无效
const toggleBodyLock = (locked) => {
  const body = document.body
  if (locked) {
    if (!bodyLockClassApplied) {
      body.classList.add('sidebar-locked')
      bodyLockClassApplied = true
    }
  } else if (bodyLockClassApplied) {
    body.classList.remove('sidebar-locked')
    bodyLockClassApplied = false
  }
}

onMounted(() => {
  toggleBodyLock(appStore.isMobile && appStore.mobileSidebarOpen)
})

onUnmounted(() => {
  toggleBodyLock(false)
})

watch(
  () => [appStore.isMobile, appStore.mobileSidebarOpen],
  ([isMobile, open]) => {
    toggleBodyLock(isMobile && open)
  },
  { immediate: true },
)
</script>

<style scoped>
.app-sidebar {
  background: #fff;
  transition: width 0.3s ease;
  overflow: hidden;
  position: relative;
  height: 100%;
}

.sidebar-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
  width: 100%;
  z-index: 1001;
}

.sidebar-menu {
  border: none;
  height: 100%;
  flex: 1 1 0%;
  overflow-y: auto;
  overflow-x: hidden;
  width: 100%;
}

/* 返回官网链接样式 */
.home-link-container {
  padding: 8px;
  border-top: 1px solid rgba(226, 232, 240, 0.6);
  margin-top: auto;
  flex-shrink: 0;
}

.home-link {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  height: 50px;
  line-height: 50px;
  margin: 4px 8px;
  transition:
    background-color 0.3s ease,
    color 0.3s ease;
  border: 2px solid transparent;
  border-radius: 48px;
  text-decoration: none;
  color: #1e293b;
  cursor: pointer;
}

.home-link:hover {
  background-color: #f5f7fa;
  color: #409eff;
}

.home-link .menu-icon {
  font-size: 18px;
  margin-right: 12px;
  width: 20px;
  height: 20px;
}

.home-link .menu-title {
  font-size: 14px;
  font-weight: 500;
}

.menu-item {
  height: 50px;
  line-height: 50px;
  margin: 4px 8px;
  transition:
    background-color 0.3s ease,
    color 0.3s ease;
  border: 2px solid transparent;
  border-radius: 48px;
}

.menu-item:hover {
  background-color: #f5f7fa;
}

.menu-item.is-active {
  background-color: #ecf5ff;
  color: #409eff;
}

.menu-icon {
  font-size: 18px;
  margin-right: 12px;
  width: 20px;
  height: 20px;
}

.menu-title {
  font-size: 14px;
  font-weight: 500;
}

/* 用户主题样式 */
.menu-item.is-active {
  background-color: #ecf5ff !important;
  color: #409eff;
}

.menu-item:hover {
  background-color: #f0f9ff !important;
}

/* 折叠状态样式 */
.el-menu--collapse .menu-item {
  margin: 4px 4px;
}

.el-menu--collapse .menu-icon {
  margin-right: 0;
}

/* 折叠状态下的返回官网链接 */
.el-menu--collapse ~ .home-link-container .home-link {
  justify-content: center;
  padding: 12px;
  margin: 4px 4px;
}

.el-menu--collapse ~ .home-link-container .home-link .menu-icon {
  margin-right: 0;
}

.el-menu--collapse ~ .home-link-container .home-link .menu-title {
  display: none;
}

/* 移动端样式 */
.mobile-sidebar {
  position: fixed;
  top: 60px;
  left: 0;
  z-index: 1000;
  height: calc(100vh - 60px);
  transform: translateX(-100%);
  transition: transform 0.3s ease;
  overflow-y: auto;
  overflow-x: hidden;
}

.mobile-sidebar.sidebar-open {
  transform: translateX(0);
}

.mobile-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.65); /* 保持浅色，不要黑色遮罩 */
  backdrop-filter: blur(2px);
  z-index: 999;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .sidebar-menu {
    width: 100%;
  }
}

@media (max-width: 480px) {
  .sidebar-menu {
    width: 100%;
  }

  .menu-item {
    height: 44px;
    line-height: 44px;
    margin: 2px 4px;
  }

  .menu-icon {
    font-size: 16px;
    margin-right: 8px;
  }

  .menu-title {
    font-size: 13px;
  }

  .home-link {
    height: 44px;
    line-height: 44px;
    margin: 2px 4px;
    padding: 10px 12px;
  }

  .home-link .menu-icon {
    font-size: 16px;
    margin-right: 8px;
  }

  .home-link .menu-title {
    font-size: 13px;
  }
}

:global(body.sidebar-locked) {
  overflow: hidden;
}

:global(body.sidebar-locked #app) {
  pointer-events: none;
}

:global(body.sidebar-locked .app-sidebar) {
  pointer-events: auto;
}

/* Element Plus 菜单样式覆盖 */
:deep(.el-menu) {
  background-color: transparent;
}

:deep(.el-menu-item) {
  background-color: transparent;
}

:deep(.el-menu-item:hover) {
  background-color: transparent;
}

:deep(.el-menu-item.is-active) {
  background-color: transparent;
}

:deep(.el-menu--collapse .el-menu-item) {
  padding: 0 20px;
}

:deep(.el-menu--collapse .el-menu-item .el-icon) {
  margin: 0;
}
</style>
