<template>
  <router-view v-if="isLoginPage" />
  <el-container v-else class="app-shell">
    <el-aside width="232px" class="sidebar">
      <div class="brand">组织人事管理平台</div>
      <el-menu :default-active="$route.path" router class="menu">
        <el-menu-item v-for="item in visibleMenuItems" :key="item.index" :index="item.index">
          <el-icon><component :is="item.icon" /></el-icon>
          <span>{{ item.label }}</span>
        </el-menu-item>
      </el-menu>
    </el-aside>
    <el-container>
      <el-header class="topbar">
        <div>{{ pageTitle }}</div>
        <div class="topbar-actions">
          <el-tag type="info">{{ auth.user?.username }}</el-tag>
          <el-button :icon="SwitchButton" @click="logout">退出</el-button>
        </div>
      </el-header>
      <el-main class="main">
        <router-view />
      </el-main>
    </el-container>
  </el-container>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useAuthStore } from './stores/auth'
import { featureRoles, hasAnyRole } from './security/access'
import {
  Briefcase,
  Calendar,
  CircleCheck,
  DataBoard,
  Download,
  Lock,
  Money,
  Monitor,
  SwitchButton,
  Tickets,
  TrendCharts,
  User
} from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const auth = useAuthStore()
const isLoginPage = computed(() => route.path === '/login')
const pageTitle = computed(() => String(route.meta.title ?? '工作台'))
const menuItems = [
  { index: '/', label: '工作台', icon: DataBoard, roles: featureRoles.dashboard },
  { index: '/employees', label: '员工档案', icon: User, roles: featureRoles.employees },
  { index: '/recruitment', label: '招聘管理', icon: Briefcase, roles: featureRoles.recruitment },
  { index: '/onboarding', label: '入离职', icon: CircleCheck, roles: featureRoles.onboarding },
  { index: '/attendance', label: '考勤请假', icon: Calendar, roles: featureRoles.attendance },
  { index: '/payroll', label: '薪酬工资', icon: Money, roles: featureRoles.payroll },
  { index: '/performance', label: '绩效管理', icon: TrendCharts, roles: featureRoles.performance },
  { index: '/reports', label: '报表导出', icon: Download, roles: featureRoles.reports },
  { index: '/security', label: '权限管理', icon: Lock, roles: featureRoles.security },
  { index: '/audit', label: '审计日志', icon: Tickets, roles: featureRoles.audit },
  { index: '/system', label: '系统信息', icon: Monitor, roles: featureRoles.system }
]
const visibleMenuItems = computed(() => menuItems.filter((item) => hasAnyRole(auth.user?.roles, item.roles)))

async function logout() {
  await auth.logout()
  router.push('/login')
}
</script>
