<template>
  <div class="h-screen bg-gray-100 flex flex-row">
    <!-- 左侧菜单 -->
    <aside class="w-64 bg-white border-r border-gray-200 flex-shrink-0 overflow-y-auto flex flex-col">
      <div class="p-6 border-b border-gray-200">
        <h2 class="text-xl font-bold text-gray-800 flex items-center gap-2">
          <span class="bg-blue-500 w-8 h-8 rounded-lg flex items-center justify-center text-white font-bold shadow-sm">广</span>
          <span>腾讯广告</span>
        </h2>
        <p class="text-xs text-gray-500 mt-1">自动化管理系统</p>
      </div>
      <nav class="flex-1 py-4">
        <el-menu
          :default-active="activeMenu"
          class="border-0"
          :router="true"
        >
          <el-menu-item
            v-for="route in menuRoutes"
            :key="route.path"
            :index="route.path"
            class="menu-item"
          >
            <el-icon>
              <component :is="route.meta.icon" />
            </el-icon>
            <span>{{ route.meta.title }}</span>
          </el-menu-item>
        </el-menu>
      </nav>
    </aside>

    <!-- 右侧内容区 -->
    <main class="flex-1 flex flex-col overflow-hidden">
      <!-- 顶部导航栏 -->
      <header class="bg-white border-b border-gray-200 px-6 py-4 flex-shrink-0 shadow-sm h-16 flex items-center justify-between">
        <h1 class="text-lg font-semibold text-gray-800">{{ currentTitle }}</h1>
        
        <!-- 用户信息区域 -->
        <div class="flex items-center gap-4">
          <!-- 实名认证状态 -->
          <el-tooltip
            :content="isAuthenticated ? '已完成实名认证' : '未完成实名认证'"
            placement="bottom"
          >
            <el-tag
              :type="isAuthenticated ? 'success' : 'warning'"
              size="small"
              class="cursor-pointer"
              @click="goToProfile"
            >
              {{ isAuthenticated ? '已认证' : '未认证' }}
            </el-tag>
          </el-tooltip>

          <!-- 用户下拉菜单 -->
          <el-dropdown @command="handleCommand">
            <div class="flex items-center gap-2 cursor-pointer hover:text-blue-500 transition-colors">
              <el-icon size="20">
                <User />
              </el-icon>
              <span class="text-sm font-medium">{{ userName }}</span>
              <el-icon size="14">
                <ArrowDown />
              </el-icon>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">
                  <el-icon class="mr-2">
                    <User />
                  </el-icon>
                  个人中心
                </el-dropdown-item>
                <el-dropdown-item divided command="logout">
                  <el-icon class="mr-2">
                    <SwitchButton />
                  </el-icon>
                  退出登录
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </header>
      
      <!-- 主内容区 -->
      <div class="flex-1 overflow-y-auto bg-gray-50 p-6">
        <div class="max-w-9xl">
          <router-view v-slot="{ Component, route }">
            <keep-alive :exclude="noCacheComponents">
              <component
                :is="Component"
                :key="route.meta.noCache ? route.fullPath : route.name"
              />
            </keep-alive>
          </router-view>
        </div>
      </div>
    </main>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { User, ArrowDown, SwitchButton } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()

// 用户信息
const userName = ref('')
const userInfo = ref(null)

// 加载用户信息
const loadUserInfo = () => {
  const storedUserInfo = localStorage.getItem('userInfo')
  if (storedUserInfo) {
    userInfo.value = JSON.parse(storedUserInfo)
    userName.value = userInfo.value.name || '未知'
  }
}

// 是否已认证
const isAuthenticated = computed(() => {
  if (!userInfo.value) return false
  if (userInfo.value.userStatus !== 2) return false
  if (!userInfo.value.userToken) return false
  if (!userInfo.value.userTokenExpiresAt) return false
  
  const expiresAt = new Date(userInfo.value.userTokenExpiresAt)
  return expiresAt > new Date()
})

const key = computed(() => {
  return route.fullPath
})

// 从路由配置中获取菜单路由
const menuRoutes = computed(() => {
  const routes = router.getRoutes()
  // 找到根路由（Layout组件）下的所有子路由
  const rootRoute = routes.find(r => r.path === '/')
  if (rootRoute && rootRoute.children) {
    // 过滤出有meta.title且不隐藏的路由作为菜单项
    return rootRoute.children
      .filter(child => child.meta && child.meta.title && !child.meta.hideInMenu)
      .map(child => ({
        path: child.path.startsWith('/') ? child.path : `/${child.path}`,
        meta: child.meta
      }))
  }
  return []
})

// 当前激活的菜单
const activeMenu = computed(() => {
  return route.path
})

// 当前页面标题
const currentTitle = computed(() => {
  return route.meta.title || '腾讯广告自动化管理后台'
})

// 获取不需要缓存的组件名列表
const noCacheComponents = computed(() => {
  const routes = router.getRoutes()
  const noCacheNames = []
  routes.forEach(r => {
    if (r.meta && r.meta.noCache && r.name) {
      noCacheNames.push(r.name)
    }
    if (r.children) {
      r.children.forEach(child => {
        if (child.meta && child.meta.noCache && child.name) {
          noCacheNames.push(child.name)
        }
      })
    }
  })
  return noCacheNames
})

// 跳转到个人中心
const goToProfile = () => {
  router.push('/profile')
}

// 处理下拉菜单命令
const handleCommand = (command) => {
  switch (command) {
    case 'profile':
      router.push('/profile')
      break
    case 'logout':
      handleLogout()
      break
  }
}

// 退出登录
const handleLogout = () => {
  ElMessageBox.confirm(
    '确认退出登录吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 清除本地存储
    localStorage.removeItem('userInfo')
    localStorage.removeItem('jobNumber')
    
    ElMessage.success('已退出登录')
    
    // 跳转到登录页
    router.push('/login')
  }).catch(() => {
    // 取消操作
  })
}

// 页面加载时获取用户信息
onMounted(() => {
  loadUserInfo()
})
</script>

<style scoped>
/* 左侧菜单样式 */
:deep(.el-menu) {
  background-color: transparent;
}

:deep(.el-menu-item) {
  color: #4b5563;
  border-radius: 0.5rem;
  margin: 0 12px 4px 12px;
  padding-left: 20px;
  transition: all 0.2s;
}

:deep(.el-menu-item:hover) {
  background-color: #f3f4f6;
  color: #1f2937;
}

:deep(.el-menu-item.is-active) {
  background-color: #eff6ff;
  color: #2563eb;
  font-weight: 500;
}

:deep(.el-menu-item .el-icon) {
  margin-right: 12px;
  font-size: 18px;
}
</style>
