<template>
  <div class="admin-layout">
    <el-container class="layout-container">
      <!-- 侧边栏 -->
      <el-aside :width="isCollapse ? '64px' : '240px'" class="sidebar">
        <div class="sidebar-header">
          <div class="logo" :class="{ 'collapsed': isCollapse }">
            <img src="/assets/admin/logo.svg" alt="Logo" class="logo-icon" v-show="!isCollapse" />
            <h2 v-show="!isCollapse">后台管理</h2>
          </div>
        </div>
        
        <el-menu
          :default-active="activeMenu"
          :collapse="isCollapse"
          :unique-opened="true"
          router
          background-color="#001529"
          text-color="#fff"
          active-text-color="#409EFF"
          class="sidebar-menu"
        >
          <el-menu-item index="/cpzsadmin/dashboard">
            <el-icon><DataBoard /></el-icon>
            <template #title>控制面板</template>
          </el-menu-item>
          
          <el-menu-item index="/cpzsadmin/user-list" v-if="userRole === 'superAdmin'">
            <el-icon><User /></el-icon>
            <template #title>用户管理</template>
          </el-menu-item>
          
          <el-menu-item index="/cpzsadmin/vip-code">
            <el-icon><Key /></el-icon>
            <template #title>会员码管理</template>
          </el-menu-item>
          
          <el-sub-menu index="data-import">
            <template #title>
              <el-icon><Document /></el-icon>
              <span>数据导入</span>
            </template>
            <el-menu-item index="/cpzsadmin/excel-import/ssq">
              <el-icon><DataBoard /></el-icon>
              <template #title>双色球</template>
            </el-menu-item>
            <el-menu-item index="/cpzsadmin/excel-import/dlt">
              <el-icon><DataBoard /></el-icon>
              <template #title>大乐透</template>
            </el-menu-item>
          </el-sub-menu>

          <el-sub-menu index="prediction-management">
            <template #title>
              <el-icon><Aim /></el-icon>
              <span>推测管理</span>
            </template>
            <el-menu-item index="/cpzsadmin/prediction/ssq">
              <el-icon><DataBoard /></el-icon>
              <template #title>双色球</template>
            </el-menu-item>
            <el-menu-item index="/cpzsadmin/prediction/dlt">
              <el-icon><DataBoard /></el-icon>
              <template #title>大乐透</template>
            </el-menu-item>
          </el-sub-menu>

          <el-sub-menu index="prize-statistics">
            <template #title>
              <el-icon><Trophy /></el-icon>
              <span>奖金统计</span>
            </template>
            <el-menu-item index="/cpzsadmin/prize-statistics/ssq">
              <el-icon><DataBoard /></el-icon>
              <template #title>双色球</template>
            </el-menu-item>
            <el-menu-item index="/cpzsadmin/prize-statistics/dlt">
              <el-icon><DataBoard /></el-icon>
              <template #title>大乐透</template>
            </el-menu-item>
          </el-sub-menu>

          <el-menu-item index="/cpzsadmin/operation-history">
            <el-icon><Clock /></el-icon>
            <template #title>操作历史</template>
          </el-menu-item>
          
          <el-menu-item index="/cpzsadmin/announcement">
            <el-icon><Bell /></el-icon>
            <template #title>公告管理</template>
          </el-menu-item>
        </el-menu>
      </el-aside>
      
      <!-- 主容器 -->
      <el-container class="main-container">
        <!-- 顶部导航 -->
        <el-header class="header">
          <div class="header-left">
            <el-button 
              link
              @click="toggleSidebar"
              class="toggle-button"
            >
              <el-icon :size="20">
                <Fold v-if="!isCollapse" />
                <Expand v-else />
              </el-icon>
            </el-button>
            
            <el-breadcrumb separator="/" class="breadcrumb">
              <el-breadcrumb-item :to="{ path: '/cpzsadmin/dashboard' }">首页</el-breadcrumb-item>
              <el-breadcrumb-item v-for="(item, index) in breadcrumbs" :key="index">
                {{ item }}
              </el-breadcrumb-item>
            </el-breadcrumb>
          </div>
          
          <div class="header-right">
            <div class="header-actions">
              <el-button link @click="refreshPage" class="refresh-button">
                <el-icon><Refresh /></el-icon>
              </el-button>
              
              <!-- 用户信息 -->
              <div class="user-info">
                <el-avatar :size="32" :src="userAvatar" />
                <span class="username">{{ userName }}</span>
              </div>
              
              <!-- 注销按钮 -->
              <el-button 
                type="danger" 
                @click="directLogout" 
                class="direct-logout"
                size="small"
              >
                <el-icon :size="16"><SwitchButton /></el-icon>
                <span style="font-size: 16px;">注销</span>
              </el-button>
            </div>
          </div>
        </el-header>
        
        <!-- 主内容区域 -->
        <el-main class="main-content">
          <div class="page-container">
            <router-view />
          </div>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  DataBoard,
  User,
  Key,
  Document,
  Fold,
  Expand,
  ArrowDown,
  Refresh,
  Setting,
  SwitchButton,
  Clock,
  Bell,
  Aim,
  Trophy
} from '@element-plus/icons-vue'
import { userStore } from '../../../store/user.js'
import { lotteryApi } from '../../../api/index.js'

export default {
  name: 'AdminLayout',
  components: {
    DataBoard,
    User,
    Key,
    Document,
    Fold,
    Expand,
    ArrowDown,
    Bell,
    Refresh,
    Setting,
    SwitchButton,
    Clock
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const isCollapse = ref(false)
    const userName = ref('管理员')
    const userAvatar = ref('https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png')
    const userRole = ref('')
    
    // 当前激活的菜单项
    const activeMenu = computed(() => route.path)
    
    // 面包屑导航
    const breadcrumbs = computed(() => {
      const path = route.path.split('/')
      if (path[2] === 'dashboard') return []
      
      const map = {
        'user-list': ['用户管理'],
        'vip-code': ['会员码管理'],
        'excel-import': {
          'ssq': ['数据导入', '双色球'],
          'dlt': ['数据导入', '大乐透'],
          'default': ['数据导入']
        },
        'prediction': {
          'ssq': ['推测管理', '双色球'],
          'dlt': ['推测管理', '大乐透'],
          'default': ['推测管理']
        },
        'prize-statistics': {
          'ssq': ['奖金统计', '双色球'],
          'dlt': ['奖金统计', '大乐透'],
          'default': ['奖金统计']
        },
        'operation-history': ['操作历史']
      }
      
      if (path[2] === 'excel-import' && path[3]) {
        return map['excel-import'][path[3]] || map['excel-import']['default']
      }

      if (path[2] === 'prediction' && path[3]) {
        return map['prediction'][path[3]] || map['prediction']['default']
      }

      if (path[2] === 'prize-statistics' && path[3]) {
        return map['prize-statistics'][path[3]] || map['prize-statistics']['default']
      }
      
      return map[path[2]] || [path[2]]
    })
    
    // 切换侧边栏
    const toggleSidebar = () => {
      isCollapse.value = !isCollapse.value
    }
    
    // 刷新页面
    const refreshPage = () => {
      window.location.reload()
    }
    
    // 处理下拉菜单命令
    const handleCommand = (command) => {
      console.log('接收到下拉菜单命令:', command)
      switch (command) {
        case 'profile':
          console.log('跳转到个人信息页面')
          router.push('/cpzsadmin/profile')
          break
        case 'settings':
          console.log('跳转到系统设置页面')
          router.push('/cpzsadmin/settings')
          break
        case 'logout':
          console.log('执行注销操作')
          handleLogout()
          break
        default:
          console.log('未知命令:', command)
      }
    }
    
    // 退出登录
    const handleLogout = () => {
      ElMessageBox.confirm('确认退出后台管理系统吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          // 调用后端注销接口
          const res = await lotteryApi.userLogout()
          console.log('注销API响应:', res)
          
          // 无论API响应如何，都清除session状态
          userStore.adminLogout()
          
          ElMessage({
            type: 'success',
            message: '已安全退出系统'
          })
          
          // 确保跳转到登录页
          setTimeout(() => {
            router.push('/cpzsadmin/login')
          }, 100)
        } catch (error) {
          console.error('注销过程中出错:', error)
          
          // 即使出错也清除session状态并跳转
          userStore.adminLogout()
          ElMessage({
            type: 'warning',
            message: '注销过程中出现错误，已强制退出'
          })
          
          setTimeout(() => {
            router.push('/cpzsadmin/login')
          }, 100)
        }
      }).catch(() => {
        // 用户取消操作
      })
    }
    
    // 直接注销，不使用确认对话框
    const directLogout = () => {
      try {
        // 调用后端注销接口
        lotteryApi.userLogout()
          .then(() => {
            console.log('注销API调用成功')
          })
          .catch((error) => {
            console.error('注销API调用失败:', error)
          })
          .finally(() => {
            // 无论成功失败，都清除session状态
            userStore.adminLogout()
            
            // 显示成功消息
            ElMessage({
              type: 'success',
              message: '已安全退出系统'
            })
            
            // 直接跳转到登录页
            window.location.href = '/cpzsadmin/login'
          })
      } catch (error) {
        console.error('注销过程中出错:', error)
        
        // 强制清除状态并跳转
        userStore.adminLogout()
        window.location.href = '/cpzsadmin/login'
      }
    }
    
    // 获取用户信息
    onMounted(() => {
      const user = userStore.getUserInfo()
      if (user) {
        userName.value = user.userName || user.username || '管理员'
        userRole.value = user.userRole || 'admin'
        if (user.avatar) {
          userAvatar.value = user.avatar
        }
      }
    })
    
    return {
      isCollapse,
      userName,
      userAvatar,
      userRole,
      activeMenu,
      breadcrumbs,
      toggleSidebar,
      refreshPage,
      handleCommand,
      handleLogout,
      directLogout
    }
  }
}
</script>

<style scoped>
.admin-layout {
  height: 100vh;
  width: 100vw;
  display: flex;
  overflow: hidden;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.layout-container {
  height: 100%;
  width: 100%;
}

/* 侧边栏 */
.sidebar {
  background-color: #001529;
  transition: width 0.3s;
  overflow-y: auto;
  box-shadow: 2px 0 6px rgba(0, 21, 41, 0.35);
  position: relative;
  height: 100%;
}

.sidebar-header {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #002140;
  border-bottom: 1px solid #001529;
}

.logo {
  display: flex;
  align-items: center;
  padding: 0 16px;
  transition: all 0.3s;
}

.logo.collapsed {
  justify-content: center;
}

.logo img.logo-icon {
  width: 32px;
  height: 32px;
  margin-right: 12px;
}

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

.sidebar-menu {
  border: none;
}

.sidebar-menu .el-menu-item,
.sidebar-menu .el-sub-menu__title {
  height: 50px;
  line-height: 50px;
}

/* 顶部导航 */
.header {
  background-color: #fff;
  border-bottom: 1px solid #f0f0f0;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  height: 60px;
}

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

.toggle-button {
  font-size: 18px;
  color: #666;
  padding: 8px;
  border-radius: 4px;
  transition: all 0.3s;
}

.toggle-button:hover {
  background-color: #f5f5f5;
  color: #409EFF;
}

.refresh-button {
  font-size: 18px;
  color: #666;
  padding: 8px;
  border-radius: 4px;
  transition: all 0.3s;
}

.refresh-button:hover {
  background-color: #f5f5f5;
  color: #409EFF;
}

.breadcrumb {
  font-size: 14px;
}

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

.header-actions {
  display: flex;
  align-items: center;
  gap: 0px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 8px;
  border-radius: 6px;
}

.username {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.dropdown-item-content {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 添加直接注销按钮样式 */
.direct-logout {
  margin-left: 10px;
  margin-right: 20px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 4px;
}

/* 主内容区域 */
.main-content {
  background-color: #f5f5f5;
  padding: 20px;
  overflow-y: auto;
  height: calc(100vh - 60px);
}

.page-container {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  min-height: calc(100vh - 120px);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .sidebar {
    position: fixed;
    z-index: 1000;
    height: 100vh;
    transform: translateX(-100%);
    transition: transform 0.3s;
  }
  
  .sidebar.show {
    transform: translateX(0);
  }
  
  .header {
    padding: 0 15px;
  }
  
  .header-left {
    gap: 15px;
  }
  
  .username {
    display: none;
  }
  
  .main-content {
    padding: 15px;
  }
}

/* 滚动条样式 */
.sidebar::-webkit-scrollbar,
.main-content::-webkit-scrollbar {
  width: 6px;
}

.sidebar::-webkit-scrollbar-track,
.main-content::-webkit-scrollbar-track {
  background: transparent;
}

.sidebar::-webkit-scrollbar-thumb,
.main-content::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.2);
  border-radius: 3px;
}

.sidebar::-webkit-scrollbar-thumb:hover,
.main-content::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.3);
}
</style> 