<template>
  <el-container class="layout-container">
    <el-aside :width="collapsed ? '64px' : '200px'" class="sidebar desktop-only">
      <div class="logo">
        <h2 v-if="!collapsed">运动会记分板</h2>
        <el-icon v-else :size="24"><Trophy /></el-icon>
      </div>
      <div class="sidebar-toggle">
        <el-button text @click="toggleCollapse" size="small">
          <el-icon>
            <ArrowLeft v-if="!collapsed" />
            <ArrowRight v-else />
          </el-icon>
        </el-button>
      </div>
      <el-menu
        :default-active="activeMenu"
        class="sidebar-menu"
        :collapse="collapsed"
        :collapse-transition="false"
      >
        <el-menu-item
          v-for="item in menuItems"
          :key="item.path"
          :index="item.path"
          @click="onMenuClick(item.path)"
        >
          <el-icon><component :is="item.icon" /></el-icon>
          <span>{{ item.label }}</span>
        </el-menu-item>

        <el-sub-menu v-if="hasAdminMenu" index="admin">
          <template #title>
            <el-icon><Setting /></el-icon>
            <span>系统管理</span>
          </template>
          <el-menu-item index="/admin/users" @click="onMenuClick('/admin/users')">
            <el-icon><UserFilled /></el-icon>
            <span>用户管理</span>
          </el-menu-item>
          <el-menu-item index="/admin/oauth" @click="onMenuClick('/admin/oauth')">
            <el-icon><Key /></el-icon>
            <span>OAuth 客户端</span>
          </el-menu-item>
        </el-sub-menu>
      </el-menu>
    </el-aside>
    <el-container>
      <el-header class="header">
        <div class="header-left">
          <el-button class="mobile-only-btn" text @click="drawerOpen = true">
            <el-icon><Menu /></el-icon>
          </el-button>
          <h3>运动会管理系统</h3>
        </div>
        <div class="header-right">
          <el-dropdown v-if="currentUser" @command="handleUserCommand">
            <span class="user-info">
              <el-avatar :size="32">
                <el-icon><UserFilled /></el-icon>
              </el-avatar>
              <span class="username">{{ currentUser.username }}</span>
              <el-icon><ArrowDown /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">个人资料</el-dropdown-item>
                <el-dropdown-item command="logout" divided>退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <el-button v-else type="primary" @click="showLoginDialog = true">登录</el-button>
        </div>
      </el-header>
      <el-main class="main-content">
        <slot />
      </el-main>
      <el-footer class="footer">
        <p>© 2026 运动会记分板系统 - 版权所有</p>
      </el-footer>
    </el-container>
  </el-container>

  <el-drawer
    v-model="drawerOpen"
    direction="ltr"
    size="70%"
    :with-header="false"
    class="mobile-only"
  >
    <div class="drawer-logo">
      <h2>运动会记分板</h2>
    </div>
    <el-menu
      :default-active="activeMenu"
      class="drawer-menu"
    >
      <el-menu-item
        v-for="item in menuItems"
        :key="item.path"
        :index="item.path"
        @click="onMenuClick(item.path, true)"
      >
        <el-icon><component :is="item.icon" /></el-icon>
        <span>{{ item.label }}</span>
      </el-menu-item>

      <el-sub-menu v-if="hasAdminMenu" index="admin">
        <template #title>
          <el-icon><Setting /></el-icon>
          <span>系统管理</span>
        </template>
        <el-menu-item index="/admin/users" @click="onMenuClick('/admin/users', true)">
          <el-icon><UserFilled /></el-icon>
          <span>用户管理</span>
        </el-menu-item>
        <el-menu-item index="/admin/oauth" @click="onMenuClick('/admin/oauth', true)">
          <el-icon><Key /></el-icon>
          <span>OAuth 客户端</span>
        </el-menu-item>
      </el-sub-menu>
    </el-menu>
  </el-drawer>

  <el-dialog v-model="showLoginDialog" title="登录" width="400px">
    <el-form :model="loginForm" :rules="loginRules" ref="loginFormRef">
      <el-form-item prop="username">
        <el-input 
          v-model="loginForm.username" 
          placeholder="用户名"
          prefix-icon="User"
        />
      </el-form-item>
      <el-form-item prop="password">
        <el-input 
          v-model="loginForm.password" 
          type="password" 
          placeholder="密码"
          prefix-icon="Lock"
          show-password
          @keyup.enter="handleLogin"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="showLoginDialog = false">取消</el-button>
      <el-button type="primary" @click="handleLogin" :loading="logging">登录</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { HomeFilled, Trophy, UserFilled, Edit, DataLine, Menu, Setting, Key, ArrowLeft, ArrowRight, ArrowDown } from '@element-plus/icons-vue'

const route = useRoute()
const activeMenu = computed(() => route.path)
const drawerOpen = ref(false)
const showLoginDialog = ref(false)
const logging = ref(false)
const loginFormRef = ref()

const collapsed = ref(false)
const currentUser = ref<any>(null)
const hasAdminMenu = computed(() => currentUser.value?.role === 'admin')

const loginForm = ref({
  username: '',
  password: ''
})

const loginRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

const menuItems = [
  { path: '/', label: '首页', icon: HomeFilled },
  { path: '/events', label: '比赛项目', icon: Trophy },
  { path: '/teams', label: '队伍管理', icon: UserFilled },
  { path: '/results', label: '成绩录入', icon: Edit },
  { path: '/scoreboard', label: '记分板', icon: DataLine }
]

const toggleCollapse = () => {
  collapsed.value = !collapsed.value
  localStorage.setItem('sidebar-collapsed', String(collapsed.value))
}

const onMenuClick = (path: string, closeDrawer = false) => {
  navigateTo(path)
  if (closeDrawer) {
    drawerOpen.value = false
  }
}

const handleUserCommand = async (command: string) => {
  if (command === 'logout') {
    localStorage.removeItem('token')
    localStorage.removeItem('refreshToken')
    localStorage.removeItem('user')
    currentUser.value = null
    ElMessage.success('已退出登录')
  }
}

const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  await loginFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    
    logging.value = true
    try {
      const res = await $fetch('/api/auth/login', {
        method: 'POST',
        body: loginForm.value
      })
      
      if (res.success) {
        localStorage.setItem('token', res.data.accessToken)
        localStorage.setItem('refreshToken', res.data.refreshToken)
        localStorage.setItem('user', JSON.stringify(res.data.user))
        currentUser.value = res.data.user
        showLoginDialog.value = false
        loginForm.value = { username: '', password: '' }
        ElMessage.success('登录成功')
      }
    } catch (error: any) {
      ElMessage.error(error.data?.message || '登录失败')
    } finally {
      logging.value = false
    }
  })
}

onMounted(() => {
  const savedCollapsed = localStorage.getItem('sidebar-collapsed')
  if (savedCollapsed !== null) {
    collapsed.value = savedCollapsed === 'true'
  }

  const savedUser = localStorage.getItem('user')
  if (savedUser) {
    currentUser.value = JSON.parse(savedUser)
  }
})
</script>

<style scoped>
.layout-container {
  height: 100vh;
  overflow: hidden;
}

.el-main {
  overflow-y: auto;
}

.sidebar {
  background-color: #304156;
  color: #fff;
  transition: width 0.3s;
  overflow: hidden;
  height: 100%;
}

.logo {
  height: 56px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #2b3a4a;
}

.logo h2 {
  color: #fff;
  font-size: 16px;
  margin: 0;
  white-space: nowrap;
}

.sidebar-toggle {
  display: flex;
  justify-content: flex-end;
  padding: 4px 8px;
  border-bottom: 1px solid #263445;
}

.sidebar-menu {
  border-right: none;
  background-color: #304156;
}

.sidebar-menu:not(.el-menu--collapse) {
  width: 200px;
}

.sidebar-menu .el-menu-item,
.sidebar-menu .el-sub-menu__title {
  color: #bfcbd9;
}

.sidebar-menu .el-menu-item:hover,
.sidebar-menu .el-sub-menu__title:hover,
.sidebar-menu .el-menu-item.is-active,
.sidebar-menu .el-sub-menu .el-menu-item.is-active {
  background-color: #263445;
  color: #409eff;
}

.header {
  background-color: #fff;
  border-bottom: 1px solid #e6e6e6;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  height: 56px;
  flex-shrink: 0;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-right {
  display: flex;
  align-items: center;
}

.header h3 {
  margin: 0;
  color: #303133;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
}

.username {
  color: #303133;
}

.main-content {
  background-color: #f0f2f5;
  padding: 20px;
  height: 100%;
  box-sizing: border-box;
  overflow-y: auto;
}

.drawer-logo {
  height: 56px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #2b3a4a;
  color: #fff;
}

.drawer-logo h2 {
  margin: 0;
  font-size: 18px;
  color: #fff;
}

.drawer-menu {
  border-right: none;
}

.desktop-only {
  display: block;
}

.mobile-only {
  display: none;
}

.mobile-only-btn {
  display: none;
}

@media (max-width: 900px) {
  .desktop-only {
    display: none;
  }

  .mobile-only {
    display: block;
  }

  .mobile-only-btn {
    display: inline-flex;
  }

  .header {
    padding: 0 12px;
  }

  .main-content {
    padding: 12px;
  }
}

.footer {
  background-color: #fff;
  border-top: 1px solid #e6e6e6;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 40px;
  padding: 0;
  flex-shrink: 0;
}

.footer p {
  margin: 0;
  color: #909399;
  font-size: 12px;
}
</style>
