<template>
  <div
    class="min-h-screen bg-base-100 container-md mx-auto p-6 space-y-6 flex flex-row"
  >
    <ul class="menu bg-base-200 w-56 gap-2 rounded-2xl p-5">
      <li id="1" @click="setActivePage">
        <a :class="{ 'menu-active': activePage === 1 }">用户信息</a>
      </li>
      <li id="2" @click="setActivePage">
        <a :class="{ 'menu-active': activePage === 2 }">Item 2</a>
      </li>
      <li v-if="isAdmin" id="100" @click="setActivePage">
        <a :class="{ 'menu-active': activePage === 100 }">实验板控制台</a>
      </li>
    </ul>
    <div class="divider divider-horizontal h-full"></div>
    <div class="card bg-base-300 flex-1 rounded-2xl p-7">
      <div v-if="activePage === 1">
        <UserInfo />
      </div>
      <div v-else-if="activePage === 2">
        <!-- 添加对应的组件或内容 -->
        <div>Item 2 内容</div>
      </div>
      <div v-else-if="activePage === 100">
        <BoardTable />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import BoardTable from "./BoardTable.vue";
import { toNumber } from "lodash";
import { onMounted, ref } from "vue";
import { AuthManager } from "@/utils/AuthManager";
import UserInfo from "./UserInfo.vue";

const activePage = ref(1);
const isAdmin = ref(false);

function setActivePage(event: Event) {
  const target = event.currentTarget as HTMLLinkElement;
  const newPage = toNumber(target.id);
  
  // 如果用户不是管理员但试图访问管理员页面，则忽略
  if (newPage === 100 && !isAdmin.value) {
    return;
  }
  
  activePage.value = newPage;
}

onMounted(async () => {
  try {
    // 首先验证用户是否已登录
    const isAuthenticated = await AuthManager.isAuthenticated();
    if (!isAuthenticated) {
      // 如果未登录，重定向到登录页面
      // 这里可以使用路由跳转
      return;
    }
    
    // 验证管理员权限
    isAdmin.value = await AuthManager.verifyAdminAuth();
    
    // 如果当前页面是管理员页面但用户不是管理员，切换到用户信息页面
    if (activePage.value === 100 && !isAdmin.value) {
      activePage.value = 1;
    }
  } catch (error) {
    console.error('用户认证检查失败:', error);
    // 可以在这里处理错误，比如显示错误信息或重定向到登录页面
  }
});
</script>

<style scoped>
.menu-active {
  position: relative;
}

.menu-active::before {
  content: "";
  position: absolute;
  left: -12px;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 80%;
  background-color: var(--color-primary);
  border-radius: 2px;
}
</style>
