<template>
  <!-- 主布局组件 -->
  <div class="h-screen flex flex-col relative overflow-hidden">
    <!-- 顶栏 - 悬浮在最上层，显示系统标题和用户信息 -->
    <header class="h-16 bg-[rgba(20,60,110,0.85)] backdrop-blur-sm shadow-lg flex items-center justify-between px-6 z-30">
      <div class="flex items-center">
        <el-icon class="text-cyan-300 mr-2"><Database /></el-icon>
        <h1 class="text-xl font-semibold text-white">仓库管理系统</h1>
      </div>
      
      <div class="flex items-center space-x-4">
        <el-dropdown placement="bottom-end">
          <div class="flex items-center cursor-pointer">
            <el-avatar :size="32" class="mr-2" style="background-color: rgba(104, 201, 255, 0.3); border: 1px solid #68c9ff;">
              {{ userInfo?.name?.charAt(0) || '用' }}
            </el-avatar>
            <span class="text-white">{{ userInfo?.name || '管理员' }}</span>
            <el-icon class="ml-1 text-cyan-300" name="ArrowDown" />
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="handleLogout">
                <el-icon name="Logout" class="text-cyan-300" />
                <span>退出登录</span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <!-- 全屏按钮 -->
        <el-button 
          icon="FullScreen" 
          @click="toggleFullScreen" 
          circle 
          title="切换全屏"
          :icon="isFullScreen ? 'CloseFullScreen' : 'FullScreen'"
          style="background-color: rgba(104, 201, 255, 0.3); color: #68c9ff; border: 1px solid #68c9ff;"
        />
      </div>
    </header>
    
    <!-- 3D地图容器 - 最底层，全屏显示，用于展示仓库的3D地图视图 -->
    <div class="fixed inset-0 z-0">
      <router-view name="map" />
    </div>
    
    <!-- 侧边栏容器 - 固定定位，不占用主内容空间，用于显示系统功能菜单 -->
    <div class="fixed left-0 top-16 h-[calc(100%-4rem)] z-20">
      <!-- 左侧菜单栏 - 可折叠，显示多级菜单 -->
      <aside class="bg-gradient-to-r from-[rgba(20,60,110,1)] to-[rgba(20,60,110,0.5)] backdrop-blur-sm border-r border-[#68c9ff] overflow-y-auto transition-all duration-300 ease-in-out h-full"
             :style="{ width: isCollapsed ? '64px' : '250px' }">
        <!-- 菜单内容 -->
        <el-menu
          active-text-color="#68c9ff"
          background-color="transparent"
          text-color="#b6dfff"
          class="h-full pt-4"
          :default-active="activeMenu"
          mode="vertical"
          :collapse-transition="false"
          v-if="menuList && menuList.length > 0"
          unique-opened="true"
        >
          <!-- 二级菜单结构 - 动态渲染菜单列表 -->
        <template v-for="menu in menuList" :key="menu.id">
            <!-- 有子菜单的一级菜单 -->
          <el-sub-menu 
            v-if="menu.children && menu.children.length > 0" 
            :index="menu.id"
            :popper-append-to-body="true"
            :popper-offset="[0, 0]"
            popper-class="sub-menu-popover"
            :title="isCollapsed ? menu.name : ''"
            @click="handleSubMenuClick"
          >
            <template #title>
              <el-icon class="text-xl menu-icon"
                :style="isCollapsed ? 'color: #91d5ff;' : 'color: #68c9ff;'"
              >
                <component :is="menu.icon" />
              </el-icon>
              <span v-if="!isCollapsed" class="transition-opacity duration-300">
                {{ menu.name }}
              </span>
            </template>
            <!-- 二级菜单项 -->
            <el-menu-item
              v-for="subMenu in menu.children"
              :key="subMenu.id"
              :index="subMenu.path"
              @click="handleMenuClick(subMenu)"
              class="whitespace-nowrap"
            >
              <span>{{ subMenu.name }}</span>
            </el-menu-item>
          </el-sub-menu>
          <!-- 没有子菜单的菜单项 -->
          <el-menu-item
            v-else
            :index="menu.path"
            @click="handleMenuClick(menu)"
            :class="{ 'px-0 justify-center': isCollapsed, 'px-4 justify-start': !isCollapsed }"
          >
            <el-icon class="text-xl" 
              :class="isCollapsed ? 'mr-0' : 'mr-3'"
              :style="isCollapsed ? 'color: #91d5ff;' : 'color: #68c9ff;'"
            >
              <component :is="menu.icon" />
            </el-icon>
            <span v-if="!isCollapsed" class="transition-opacity duration-300">
              {{ menu.name }}
            </span>
          </el-menu-item>
          </template>
        </el-menu>
      </aside>
    </div>
    
    <!-- 折叠按钮 - 固定定位，不占用主内容空间，用于切换侧边栏折叠状态 -->
      <div class="fixed left-[250px] top-1/2 -translate-y-1/2 z-30 transition-all duration-300 ease-in-out"
         :style="{ left: isCollapsed ? '64px' : '250px' }">
      <el-button 
        @click="toggleCollapse" 
        size="default" 
        :icon="isCollapsed ? 'ArrowRight' : 'ArrowLeft'"
        style="background-color: rgba(104, 201, 255, 0.3); color: #68c9ff; border: 1px solid #68c9ff; border-radius: 0 4px 4px 0; width: 10px; height: 64px; display: flex; align-items: center; justify-content: center; padding: 0;"
      />
    </div>

    <!-- Drawer组件 - 从右侧滑出，用于显示具体功能页面内容 -->
    <el-drawer
      v-model="drawerVisible"
      :title="currentMenu?.name || '页面内容'"
      size="800px"
      direction="rtl"
      :with-header="true"
      close-on-click-modal="false"
      close-on-press-escape="true"
      header-class="drawer-header-class"
    >
      <div class="h-full overflow-y-auto">
        <router-view name="right" />
      </div>
    </el-drawer>
  </div>
</template>

<script setup>
/**
 * 主布局组件脚本部分
 * 使用组合式API实现布局功能和交互逻辑
 * 管理侧边栏折叠状态、菜单导航和用户认证
 */
import { ref, onMounted, computed, onUnmounted } from 'vue' // 导入Vue组合式API
import { useRouter } from 'vue-router' // 导入路由相关函数
import { useUserStore } from '@/stores/user' // 导入用户状态管理
import { ElMessage, ElDrawer } from 'element-plus' // 导入Element Plus组件

const router = useRouter() // 路由实例
const userStore = useUserStore() // 用户状态管理
const activeMenu = computed(() => router.currentRoute.value.path) // 当前激活的菜单路径

// 侧边栏折叠状态
const isCollapsed = ref(false) // 侧边栏是否折叠

// Drawer相关状态
const drawerVisible = ref(false) // Drawer是否可见
const currentMenu = ref(null) // 当前选中的菜单项

// 模拟菜单数据，实际应用中应从userStore获取
const menuList = ref([
  { 
    id: '1', 
    name: '首页', 
    path: '/', 
    icon: 'House' 
  },
  { id: '2', 
    name: '钥匙管理', 
    icon: 'Key',
    children: [
      { id: '2-1', name: '钥匙信息管理', path: '/Key/KeyManager' },
      { id: '2-2', name: '钥匙使用申请', path: '/warehouse/add' },
      { id: '2-3', name: '钥匙取用记录', path: '/warehouse/stats' }
    ]
  },
  { id: '3', 
    name: '巡检管理', 
    icon: 'View',
    children: [
      { id: '3-1', name: '巡检路径管理', path: '/inventory/overview' },
      { id: '3-2', name: '巡检排班管理', path: '/inventory/detail' },
      { id: '3-3', name: '巡检记录', path: '/inventory/alerts' }
    ]
  },
  { id: '4', 
    name: '车辆管理', 
    icon: 'Van',
    children: [
      { id: '4-1', name: '车辆信息管理', path: '/inventory/overview' },
      { id: '4-2', name: '车辆使用申请', path: '/inventory/detail' },
      { id: '4-3', name: '车辆出入库记录', path: '/inventory/alerts' },
      { id: '4-4', name: '车辆出入营区记录', path: '/inventory/alerts' }
    ]
  },
  { id: '5', 
    name: '环境监控', 
    icon: 'Odometer',
    children: [
      { id: '5-1', name: '环境变量管理', path: '/inventory/overview' }
    ]
  },
  { id: '6', 
    name: '信息管理', 
    icon: 'Document',
    children: [
      { id: '6-1', name: '特情处置预案', path: '/inventory/overview' },
      { id: '6-2', name: '安全提示', path: '/inventory/detail' }
    ]
  },
  { id: '7', 
    name: '访客管理', 
    icon: 'User',
    children: [
      { id: '7-1', name: '来访人员管理', path: '/inventory/overview' },
      { id: '7-2', name: '来访车辆管理', path: '/inventory/detail' }
    ]
  },
  { id: '8', 
    name: '营区管理', 
    icon: 'MapLocation',
    children: [
      { id: '8-1', name: '岗位职责', path: '/inventory/overview' },
      { id: '8-2', name: '人员区域管理', path: '/inventory/detail' }
    ]
  },
  { id: '9', 
    name: '无人机管理', 
    icon: 'Promotion',
    children: [
      { id: '9-1', name: '无人机管理', path: '/inventory/overview' }
    ]
  }
])

/**
 * 用户信息响应式数据
 * 用于显示当前登录用户的信息
 */
const userInfo = ref({
  name: '管理员' // 默认用户名称
})

/**
 * 全屏状态响应式数据
 * 用于跟踪应用的全屏状态
 */
const isFullScreen = ref(false)

/**
 * 切换侧边栏折叠状态
 * 控制侧边栏的展开和收起
 */
const toggleCollapse = () => {
  isCollapsed.value = !isCollapsed.value
}

/**
 * 处理一级菜单点击事件
 * 在折叠状态下点击一级菜单时自动展开侧边栏
 */
const handleSubMenuClick = () => {
  if (isCollapsed.value) {
    toggleCollapse()
  }
}

/**
 * 处理菜单项点击事件
 * @param {Object} menu - 菜单对象，包含路径和名称等信息
 */
const handleMenuClick = (menu) => {
  currentMenu.value = menu // 保存当前选中的菜单项
  drawerVisible.value = true // 显示右侧抽屉
  
  // 首页菜单特殊处理：不显示抽屉，直接路由跳转
  if (menu.path === '/') {
    drawerVisible.value = false
  }
  
  router.push(menu.path) // 跳转到对应路由
}

/**
 * 处理用户退出登录
 * 清除用户状态并跳转到登录页面
 */
const handleLogout = () => {
  userStore.logout() // 调用用户store的logout方法，清除用户状态
  ElMessage.success('退出登录成功') // 显示成功提示信息
  router.push('/login') // 跳转到登录页面
}

/**
 * 切换全屏功能
 * 控制应用在全屏和非全屏状态之间切换
 */
const toggleFullScreen = () => {
  // 如果当前是全屏状态，则退出全屏
  if (isFullScreen.value) {
    if (document.exitFullscreen) {
      document.exitFullscreen()
    } else if (document.mozCancelFullScreen) {
      document.mozCancelFullScreen()
    } else if (document.webkitExitFullscreen) {
      document.webkitExitFullscreen()
    } else if (document.msExitFullscreen) {
      document.msExitFullscreen()
    }
  } 
  // 如果当前是非全屏状态，则进入全屏
  else {
    const docEl = document.documentElement
    if (docEl.requestFullscreen) {
      docEl.requestFullscreen()
    } else if (docEl.mozRequestFullScreen) {
      docEl.mozRequestFullScreen()
    } else if (docEl.webkitRequestFullscreen) {
      docEl.webkitRequestFullscreen()
    } else if (docEl.msRequestFullscreen) {
      docEl.msRequestFullscreen()
    }
  }
}

/**
 * 处理全屏变化事件
 * 更新isFullScreen状态
 */
const handleFullScreenChange = () => {
  isFullScreen.value = !!(document.fullscreenElement || 
    document.mozFullScreenElement || 
    document.webkitFullscreenElement || 
    document.msFullscreenElement)
}

/**
 * 组件生命周期钩子：挂载时执行
 * 初始化用户信息、菜单列表并添加全屏事件监听
 */
onMounted(() => {
  // 初始化用户信息
  userStore.initUserInfo().then(() => {
    // 更新用户信息
    if (userStore.userInfo) {
      userInfo.value = userStore.userInfo
    }
    
    // 安全检查：确保userStore.menuList存在并有值
    if (userStore.menuList && userStore.menuList.length > 0) {
      menuList.value = userStore.menuList // 更新菜单列表
    }
  })
  
  // 添加全屏变化事件监听
  document.addEventListener('fullscreenchange', handleFullScreenChange)
  document.addEventListener('webkitfullscreenchange', handleFullScreenChange)
  document.addEventListener('mozfullscreenchange', handleFullScreenChange)
  document.addEventListener('MSFullscreenChange', handleFullScreenChange)
})

/**
 * 组件生命周期钩子：卸载时执行
 * 移除全屏事件监听
 */
onUnmounted(() => {
  // 移除全屏变化事件监听
  document.removeEventListener('fullscreenchange', handleFullScreenChange)
  document.removeEventListener('webkitfullscreenchange', handleFullScreenChange)
  document.removeEventListener('mozfullscreenchange', handleFullScreenChange)
  document.removeEventListener('MSFullscreenChange', handleFullScreenChange)
})
</script>

<style scoped>
/**
 * 布局组件样式定义
 * 包含菜单、顶栏、Drawer等自定义样式
 */
/* 布局样式 */
.el-menu {
  border-right: none;
}

/* 隐藏折叠状态下的一级菜单箭头 */
:deep(.collapse .el-sub-menu__icon-arrow) {
  display: none !important;
}

/* 空军蓝背景 - 用户下拉菜单样式 */
:deep(.el-dropdown-menu) {
  background-color: rgba(12, 43, 77, 0.95) !important;
  border: 1px solid #68c9ff !important;
  box-shadow: 0 4px 20px rgba(104, 201, 255, 0.2) !important;
}

:deep(.el-dropdown-item) {
  color: #b6dfff !important;
}

:deep(.el-dropdown-item:hover) {
  background-color: rgba(104, 201, 255, 0.2) !important;
}

:deep(.el-menu-item.is-active) {
  background-color: rgba(104, 201, 255, 0.2) !important;
  color: #68c9ff !important;
}

:deep(.el-menu-item:hover) {
  background-color: rgba(104, 201, 255, 0.1) !important;
  color: #68c9ff !important;
}

/* 二级菜单弹出样式 - 在侧边栏外部显示 */
:deep(.sub-menu-popover) {
  position: fixed !important;
  left: 64px !important;
  background-color: rgba(12, 43, 77, 0.95) !important;
  border: 1px solid #68c9ff !important;
  box-shadow: 0 4px 20px rgba(104, 201, 255, 0.2) !important;
  z-index: 40 !important;
}

/* 确保二级菜单不会被隐藏 */
:deep(.el-sub-menu__popper) {
  max-width: none !important;
  width: auto !important;
}

/* Drawer自定义样式 - 统一与左侧边栏配色方案 */
/* 简化并统一所有Drawer样式，使用单一的drawer-custom-class */
:deep(.el-drawer){
  top:4rem;
  background: linear-gradient(to left, rgba(12, 43, 77, 0.95), rgba(12, 43, 77, 0.7)) !important;
  backdrop-filter: blur(5px) !important;
  box-shadow: -5px 0 25px rgba(104, 201, 255, 0.3) !important;
  border-left: 1px solid #68c9ff !important;
  color: #b6dfff !important;
}

:deep(.drawer-header-class){
  color:#b6dfff !important;
}

/* 修复折叠状态下的二级菜单位置 */
:deep(.is-collapsed .el-sub-menu__popper) {
  left: 64px !important;
  margin-left: 0 !important;
}
</style>