提交 2f089360 authored 作者: caifuming's avatar caifuming

cfm_7/17优化前端 - 先暂时静态页面进行功能展示

上级 44c60fc9
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>实习生训练平台 · 原型预览</title>
<script src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script src="https://unpkg.com/antd@5.20.0/dist/antd.min.js"></script>
<script src="https://unpkg.com/@ant-design/icons@5.4.0/dist/index.umd.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/antd@5.20.0/dist/reset.css">
<style>
* { box-sizing: border-box; }
body { margin: 0; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif; background: #f0f2f5; }
.page-wrap { padding: 24px; min-height: calc(100vh - 64px - 48px); background: #f0f2f5; }
.stat-card {
border-radius: 12px;
padding: 20px;
color: white;
position: relative;
overflow: hidden;
box-shadow: 0 4px 12px rgba(0,0,0,0.08);
transition: transform 0.2s;
}
.stat-card:hover { transform: translateY(-3px); }
.stat-card .num { font-size: 32px; font-weight: 700; margin-bottom: 4px; }
.stat-card .label { font-size: 14px; opacity: 0.9; }
.stat-card .icon-bg {
position: absolute; right: -10px; bottom: -10px;
font-size: 80px; opacity: 0.18;
}
.grad-1 { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
.grad-2 { background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); }
.grad-3 { background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); }
.grad-4 { background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%); }
.grad-5 { background: linear-gradient(135deg, #fa709a 0%, #fee140 100%); }
.grad-6 { background: linear-gradient(135deg, #30cfd0 0%, #330867 100%); }
.welcome-banner {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border-radius: 16px;
padding: 32px;
color: white;
margin-bottom: 24px;
position: relative;
overflow: hidden;
}
.welcome-banner h2 { margin: 0 0 8px 0; font-size: 26px; font-weight: 600; }
.welcome-banner p { margin: 0; opacity: 0.9; }
.welcome-banner .decor {
position: absolute; right: 40px; top: 50%; transform: translateY(-50%);
font-size: 120px; opacity: 0.2;
}
.task-item {
padding: 14px 16px;
border-radius: 8px;
border: 1px solid #f0f0f0;
margin-bottom: 10px;
transition: all 0.2s;
cursor: pointer;
}
.task-item:hover {
border-color: #667eea;
box-shadow: 0 2px 8px rgba(102,126,234,0.1);
transform: translateX(4px);
}
.task-item .title { font-weight: 500; margin-bottom: 4px; }
.task-item .meta { font-size: 12px; color: #999; }
.course-card {
border-radius: 12px;
overflow: hidden;
transition: all 0.25s;
cursor: pointer;
border: 1px solid #f0f0f0;
}
.course-card:hover {
transform: translateY(-4px);
box-shadow: 0 8px 24px rgba(0,0,0,0.1);
}
.course-cover {
height: 120px;
display: flex;
align-items: center;
justify-content: center;
color: white;
font-size: 36px;
font-weight: 700;
letter-spacing: 2px;
}
.cover-1 { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
.cover-2 { background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); }
.cover-3 { background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); }
.cover-4 { background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%); }
.cover-5 { background: linear-gradient(135deg, #fa709a 0%, #fee140 100%); }
.cover-6 { background: linear-gradient(135deg, #30cfd0 0%, #330867 100%); }
.cover-7 { background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%); color: #333; }
.cover-8 { background: linear-gradient(135deg, #ff9a9e 0%, #fad0c4 100%); color: #333; }
.project-card {
border-radius: 12px;
padding: 20px;
background: white;
border: 1px solid #f0f0f0;
transition: all 0.25s;
cursor: pointer;
}
.project-card:hover {
transform: translateY(-3px);
box-shadow: 0 6px 20px rgba(0,0,0,0.08);
border-color: #667eea;
}
.role-switcher {
display: flex; gap: 12px; padding: 16px 24px;
background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
border-radius: 12px; margin-bottom: 16px;
}
.role-btn {
padding: 8px 18px; border-radius: 20px; border: 2px solid transparent;
cursor: pointer; font-weight: 500; transition: all 0.2s;
background: white; color: #555;
}
.role-btn:hover { transform: translateY(-2px); }
.role-btn.active {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
box-shadow: 0 4px 12px rgba(102,126,234,0.4);
}
.timeline-item {
padding: 12px 16px;
border-left: 3px solid #667eea;
background: #fafafa;
border-radius: 0 8px 8px 0;
margin-bottom: 12px;
}
.timeline-item .time { font-size: 12px; color: #999; }
.timeline-item .title { font-weight: 500; margin: 4px 0; }
.leaderboard-item {
display: flex; align-items: center; gap: 12px;
padding: 10px 12px; border-radius: 8px;
margin-bottom: 6px; transition: background 0.2s;
}
.leaderboard-item:hover { background: #f5f7ff; }
.rank-badge {
width: 28px; height: 28px; border-radius: 50%;
display: flex; align-items: center; justify-content: center;
font-weight: 700; color: white;
}
.rank-1 { background: linear-gradient(135deg, #ffd700 0%, #ffa500 100%); }
.rank-2 { background: linear-gradient(135deg, #c0c0c0 0%, #808080 100%); }
.rank-3 { background: linear-gradient(135deg, #cd7f32 0%, #8b4513 100%); }
.rank-n { background: #e0e0e0; color: #666; }
</style>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
const { useState, useMemo, useEffect } = React;
const {
Layout, Menu, Dropdown, Avatar, Button, Space, Tag, Spin,
Card, Row, Col, Progress, Table, Badge, Tabs, Statistic,
List, Empty, Divider, Tooltip
} = antd;
const Icons = window['ant-design/icons'];
const {
DashboardOutlined, ProjectOutlined, BookOutlined, AuditOutlined,
BellOutlined, UserOutlined, LogoutOutlined, SettingOutlined,
TeamOutlined, SafetyOutlined, TrophyOutlined, FireOutlined,
RocketOutlined, BulbOutlined, StarOutlined, ThunderboltOutlined,
CrownOutlined, SolutionOutlined, ReadOutlined, CodeOutlined,
CheckCircleOutlined, ClockCircleOutlined, RiseOutlined
} = Icons;
const { Header, Sider, Content } = Layout;
/* ============ 角色配置 ============ */
const ROLES = {
ADMIN: {
name: '系统管理员',
code: 'ADMIN',
color: 'red',
icon: '👑',
realName: '系统管理员',
username: 'admin',
desc: '拥有平台全部权限',
avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=admin'
},
SUPERVISOR: {
name: '部门主管',
code: 'SUPERVISOR',
color: 'orange',
icon: '🛡️',
realName: '张主管',
username: 'supervisor01',
desc: '管理整个部门的培训与项目',
avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=supervisor'
},
MENTOR: {
name: '导师',
code: 'MENTOR',
color: 'blue',
icon: '🎓',
realName: '李导师',
username: 'mentor01',
desc: '指导学员完成项目与答辩',
avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=mentor'
},
STUDENT: {
name: '实习生',
code: 'STUDENT',
color: 'green',
icon: '🚀',
realName: '小王同学',
username: 'student01',
desc: '正在努力成长为合格的工程师',
avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=student'
}
};
/* ============ 菜单配置 ============ */
const ALL_MENUS = [
{ key: '/dashboard', icon: <DashboardOutlined />, label: '工作台', roles: ['ADMIN','SUPERVISOR','MENTOR','STUDENT'] },
{ key: '/projects', icon: <ProjectOutlined />, label: '项目中心', roles: ['ADMIN','SUPERVISOR','MENTOR','STUDENT'] },
{ key: '/training', icon: <BookOutlined />, label: '训练营', roles: ['ADMIN','SUPERVISOR','MENTOR','STUDENT'] },
{ key: '/defense', icon: <AuditOutlined />, label: '答辩中心', roles: ['ADMIN','SUPERVISOR','MENTOR','STUDENT'] },
{ key: '/audit', icon: <SafetyOutlined />, label: '审计中心', roles: ['ADMIN','SUPERVISOR','MENTOR'] },
{ key: '/users', icon: <TeamOutlined />, label: '用户管理', roles: ['ADMIN'] },
{ key: '/roles', icon: <SafetyOutlined />, label: '角色管理', roles: ['ADMIN'] },
{ key: '/notifications', icon: <BellOutlined />, label: '通知中心', roles: ['ADMIN','SUPERVISOR','MENTOR','STUDENT'] },
];
/* ============ 登录页 ============ */
const LoginPage = ({ onLogin }) => {
const [selectedRole, setSelectedRole] = useState('STUDENT');
return (
<div style={{ display: 'flex', minHeight: '100vh', background: '#f0f2f5' }}>
{/* 左侧品牌 */}
<div style={{
flex: 1,
background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
position: 'relative', overflow: 'hidden',
display: 'flex', alignItems: 'center', justifyContent: 'center',
color: 'white'
}}>
<div style={{ position: 'relative', zIndex: 1, textAlign: 'center', padding: 40 }}>
<div style={{ marginBottom: 24 }}>
<div style={{
width: 100, height: 100, borderRadius: 24,
background: 'rgba(255,255,255,0.2)', backdropFilter: 'blur(10px)',
display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
fontSize: 56
}}>🎓</div>
</div>
<h1 style={{ fontSize: 42, fontWeight: 700, marginBottom: 8 }}>实习生训练平台</h1>
<p style={{ fontSize: 18, opacity: 0.9, marginBottom: 48 }}>Intern Training Platform · v2.0</p>
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 20, maxWidth: 500, textAlign: 'left' }}>
<div style={{ background: 'rgba(255,255,255,0.15)', padding: '14px 20px', borderRadius: 12, backdropFilter: 'blur(10px)' }}>
<span style={{ fontSize: 24, marginRight: 12 }}>🎯</span><span>项目实战体系</span>
</div>
<div style={{ background: 'rgba(255,255,255,0.15)', padding: '14px 20px', borderRadius: 12, backdropFilter: 'blur(10px)' }}>
<span style={{ fontSize: 24, marginRight: 12 }}>👥</span><span>导师1V1指导</span>
</div>
<div style={{ background: 'rgba(255,255,255,0.15)', padding: '14px 20px', borderRadius: 12, backdropFilter: 'blur(10px)' }}>
<span style={{ fontSize: 24, marginRight: 12 }}>📚</span><span>系统训练课程</span>
</div>
<div style={{ background: 'rgba(255,255,255,0.15)', padding: '14px 20px', borderRadius: 12, backdropFilter: 'blur(10px)' }}>
<span style={{ fontSize: 24, marginRight: 12 }}>🏆</span><span>能力评估认证</span>
</div>
</div>
</div>
</div>
{/* 右侧角色选择 */}
<div style={{ width: 560, background: 'white', padding: 40, display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
<div style={{ maxWidth: 440, margin: '0 auto', width: '100%' }}>
<h2 style={{ fontSize: 28, fontWeight: 600, marginBottom: 8 }}>选择身份进入 👋</h2>
<p style={{ color: '#666', marginBottom: 32 }}>原型预览:点击下方任一角色即可登录对应视图</p>
{Object.entries(ROLES).map(([key, role]) => (
<div
key={key}
onClick={() => onLogin(key)}
style={{
padding: 20, marginBottom: 16, borderRadius: 12,
border: selectedRole === key ? '2px solid #667eea' : '2px solid #f0f0f0',
cursor: 'pointer', transition: 'all 0.2s',
display: 'flex', alignItems: 'center', gap: 16,
background: selectedRole === key ? '#f5f7ff' : 'white'
}}
onMouseEnter={(e) => { if (selectedRole !== key) e.currentTarget.style.borderColor = '#d0d7e6'; }}
onMouseLeave={(e) => { if (selectedRole !== key) e.currentTarget.style.borderColor = '#f0f0f0'; }}
onClickCapture={() => setSelectedRole(key)}
>
<div style={{
width: 56, height: 56, borderRadius: '50%',
background: role.color === 'red' ? 'linear-gradient(135deg,#ff6b6b,#ee5a6f)' :
role.color === 'orange' ? 'linear-gradient(135deg,#ffa726,#fb8c00)' :
role.color === 'blue' ? 'linear-gradient(135deg,#42a5f5,#1976d2)' :
'linear-gradient(135deg,#66bb6a,#43a047)',
display: 'flex', alignItems: 'center', justifyContent: 'center',
fontSize: 28
}}>{role.icon}</div>
<div style={{ flex: 1 }}>
<div style={{ fontSize: 18, fontWeight: 600 }}>{role.name}</div>
<div style={{ fontSize: 13, color: '#888', marginTop: 2 }}>{role.desc}</div>
</div>
<Tag color={role.color}>{role.code}</Tag>
</div>
))}
<div style={{ textAlign: 'center', marginTop: 24, color: '#999', fontSize: 13 }}>
© 2026 实习生训练平台 · 原型预览
</div>
</div>
</div>
</div>
);
};
/* ============ 工作台 - 不同角色展示不同内容 ============ */
const DashboardPage = ({ role }) => {
const r = ROLES[role];
const isAdmin = role === 'ADMIN';
const isSupervisor = role === 'SUPERVISOR';
const isMentor = role === 'MENTOR';
const isStudent = role === 'STUDENT';
// 不同角色的统计数据
const stats = {
ADMIN: [
{ num: 156, label: '注册用户', icon: '👥', grad: 'grad-1' },
{ num: 42, label: '活跃项目', icon: '📁', grad: 'grad-2' },
{ num: 28, label: '今日登录', icon: '🔐', grad: 'grad-3' },
{ num: 8, label: '待审批', icon: '⏰', grad: 'grad-4' },
],
SUPERVISOR: [
{ num: 23, label: '部门成员', icon: '👥', grad: 'grad-1' },
{ num: 12, label: '进行中项目', icon: '📁', grad: 'grad-2' },
{ num: 5, label: '本周答辩', icon: '🎯', grad: 'grad-3' },
{ num: 3, label: '待审核', icon: '⏰', grad: 'grad-4' },
],
MENTOR: [
{ num: 6, label: '我的学员', icon: '🎓', grad: 'grad-1' },
{ num: 8, label: '指导项目', icon: '📁', grad: 'grad-2' },
{ num: 2, label: '待批改', icon: '📝', grad: 'grad-3' },
{ num: 86, label: '学员平均分', icon: '⭐', grad: 'grad-4' },
],
STUDENT: [
{ num: 12, label: '已学课程', icon: '📚', grad: 'grad-1' },
{ num: 3, label: '进行中项目', icon: '📁', grad: 'grad-2' },
{ num: 78, label: '总学分', icon: '⭐', grad: 'grad-3' },
{ num: 5, label: '待完成', icon: '⏰', grad: 'grad-4' },
]
}[role];
const welcomeMsg = {
ADMIN: '欢迎回来,平台一切运行正常!',
SUPERVISOR: '今天有 3 位学员申请项目答辩,请及时审批。',
MENTOR: '您指导的 6 位学员本周表现都很棒!',
STUDENT: '今天又是充满能量的一天,加油!'
}[role];
return (
<div>
{/* 欢迎横幅 */}
<div className="welcome-banner">
<h2>{r.icon} 你好,{r.realName}</h2>
<p>{welcomeMsg}</p>
<div className="decor">{r.icon}</div>
</div>
{/* 统计卡片 */}
<Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
{stats.map((s, i) => (
<Col xs={24} sm={12} lg={6} key={i}>
<div className={`stat-card ${s.grad}`}>
<div className="num">{s.num}</div>
<div className="label">{s.label}</div>
<div className="icon-bg">{s.icon}</div>
</div>
</Col>
))}
</Row>
<Row gutter={[16, 16]}>
{/* 左侧:进行中任务 */}
<Col xs={24} lg={16}>
<Card title={<><RocketOutlined /> 进行中的任务</>} extra={<a>查看全部</a>}>
{(role === 'STUDENT' ? [
{ t: '完成电商系统订单模块', m: '项目中心 · 截止 2026-07-25', tag: '进行中', color: 'blue' },
{ t: '学习 Spring Cloud 微服务章节', m: '训练营 · 进度 60%', tag: '学习中', color: 'cyan' },
{ t: '准备项目答辩 PPT', m: '答辩中心 · 7月20日 14:00', tag: '待答辩', color: 'orange' },
{ t: '完成前端组件库作业', m: '训练营 · 截止 2026-07-18', tag: '待提交', color: 'red' },
] : role === 'MENTOR' ? [
{ t: '审阅 王同学的电商项目代码', m: '项目中心 · 已分配 2天前', tag: '待批阅', color: 'red' },
{ t: '审阅 李同学的算法作业', m: '训练营 · 已提交', tag: '待批阅', color: 'red' },
{ t: '参加项目答辩评审', m: '答辩中心 · 7月20日 14:00', tag: '已确认', color: 'green' },
{ t: '为新学员制定培养计划', m: '审计中心 · 优先级高', tag: '进行中', color: 'blue' },
] : role === 'SUPERVISOR' ? [
{ t: '审批本周项目立项申请 (3项)', m: '审计中心 · 待审批', tag: '待审批', color: 'red' },
{ t: '审核部门成员答辩评分', m: '答辩中心 · 本周五', tag: '待审核', color: 'orange' },
{ t: '季度培训计划制定', m: '训练营 · 部门级', tag: '进行中', color: 'blue' },
{ t: '查看部门成员周报', m: '项目中心 · 8份未读', tag: '待查看', color: 'purple' },
] : [
{ t: '审核角色权限配置变更', m: '角色管理 · 等待审批', tag: '待审批', color: 'red' },
{ t: '查看系统运行状况报告', m: '审计中心 · 异常 2 项', tag: '需关注', color: 'orange' },
{ t: '审批新增用户账号申请 (5个)', m: '用户管理 · 等待处理', tag: '待审批', color: 'red' },
{ t: '系统数据库备份确认', m: '审计中心 · 每日任务', tag: '已完成', color: 'green' },
]).map((task, i) => (
<div key={i} className="task-item">
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<div className="title">{task.t}</div>
<Tag color={task.color}>{task.tag}</Tag>
</div>
<div className="meta">{task.m}</div>
</div>
))}
</Card>
{/* 学习/项目进度 */}
<Card title={<><RiseOutlined /> {role === 'STUDENT' ? '学习进度' : '项目进度概览'}</>} style={{ marginTop: 16 }}>
{(role === 'STUDENT' ? [
{ name: 'Java 进阶课程', val: 75, color: '#667eea' },
{ name: 'Spring Boot 实战', val: 60, color: '#f093fb' },
{ name: '微服务架构', val: 45, color: '#4facfe' },
{ name: '前端开发基础', val: 90, color: '#43e97b' },
{ name: '数据库设计与优化', val: 70, color: '#fa709a' },
] : role === 'MENTOR' ? [
{ name: '电商系统项目', val: 65, color: '#667eea' },
{ name: '推荐系统项目', val: 40, color: '#f093fb' },
{ name: '在线教育平台', val: 80, color: '#4facfe' },
] : role === 'SUPERVISOR' ? [
{ name: '后端开发部', val: 72, color: '#667eea' },
{ name: '前端开发部', val: 68, color: '#f093fb' },
{ name: '数据工程部', val: 55, color: '#4facfe' },
{ name: '运维部', val: 88, color: '#43e97b' },
] : [
{ name: '平台总体活跃度', val: 78, color: '#667eea' },
{ name: '训练营完成率', val: 65, color: '#f093fb' },
{ name: '项目交付率', val: 82, color: '#4facfe' },
{ name: '用户满意度', val: 91, color: '#43e97b' },
]).map((p, i) => (
<div key={i} style={{ marginBottom: 16 }}>
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
<span>{p.name}</span>
<span style={{ color: '#666' }}>{p.val}%</span>
</div>
<Progress percent={p.val} strokeColor={p.color} showInfo={false} />
</div>
))}
</Card>
</Col>
{/* 右侧:成就/排行榜/动态 */}
<Col xs={24} lg={8}>
{/* 学员成就 */}
{isStudent && (
<Card title={<><TrophyOutlined style={{color:'#faad14'}}/> 我的成就</>} style={{ marginBottom: 16 }}>
<Row gutter={[8, 8]}>
{[
{ e: '🥇', n: '首次答辩', c: 'gold' },
{ e: '🔥', n: '连续7天', c: 'volcano' },
{ e: '💎', n: '优秀学员', c: 'blue' },
{ e: '⭐', n: '满分作业', c: 'purple' },
{ e: '🎯', n: '项目完成', c: 'green' },
{ e: '📚', n: '学霸认证', c: 'magenta' },
].map((a, i) => (
<Col span={8} key={i}>
<div style={{
textAlign: 'center', padding: '14px 0',
background: '#fafafa', borderRadius: 8,
transition: 'transform 0.2s', cursor: 'pointer'
}} onMouseEnter={(e) => e.currentTarget.style.transform = 'scale(1.05)'}
onMouseLeave={(e) => e.currentTarget.style.transform = 'scale(1)'}>
<div style={{ fontSize: 32 }}>{a.e}</div>
<div style={{ fontSize: 12, color: '#666', marginTop: 4 }}>{a.n}</div>
</div>
</Col>
))}
</Row>
</Card>
)}
{/* 排行榜 */}
<Card title={<><FireOutlined style={{color:'#f5222d'}}/> {role === 'STUDENT' ? '学员积分榜' : role === 'MENTOR' ? '导师评分榜' : '部门积分榜'}</>} style={{ marginBottom: 16 }}>
{(role === 'STUDENT' ? [
{ r: 1, n: '王同学', s: 980, t: '98分' },
{ r: 2, n: '李同学', s: 920, t: '92分' },
{ r: 3, n: '张同学', s: 880, t: '88分' },
{ r: 4, n: '赵同学', s: 850, t: '85分' },
{ r: 5, n: '钱同学', s: 820, t: '82分' },
{ r: 6, n: '孙同学', s: 780, t: '78分' },
] : role === 'MENTOR' ? [
{ r: 1, n: '陈导师', s: 96, t: '96分' },
{ r: 2, n: '李导师', s: 94, t: '94分' },
{ r: 3, n: '刘导师', s: 92, t: '92分' },
{ r: 4, n: '黄导师', s: 90, t: '90分' },
] : role === 'SUPERVISOR' ? [
{ r: 1, n: '后端开发部', s: 9200, t: '部门得分' },
{ r: 2, n: '前端开发部', s: 8800, t: '部门得分' },
{ r: 3, n: '数据工程部', s: 8600, t: '部门得分' },
{ r: 4, n: '产品设计部', s: 8200, t: '部门得分' },
] : [
{ r: 1, n: '北京研发中心', s: 9800, t: '基地得分' },
{ r: 2, n: '上海研发分中心', s: 9200, t: '基地得分' },
{ r: 3, n: '深圳研发分中心', s: 8800, t: '基地得分' },
]).map((u, i) => (
<div key={i} className="leaderboard-item">
<div className={`rank-badge rank-${u.r <= 3 ? u.r : 'n'}`}>{u.r}</div>
<div style={{ flex: 1 }}>
<div style={{ fontWeight: 500 }}>{u.n}</div>
<div style={{ fontSize: 12, color: '#999' }}>{u.t}</div>
</div>
<div style={{ fontWeight: 600, color: '#667eea' }}>{u.s}</div>
</div>
))}
</Card>
{/* 最新动态 */}
<Card title={<><BellOutlined /> 最新动态</>}>
{[
{ t: '系统公告', d: '2026-07-16 09:00', c: '平台将进行版本升级' },
{ t: '项目通知', d: '2026-07-15 17:30', c: '您的项目已通过立项审批' },
{ t: '训练营', d: '2026-07-14 14:20', c: '新课程《云原生实战》已上线' },
{ t: '答辩通知', d: '2026-07-13 11:00', c: '本周答辩安排已发布' },
].map((n, i) => (
<div key={i} className="timeline-item">
<div className="time">{n.d}</div>
<div className="title">{n.t}</div>
<div style={{ fontSize: 13, color: '#666' }}>{n.c}</div>
</div>
))}
</Card>
</Col>
</Row>
</div>
);
};
/* ============ 项目中心 ============ */
const ProjectPage = ({ role }) => {
const projects = [
{ name: '电商系统订单模块', tech: ['Spring Boot','MySQL','Redis'], status: '进行中', progress: 65, mentor: '李导师', members: ['王同学','张同学','李同学'] },
{ name: '推荐算法系统', tech: ['Python','TensorFlow'], status: '进行中', progress: 40, mentor: '陈导师', members: ['赵同学'] },
{ name: '在线教育平台', tech: ['Vue','Node.js'], status: '已交付', progress: 100, mentor: '刘导师', members: ['钱同学','孙同学'] },
{ name: '智能客服机器人', tech: ['NLP','Flask'], status: '待评审', progress: 90, mentor: '李导师', members: ['周同学'] },
{ name: '移动端App开发', tech: ['React Native'], status: '进行中', progress: 55, mentor: '黄导师', members: ['王同学','陈同学'] },
{ name: '数据分析平台', tech: ['Spark','Hadoop'], status: '已立项', progress: 10, mentor: '陈导师', members: ['李同学'] },
];
return (
<div>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
<h2 style={{ margin: 0 }}>📁 项目中心</h2>
{(role === 'ADMIN' || role === 'SUPERVISOR' || role === 'STUDENT') && (
<Button type="primary" icon={<RocketOutlined />}>新建项目</Button>
)}
</div>
<Row gutter={[16, 16]}>
{projects.map((p, i) => (
<Col xs={24} md={12} lg={8} key={i}>
<div className="project-card">
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 12 }}>
<h3 style={{ margin: 0, fontSize: 16 }}>{p.name}</h3>
<Tag color={p.status === '已交付' ? 'green' : p.status === '进行中' ? 'blue' : p.status === '待评审' ? 'orange' : 'default'}>{p.status}</Tag>
</div>
<Space size={4} wrap style={{ marginBottom: 12 }}>
{p.tech.map((t, j) => <Tag key={j}>{t}</Tag>)}
</Space>
<Progress percent={p.progress} strokeColor={{ '0%': '#667eea', '100%': '#764ba2' }} />
<Divider style={{ margin: '12px 0' }} />
<div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13, color: '#666' }}>
<span>👨‍🏫 {p.mentor}</span>
<span>👥 {p.members.length} 人</span>
</div>
<div style={{ marginTop: 8 }}>
<Avatar.Group size="small">
{p.members.map((m, k) => (
<Tooltip key={k} title={m}>
<Avatar style={{ backgroundColor: '#' + Math.random().toString(16).slice(2,8) }}>{m[0]}</Avatar>
</Tooltip>
))}
</Avatar.Group>
</div>
</div>
</Col>
))}
</Row>
</div>
);
};
/* ============ 训练营 ============ */
const TrainingPage = ({ role }) => {
const courses = [
{ n: 'Java 进阶:并发编程', t: '李导师', dur: '24学时', level: '进阶', c: 'cover-1', tag: '热门' },
{ n: 'Spring Cloud 微服务实战', t: '陈导师', dur: '36学时', level: '高级', c: 'cover-2', tag: '推荐' },
{ n: 'MySQL 性能优化', t: '刘导师', dur: '18学时', level: '进阶', c: 'cover-3' },
{ n: 'React Hooks 深入', t: '黄导师', dur: '20学时', level: '中级', c: 'cover-4', tag: '新课' },
{ n: 'Python 数据分析', t: '陈导师', dur: '30学时', level: '入门', c: 'cover-5' },
{ n: 'Docker 与 Kubernetes', t: '李导师', dur: '28学时', level: '高级', c: 'cover-6', tag: '热门' },
{ n: '系统设计与架构', t: '陈导师', dur: '40学时', level: '高级', c: 'cover-7' },
{ n: '前端性能优化', t: '黄导师', dur: '16学时', level: '中级', c: 'cover-8' },
];
return (
<div>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
<h2 style={{ margin: 0 }}>📚 训练营</h2>
{(role === 'ADMIN' || role === 'SUPERVISOR' || role === 'MENTOR') && (
<Button type="primary" icon={<BulbOutlined />}>发布课程</Button>
)}
</div>
<Row gutter={[16, 16]}>
{courses.map((c, i) => (
<Col xs={24} sm={12} md={8} lg={6} key={i}>
<div className="course-card">
<div className={`course-cover ${c.c}`}>
{c.tag && <Tag color="gold" style={{position:'absolute',right:8,top:8}}>{c.tag}</Tag>}
<div style={{ textAlign: 'center' }}>
<CodeOutlined style={{ fontSize: 36, display: 'block', marginBottom: 4 }} />
<div style={{ fontSize: 14 }}>{c.n}</div>
</div>
</div>
<div style={{ padding: 16 }}>
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
<Tag color="blue">{c.level}</Tag>
<span style={{ fontSize: 12, color: '#999' }}>⏱ {c.dur}</span>
</div>
<div style={{ fontSize: 13, color: '#666' }}>👨‍🏫 {c.t}</div>
<Button type="primary" block style={{ marginTop: 12 }}>
{role === 'STUDENT' ? '开始学习' : '查看详情'}
</Button>
</div>
</div>
</Col>
))}
</Row>
</div>
);
};
/* ============ 答辩中心 ============ */
const DefensePage = ({ role }) => {
const data = [
{ name: '电商系统订单模块', student: '王同学', mentor: '李导师', date: '2026-07-20 14:00', status: '待答辩', score: '-' },
{ name: '推荐算法系统', student: '赵同学', mentor: '陈导师', date: '2026-07-21 10:00', status: '待答辩', score: '-' },
{ name: '智能客服机器人', student: '周同学', mentor: '李导师', date: '2026-07-18 15:00', status: '已答辩', score: 92 },
{ name: '在线教育平台', student: '钱同学', mentor: '刘导师', date: '2026-07-15 14:00', status: '已答辩', score: 88 },
];
const columns = [
{ title: '项目名称', dataIndex: 'name' },
{ title: role === 'STUDENT' ? '我的' : '学员', dataIndex: 'student' },
{ title: '导师', dataIndex: 'mentor' },
{ title: '答辩时间', dataIndex: 'date' },
{ title: '状态', dataIndex: 'status', render: s => <Tag color={s === '已答辩' ? 'green' : 'blue'}>{s}</Tag> },
{ title: '评分', dataIndex: 'score' },
{
title: '操作', render: (_, r) => (
<Space>
{role === 'MENTOR' && r.status === '待答辩' && <Button type="primary" size="small">评分</Button>}
{role === 'SUPERVISOR' && r.status === '待答辩' && <Button size="small">审核</Button>}
{role === 'STUDENT' && r.status === '待答辩' && <Button type="primary" size="small">进入答辩</Button>}
<Button size="small">详情</Button>
</Space>
)
}
];
return (
<Card title="🎯 答辩中心">
<Table dataSource={data} columns={columns} pagination={false} />
</Card>
);
};
/* ============ 审计中心 ============ */
const AuditPage = ({ role }) => {
if (role === 'STUDENT') return <Empty description="您无权访问此模块" />;
const data = [
{ t: '用户:student01 创建项目', u: 'student01', time: '2026-07-16 14:23', type: '项目', status: 'success' },
{ t: '用户:mentor01 批阅作业', u: 'mentor01', time: '2026-07-16 11:05', type: '教学', status: 'success' },
{ t: '用户:supervisor01 审批答辩', u: 'supervisor01', time: '2026-07-16 09:30', type: '审批', status: 'success' },
{ t: '系统:异常登录尝试 (3次)', u: 'system', time: '2026-07-15 23:14', type: '安全', status: 'warning' },
{ t: '用户:admin 修改角色权限', u: 'admin', time: '2026-07-15 17:00', type: '系统', status: 'danger' },
{ t: '用户:student03 提交作业', u: 'student03', time: '2026-07-15 14:20', type: '教学', status: 'success' },
];
const columns = [
{ title: '操作', dataIndex: 't' },
{ title: '操作人', dataIndex: 'u' },
{ title: '时间', dataIndex: 'time' },
{ title: '类型', dataIndex: 'type', render: t => <Tag>{t}</Tag> },
{ title: '状态', dataIndex: 'status', render: s => <Badge status={s} text={s === 'success' ? '正常' : s === 'warning' ? '警告' : '严重'} /> },
];
return (
<div>
<Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
<Col span={6}><div className="stat-card grad-3"><div className="num">1,248</div><div className="label">今日操作总数</div><div className="icon-bg">📊</div></div></Col>
<Col span={6}><div className="stat-card grad-2"><div className="num">12</div><div className="label">异常事件</div><div className="icon-bg">⚠️</div></div></Col>
<Col span={6}><div className="stat-card grad-4"><div className="num">98%</div><div className="label">操作成功率</div><div className="icon-bg">✅</div></div></Col>
<Col span={6}><div className="stat-card grad-1"><div className="num">86</div><div className="label">活跃用户</div><div className="icon-bg">👥</div></div></Col>
</Row>
<Card title="🛡️ 操作审计日志">
<Table dataSource={data} columns={columns} pagination={false} />
</Card>
</div>
);
};
/* ============ 用户管理(仅ADMIN) ============ */
const UserManagementPage = () => {
const data = [
{ id: 1, username: 'admin', realName: '系统管理员', role: 'ADMIN', dept: '总部', status: '正常', last: '2分钟前' },
{ id: 2, username: 'supervisor01', realName: '张主管', role: 'SUPERVISOR', dept: '后端部', status: '正常', last: '1小时前' },
{ id: 3, username: 'mentor01', realName: '李导师', role: 'MENTOR', dept: '后端部', status: '正常', last: '10分钟前' },
{ id: 4, username: 'student01', realName: '王同学', role: 'STUDENT', dept: '后端部', status: '正常', last: '5分钟前' },
{ id: 5, username: 'student02', realName: '赵同学', role: 'STUDENT', dept: '前端部', status: '禁用', last: '3天前' },
];
const columns = [
{ title: 'ID', dataIndex: 'id' },
{ title: '用户名', dataIndex: 'username' },
{ title: '姓名', dataIndex: 'realName' },
{ title: '角色', dataIndex: 'role', render: r => {
const c = { ADMIN: 'red', SUPERVISOR: 'orange', MENTOR: 'blue', STUDENT: 'green' };
return <Tag color={c[r]}>{r}</Tag>;
}},
{ title: '部门', dataIndex: 'dept' },
{ title: '状态', dataIndex: 'status', render: s => <Badge status={s === '正常' ? 'success' : 'error'} text={s} /> },
{ title: '最后登录', dataIndex: 'last' },
{ title: '操作', render: () => <Space><Button size="small">编辑</Button><Button size="small" danger>禁用</Button></Space> },
];
return (
<Card title="👥 用户管理" extra={<Button type="primary">+ 新建用户</Button>}>
<Table dataSource={data} columns={columns} pagination={false} />
</Card>
);
};
/* ============ 角色管理(仅ADMIN) ============ */
const RoleManagementPage = () => {
const data = [
{ name: 'ADMIN', code: '系统管理员', count: 1, perms: 24, desc: '拥有全部权限' },
{ name: 'SUPERVISOR', code: '部门主管', count: 3, perms: 18, desc: '管理部门事务' },
{ name: 'MENTOR', code: '导师', count: 8, perms: 14, desc: '指导学员' },
{ name: 'STUDENT', code: '实习生', count: 144, perms: 6, desc: '学习与项目' },
];
return (
<Row gutter={[16, 16]}>
{data.map((r, i) => (
<Col xs={24} sm={12} lg={6} key={i}>
<Card hoverable>
<div style={{ textAlign: 'center' }}>
<div style={{
width: 64, height: 64, borderRadius: '50%',
background: r.name === 'ADMIN' ? 'linear-gradient(135deg,#ff6b6b,#ee5a6f)' :
r.name === 'SUPERVISOR' ? 'linear-gradient(135deg,#ffa726,#fb8c00)' :
r.name === 'MENTOR' ? 'linear-gradient(135deg,#42a5f5,#1976d2)' :
'linear-gradient(135deg,#66bb6a,#43a047)',
margin: '0 auto 16px', display: 'flex', alignItems: 'center', justifyContent: 'center',
fontSize: 28, color: 'white', fontWeight: 700
}}>{r.name[0]}</div>
<h3 style={{ margin: 0 }}>{r.code}</h3>
<Tag style={{ marginTop: 8 }}>{r.name}</Tag>
<div style={{ marginTop: 16, color: '#666', fontSize: 13 }}>{r.desc}</div>
<Divider />
<Row>
<Col span={12}><Statistic title="用户数" value={r.count} valueStyle={{fontSize:20,color:'#667eea'}} /></Col>
<Col span={12}><Statistic title="权限数" value={r.perms} valueStyle={{fontSize:20,color:'#f5576c'}} /></Col>
</Row>
<Button block style={{ marginTop: 16 }}>配置权限</Button>
</div>
</Card>
</Col>
))}
</Row>
);
};
/* ============ 通知中心 ============ */
const NotificationPage = () => {
return (
<List
itemLayout="horizontal"
dataSource={[
{ t: '🎉 新课程上线通知', d: '《云原生实战》课程已上线,立即学习', time: '2小时前', read: false },
{ t: '📝 答辩安排通知', d: '您的项目答辩已安排在 7月20日 14:00', time: '5小时前', read: false },
{ t: '✅ 项目审批通过', d: '您的项目《电商系统订单模块》已通过立项审批', time: '1天前', read: true },
{ t: '🎯 训练营通知', d: '您的导师已为您分配新的学习任务', time: '2天前', read: true },
]}
renderItem={item => (
<List.Item style={{ background: item.read ? 'white' : '#f0f5ff', padding: 16, borderRadius: 8, marginBottom: 8 }}>
<List.Item.Meta
title={<span><Badge dot={!item.read}><span style={{ fontWeight: 500 }}>{item.t}</span></Badge></span>}
description={<><div>{item.d}</div><div style={{ fontSize: 12, color: '#999', marginTop: 4 }}>{item.time}</div></>}
/>
</List.Item>
)}
/>
);
};
/* ============ 主布局 ============ */
const MainLayout = ({ role, setRole }) => {
const [collapsed, setCollapsed] = useState(false);
const [selectedKey, setSelectedKey] = useState(() => {
const h = window.location.hash.replace('#', '');
if (h) return h;
return '/dashboard';
});
const r = ROLES[role];
const visibleMenus = useMemo(() => {
return ALL_MENUS.filter(m => m.roles.includes(role));
}, [role]);
const userMenuItems = [
{ key: 'profile', icon: <UserOutlined />, label: '个人信息' },
{ key: 'settings', icon: <SettingOutlined />, label: '设置' },
{ type: 'divider' },
{ key: 'switch', icon: <SolutionOutlined />, label: '切换角色' },
{ type: 'divider' },
{ key: 'logout', icon: <LogoutOutlined />, label: '退出登录', danger: true },
];
const handleUserMenuClick = ({ key }) => {
if (key === 'logout' || key === 'switch') setRole(null);
};
const renderPage = () => {
switch (selectedKey) {
case '/dashboard': return <DashboardPage role={role} />;
case '/projects': return <ProjectPage role={role} />;
case '/training': return <TrainingPage role={role} />;
case '/defense': return <DefensePage role={role} />;
case '/audit': return <AuditPage role={role} />;
case '/users': return <UserManagementPage />;
case '/roles': return <RoleManagementPage />;
case '/notifications': return <NotificationPage />;
default: return <DashboardPage role={role} />;
}
};
return (
<Layout style={{ minHeight: '100vh' }}>
<Sider collapsible collapsed={collapsed} onCollapse={setCollapsed} theme="dark">
<div style={{
height: 64, margin: 16, color: '#fff', fontSize: 18, fontWeight: 600,
textAlign: 'center', lineHeight: '32px',
display: 'flex', alignItems: 'center', justifyContent: 'center',
background: 'rgba(255,255,255,0.1)', borderRadius: 8
}}>
{collapsed ? '🎓' : '🎓 实习生训练'}
</div>
<Menu
theme="dark" mode="inline"
selectedKeys={[selectedKey]}
items={visibleMenus.map(m => ({ key: m.key, icon: m.icon, label: m.label }))}
onClick={({ key }) => { setSelectedKey(key); window.location.hash = key; }}
/>
</Sider>
<Layout>
<Header style={{
background: '#fff', padding: '0 24px',
display: 'flex', alignItems: 'center', justifyContent: 'space-between',
boxShadow: '0 1px 4px rgba(0,21,41,.08)'
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
<span style={{ fontSize: 20, fontWeight: 500 }}>👋 欢迎,{r.realName}</span>
<Tag color={r.color}>{r.name}</Tag>
</div>
<Space size={16}>
<Badge count={5}><Button type="text" icon={<BellOutlined />} /></Badge>
<Dropdown menu={{ items: userMenuItems, onClick: handleUserMenuClick }} placement="bottomRight">
<Space style={{ cursor: 'pointer' }}>
<Avatar src={r.avatar} />
<span style={{ fontWeight: 500 }}>{r.realName}</span>
</Space>
</Dropdown>
</Space>
</Header>
{/* 角色快速切换 */}
<div style={{ padding: '12px 16px 0 16px' }}>
<div className="role-switcher">
<span style={{ lineHeight: '32px', marginRight: 8 }}>🎭 快速切换角色:</span>
{Object.entries(ROLES).map(([k, rr]) => (
<div key={k}
className={`role-btn ${role === k ? 'active' : ''}`}
onClick={() => setRole(k)}>
{rr.icon} {rr.name}
</div>
))}
</div>
</div>
<Content className="page-wrap">
{renderPage()}
</Content>
</Layout>
</Layout>
);
};
/* ============ 应用根 ============ */
const App = () => {
// 支持 ?role=STUDENT/MENTOR/SUPERVISOR/ADMIN 直接进入对应角色
const initialRole = (() => {
const params = new URLSearchParams(window.location.search);
const r = params.get('role');
if (r && ROLES[r]) return r;
return null;
})();
const [role, setRole] = useState(initialRole);
if (!role) return <LoginPage onLogin={setRole} />;
return <MainLayout role={role} setRole={setRole} />;
};
ReactDOM.createRoot(document.getElementById('root')).render(<App />);
</script>
</body>
</html>
\ No newline at end of file
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>实习生训练平台 · 原型预览</title>
<script src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script src="https://unpkg.com/antd@5.20.0/dist/antd.min.js"></script>
<script src="https://unpkg.com/@ant-design/icons@5.4.0/dist/index.umd.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/antd@5.20.0/dist/reset.css">
<style>
* { box-sizing: border-box; }
body { margin: 0; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif; background: #f0f2f5; }
.page-wrap { padding: 24px; min-height: calc(100vh - 64px - 48px); background: #f0f2f5; }
.stat-card {
border-radius: 12px;
padding: 20px;
color: white;
position: relative;
overflow: hidden;
box-shadow: 0 4px 12px rgba(0,0,0,0.08);
transition: transform 0.2s;
}
.stat-card:hover { transform: translateY(-3px); }
.stat-card .num { font-size: 32px; font-weight: 700; margin-bottom: 4px; }
.stat-card .label { font-size: 14px; opacity: 0.9; }
.stat-card .icon-bg {
position: absolute; right: -10px; bottom: -10px;
font-size: 80px; opacity: 0.18;
}
.grad-1 { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
.grad-2 { background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); }
.grad-3 { background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); }
.grad-4 { background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%); }
.grad-5 { background: linear-gradient(135deg, #fa709a 0%, #fee140 100%); }
.grad-6 { background: linear-gradient(135deg, #30cfd0 0%, #330867 100%); }
.welcome-banner {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border-radius: 16px;
padding: 32px;
color: white;
margin-bottom: 24px;
position: relative;
overflow: hidden;
}
.welcome-banner h2 { margin: 0 0 8px 0; font-size: 26px; font-weight: 600; }
.welcome-banner p { margin: 0; opacity: 0.9; }
.welcome-banner .decor {
position: absolute; right: 40px; top: 50%; transform: translateY(-50%);
font-size: 120px; opacity: 0.2;
}
.task-item {
padding: 14px 16px;
border-radius: 8px;
border: 1px solid #f0f0f0;
margin-bottom: 10px;
transition: all 0.2s;
cursor: pointer;
}
.task-item:hover {
border-color: #667eea;
box-shadow: 0 2px 8px rgba(102,126,234,0.1);
transform: translateX(4px);
}
.task-item .title { font-weight: 500; margin-bottom: 4px; }
.task-item .meta { font-size: 12px; color: #999; }
.course-card {
border-radius: 12px;
overflow: hidden;
transition: all 0.25s;
cursor: pointer;
border: 1px solid #f0f0f0;
}
.course-card:hover {
transform: translateY(-4px);
box-shadow: 0 8px 24px rgba(0,0,0,0.1);
}
.course-cover {
height: 120px;
display: flex;
align-items: center;
justify-content: center;
color: white;
font-size: 36px;
font-weight: 700;
letter-spacing: 2px;
}
.cover-1 { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
.cover-2 { background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); }
.cover-3 { background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); }
.cover-4 { background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%); }
.cover-5 { background: linear-gradient(135deg, #fa709a 0%, #fee140 100%); }
.cover-6 { background: linear-gradient(135deg, #30cfd0 0%, #330867 100%); }
.cover-7 { background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%); color: #333; }
.cover-8 { background: linear-gradient(135deg, #ff9a9e 0%, #fad0c4 100%); color: #333; }
.project-card {
border-radius: 12px;
padding: 20px;
background: white;
border: 1px solid #f0f0f0;
transition: all 0.25s;
cursor: pointer;
}
.project-card:hover {
transform: translateY(-3px);
box-shadow: 0 6px 20px rgba(0,0,0,0.08);
border-color: #667eea;
}
.role-switcher {
display: flex; gap: 12px; padding: 16px 24px;
background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
border-radius: 12px; margin-bottom: 16px;
}
.role-btn {
padding: 8px 18px; border-radius: 20px; border: 2px solid transparent;
cursor: pointer; font-weight: 500; transition: all 0.2s;
background: white; color: #555;
}
.role-btn:hover { transform: translateY(-2px); }
.role-btn.active {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
box-shadow: 0 4px 12px rgba(102,126,234,0.4);
}
.timeline-item {
padding: 12px 16px;
border-left: 3px solid #667eea;
background: #fafafa;
border-radius: 0 8px 8px 0;
margin-bottom: 12px;
}
.timeline-item .time { font-size: 12px; color: #999; }
.timeline-item .title { font-weight: 500; margin: 4px 0; }
.leaderboard-item {
display: flex; align-items: center; gap: 12px;
padding: 10px 12px; border-radius: 8px;
margin-bottom: 6px; transition: background 0.2s;
}
.leaderboard-item:hover { background: #f5f7ff; }
.rank-badge {
width: 28px; height: 28px; border-radius: 50%;
display: flex; align-items: center; justify-content: center;
font-weight: 700; color: white;
}
.rank-1 { background: linear-gradient(135deg, #ffd700 0%, #ffa500 100%); }
.rank-2 { background: linear-gradient(135deg, #c0c0c0 0%, #808080 100%); }
.rank-3 { background: linear-gradient(135deg, #cd7f32 0%, #8b4513 100%); }
.rank-n { background: #e0e0e0; color: #666; }
</style>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
const { useState, useMemo, useEffect } = React;
const {
Layout, Menu, Dropdown, Avatar, Button, Space, Tag, Spin,
Card, Row, Col, Progress, Table, Badge, Tabs, Statistic,
List, Empty, Divider, Tooltip
} = antd;
const Icons = window['ant-design/icons'];
const {
DashboardOutlined, ProjectOutlined, BookOutlined, AuditOutlined,
BellOutlined, UserOutlined, LogoutOutlined, SettingOutlined,
TeamOutlined, SafetyOutlined, TrophyOutlined, FireOutlined,
RocketOutlined, BulbOutlined, StarOutlined, ThunderboltOutlined,
CrownOutlined, SolutionOutlined, ReadOutlined, CodeOutlined,
CheckCircleOutlined, ClockCircleOutlined, RiseOutlined
} = Icons;
const { Header, Sider, Content } = Layout;
/* ============ 角色配置 ============ */
const ROLES = {
ADMIN: {
name: '系统管理员',
code: 'ADMIN',
color: 'red',
icon: '👑',
realName: '系统管理员',
username: 'admin',
desc: '拥有平台全部权限',
avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=admin'
},
SUPERVISOR: {
name: '部门主管',
code: 'SUPERVISOR',
color: 'orange',
icon: '🛡️',
realName: '张主管',
username: 'supervisor01',
desc: '管理整个部门的培训与项目',
avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=supervisor'
},
MENTOR: {
name: '导师',
code: 'MENTOR',
color: 'blue',
icon: '🎓',
realName: '李导师',
username: 'mentor01',
desc: '指导学员完成项目与答辩',
avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=mentor'
},
STUDENT: {
name: '实习生',
code: 'STUDENT',
color: 'green',
icon: '🚀',
realName: '小王同学',
username: 'student01',
desc: '正在努力成长为合格的工程师',
avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=student'
}
};
/* ============ 菜单配置 ============ */
const ALL_MENUS = [
{ key: '/dashboard', icon: <DashboardOutlined />, label: '工作台', roles: ['ADMIN','SUPERVISOR','MENTOR','STUDENT'] },
{ key: '/projects', icon: <ProjectOutlined />, label: '项目中心', roles: ['ADMIN','SUPERVISOR','MENTOR','STUDENT'] },
{ key: '/training', icon: <BookOutlined />, label: '训练营', roles: ['ADMIN','SUPERVISOR','MENTOR','STUDENT'] },
{ key: '/defense', icon: <AuditOutlined />, label: '答辩中心', roles: ['ADMIN','SUPERVISOR','MENTOR','STUDENT'] },
{ key: '/audit', icon: <SafetyOutlined />, label: '审计中心', roles: ['ADMIN','SUPERVISOR','MENTOR'] },
{ key: '/users', icon: <TeamOutlined />, label: '用户管理', roles: ['ADMIN'] },
{ key: '/roles', icon: <SafetyOutlined />, label: '角色管理', roles: ['ADMIN'] },
{ key: '/notifications', icon: <BellOutlined />, label: '通知中心', roles: ['ADMIN','SUPERVISOR','MENTOR','STUDENT'] },
];
/* ============ 登录页 ============ */
const LoginPage = ({ onLogin }) => {
const [selectedRole, setSelectedRole] = useState('STUDENT');
return (
<div style={{ display: 'flex', minHeight: '100vh', background: '#f0f2f5' }}>
{/* 左侧品牌 */}
<div style={{
flex: 1,
background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
position: 'relative', overflow: 'hidden',
display: 'flex', alignItems: 'center', justifyContent: 'center',
color: 'white'
}}>
<div style={{ position: 'relative', zIndex: 1, textAlign: 'center', padding: 40 }}>
<div style={{ marginBottom: 24 }}>
<div style={{
width: 100, height: 100, borderRadius: 24,
background: 'rgba(255,255,255,0.2)', backdropFilter: 'blur(10px)',
display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
fontSize: 56
}}>🎓</div>
</div>
<h1 style={{ fontSize: 42, fontWeight: 700, marginBottom: 8 }}>实习生训练平台</h1>
<p style={{ fontSize: 18, opacity: 0.9, marginBottom: 48 }}>Intern Training Platform · v2.0</p>
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 20, maxWidth: 500, textAlign: 'left' }}>
<div style={{ background: 'rgba(255,255,255,0.15)', padding: '14px 20px', borderRadius: 12, backdropFilter: 'blur(10px)' }}>
<span style={{ fontSize: 24, marginRight: 12 }}>🎯</span><span>项目实战体系</span>
</div>
<div style={{ background: 'rgba(255,255,255,0.15)', padding: '14px 20px', borderRadius: 12, backdropFilter: 'blur(10px)' }}>
<span style={{ fontSize: 24, marginRight: 12 }}>👥</span><span>导师1V1指导</span>
</div>
<div style={{ background: 'rgba(255,255,255,0.15)', padding: '14px 20px', borderRadius: 12, backdropFilter: 'blur(10px)' }}>
<span style={{ fontSize: 24, marginRight: 12 }}>📚</span><span>系统训练课程</span>
</div>
<div style={{ background: 'rgba(255,255,255,0.15)', padding: '14px 20px', borderRadius: 12, backdropFilter: 'blur(10px)' }}>
<span style={{ fontSize: 24, marginRight: 12 }}>🏆</span><span>能力评估认证</span>
</div>
</div>
</div>
</div>
{/* 右侧角色选择 */}
<div style={{ width: 560, background: 'white', padding: 40, display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
<div style={{ maxWidth: 440, margin: '0 auto', width: '100%' }}>
<h2 style={{ fontSize: 28, fontWeight: 600, marginBottom: 8 }}>选择身份进入 👋</h2>
<p style={{ color: '#666', marginBottom: 32 }}>原型预览:点击下方任一角色即可登录对应视图</p>
{Object.entries(ROLES).map(([key, role]) => (
<div
key={key}
onClick={() => onLogin(key)}
style={{
padding: 20, marginBottom: 16, borderRadius: 12,
border: selectedRole === key ? '2px solid #667eea' : '2px solid #f0f0f0',
cursor: 'pointer', transition: 'all 0.2s',
display: 'flex', alignItems: 'center', gap: 16,
background: selectedRole === key ? '#f5f7ff' : 'white'
}}
onMouseEnter={(e) => { if (selectedRole !== key) e.currentTarget.style.borderColor = '#d0d7e6'; }}
onMouseLeave={(e) => { if (selectedRole !== key) e.currentTarget.style.borderColor = '#f0f0f0'; }}
onClickCapture={() => setSelectedRole(key)}
>
<div style={{
width: 56, height: 56, borderRadius: '50%',
background: role.color === 'red' ? 'linear-gradient(135deg,#ff6b6b,#ee5a6f)' :
role.color === 'orange' ? 'linear-gradient(135deg,#ffa726,#fb8c00)' :
role.color === 'blue' ? 'linear-gradient(135deg,#42a5f5,#1976d2)' :
'linear-gradient(135deg,#66bb6a,#43a047)',
display: 'flex', alignItems: 'center', justifyContent: 'center',
fontSize: 28
}}>{role.icon}</div>
<div style={{ flex: 1 }}>
<div style={{ fontSize: 18, fontWeight: 600 }}>{role.name}</div>
<div style={{ fontSize: 13, color: '#888', marginTop: 2 }}>{role.desc}</div>
</div>
<Tag color={role.color}>{role.code}</Tag>
</div>
))}
<div style={{ textAlign: 'center', marginTop: 24, color: '#999', fontSize: 13 }}>
© 2026 实习生训练平台 · 原型预览
</div>
</div>
</div>
</div>
);
};
/* ============ 工作台 - 不同角色展示不同内容 ============ */
const DashboardPage = ({ role }) => {
const r = ROLES[role];
const isAdmin = role === 'ADMIN';
const isSupervisor = role === 'SUPERVISOR';
const isMentor = role === 'MENTOR';
const isStudent = role === 'STUDENT';
// 不同角色的统计数据
const stats = {
ADMIN: [
{ num: 156, label: '注册用户', icon: '👥', grad: 'grad-1' },
{ num: 42, label: '活跃项目', icon: '📁', grad: 'grad-2' },
{ num: 28, label: '今日登录', icon: '🔐', grad: 'grad-3' },
{ num: 8, label: '待审批', icon: '⏰', grad: 'grad-4' },
],
SUPERVISOR: [
{ num: 23, label: '部门成员', icon: '👥', grad: 'grad-1' },
{ num: 12, label: '进行中项目', icon: '📁', grad: 'grad-2' },
{ num: 5, label: '本周答辩', icon: '🎯', grad: 'grad-3' },
{ num: 3, label: '待审核', icon: '⏰', grad: 'grad-4' },
],
MENTOR: [
{ num: 6, label: '我的学员', icon: '🎓', grad: 'grad-1' },
{ num: 8, label: '指导项目', icon: '📁', grad: 'grad-2' },
{ num: 2, label: '待批改', icon: '📝', grad: 'grad-3' },
{ num: 86, label: '学员平均分', icon: '⭐', grad: 'grad-4' },
],
STUDENT: [
{ num: 12, label: '已学课程', icon: '📚', grad: 'grad-1' },
{ num: 3, label: '进行中项目', icon: '📁', grad: 'grad-2' },
{ num: 78, label: '总学分', icon: '⭐', grad: 'grad-3' },
{ num: 5, label: '待完成', icon: '⏰', grad: 'grad-4' },
]
}[role];
const welcomeMsg = {
ADMIN: '欢迎回来,平台一切运行正常!',
SUPERVISOR: '今天有 3 位学员申请项目答辩,请及时审批。',
MENTOR: '您指导的 6 位学员本周表现都很棒!',
STUDENT: '今天又是充满能量的一天,加油!'
}[role];
return (
<div>
{/* 欢迎横幅 */}
<div className="welcome-banner">
<h2>{r.icon} 你好,{r.realName}</h2>
<p>{welcomeMsg}</p>
<div className="decor">{r.icon}</div>
</div>
{/* 统计卡片 */}
<Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
{stats.map((s, i) => (
<Col xs={24} sm={12} lg={6} key={i}>
<div className={`stat-card ${s.grad}`}>
<div className="num">{s.num}</div>
<div className="label">{s.label}</div>
<div className="icon-bg">{s.icon}</div>
</div>
</Col>
))}
</Row>
<Row gutter={[16, 16]}>
{/* 左侧:进行中任务 */}
<Col xs={24} lg={16}>
<Card title={<><RocketOutlined /> 进行中的任务</>} extra={<a>查看全部</a>}>
{(role === 'STUDENT' ? [
{ t: '完成电商系统订单模块', m: '项目中心 · 截止 2026-07-25', tag: '进行中', color: 'blue' },
{ t: '学习 Spring Cloud 微服务章节', m: '训练营 · 进度 60%', tag: '学习中', color: 'cyan' },
{ t: '准备项目答辩 PPT', m: '答辩中心 · 7月20日 14:00', tag: '待答辩', color: 'orange' },
{ t: '完成前端组件库作业', m: '训练营 · 截止 2026-07-18', tag: '待提交', color: 'red' },
] : role === 'MENTOR' ? [
{ t: '审阅 王同学的电商项目代码', m: '项目中心 · 已分配 2天前', tag: '待批阅', color: 'red' },
{ t: '审阅 李同学的算法作业', m: '训练营 · 已提交', tag: '待批阅', color: 'red' },
{ t: '参加项目答辩评审', m: '答辩中心 · 7月20日 14:00', tag: '已确认', color: 'green' },
{ t: '为新学员制定培养计划', m: '审计中心 · 优先级高', tag: '进行中', color: 'blue' },
] : role === 'SUPERVISOR' ? [
{ t: '审批本周项目立项申请 (3项)', m: '审计中心 · 待审批', tag: '待审批', color: 'red' },
{ t: '审核部门成员答辩评分', m: '答辩中心 · 本周五', tag: '待审核', color: 'orange' },
{ t: '季度培训计划制定', m: '训练营 · 部门级', tag: '进行中', color: 'blue' },
{ t: '查看部门成员周报', m: '项目中心 · 8份未读', tag: '待查看', color: 'purple' },
] : [
{ t: '审核角色权限配置变更', m: '角色管理 · 等待审批', tag: '待审批', color: 'red' },
{ t: '查看系统运行状况报告', m: '审计中心 · 异常 2 项', tag: '需关注', color: 'orange' },
{ t: '审批新增用户账号申请 (5个)', m: '用户管理 · 等待处理', tag: '待审批', color: 'red' },
{ t: '系统数据库备份确认', m: '审计中心 · 每日任务', tag: '已完成', color: 'green' },
]).map((task, i) => (
<div key={i} className="task-item">
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<div className="title">{task.t}</div>
<Tag color={task.color}>{task.tag}</Tag>
</div>
<div className="meta">{task.m}</div>
</div>
))}
</Card>
{/* 学习/项目进度 */}
<Card title={<><RiseOutlined /> {role === 'STUDENT' ? '学习进度' : '项目进度概览'}</>} style={{ marginTop: 16 }}>
{(role === 'STUDENT' ? [
{ name: 'Java 进阶课程', val: 75, color: '#667eea' },
{ name: 'Spring Boot 实战', val: 60, color: '#f093fb' },
{ name: '微服务架构', val: 45, color: '#4facfe' },
{ name: '前端开发基础', val: 90, color: '#43e97b' },
{ name: '数据库设计与优化', val: 70, color: '#fa709a' },
] : role === 'MENTOR' ? [
{ name: '电商系统项目', val: 65, color: '#667eea' },
{ name: '推荐系统项目', val: 40, color: '#f093fb' },
{ name: '在线教育平台', val: 80, color: '#4facfe' },
] : role === 'SUPERVISOR' ? [
{ name: '后端开发部', val: 72, color: '#667eea' },
{ name: '前端开发部', val: 68, color: '#f093fb' },
{ name: '数据工程部', val: 55, color: '#4facfe' },
{ name: '运维部', val: 88, color: '#43e97b' },
] : [
{ name: '平台总体活跃度', val: 78, color: '#667eea' },
{ name: '训练营完成率', val: 65, color: '#f093fb' },
{ name: '项目交付率', val: 82, color: '#4facfe' },
{ name: '用户满意度', val: 91, color: '#43e97b' },
]).map((p, i) => (
<div key={i} style={{ marginBottom: 16 }}>
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
<span>{p.name}</span>
<span style={{ color: '#666' }}>{p.val}%</span>
</div>
<Progress percent={p.val} strokeColor={p.color} showInfo={false} />
</div>
))}
</Card>
</Col>
{/* 右侧:成就/排行榜/动态 */}
<Col xs={24} lg={8}>
{/* 学员成就 */}
{isStudent && (
<Card title={<><TrophyOutlined style={{color:'#faad14'}}/> 我的成就</>} style={{ marginBottom: 16 }}>
<Row gutter={[8, 8]}>
{[
{ e: '🥇', n: '首次答辩', c: 'gold' },
{ e: '🔥', n: '连续7天', c: 'volcano' },
{ e: '💎', n: '优秀学员', c: 'blue' },
{ e: '⭐', n: '满分作业', c: 'purple' },
{ e: '🎯', n: '项目完成', c: 'green' },
{ e: '📚', n: '学霸认证', c: 'magenta' },
].map((a, i) => (
<Col span={8} key={i}>
<div style={{
textAlign: 'center', padding: '14px 0',
background: '#fafafa', borderRadius: 8,
transition: 'transform 0.2s', cursor: 'pointer'
}} onMouseEnter={(e) => e.currentTarget.style.transform = 'scale(1.05)'}
onMouseLeave={(e) => e.currentTarget.style.transform = 'scale(1)'}>
<div style={{ fontSize: 32 }}>{a.e}</div>
<div style={{ fontSize: 12, color: '#666', marginTop: 4 }}>{a.n}</div>
</div>
</Col>
))}
</Row>
</Card>
)}
{/* 排行榜 */}
<Card title={<><FireOutlined style={{color:'#f5222d'}}/> {role === 'STUDENT' ? '学员积分榜' : role === 'MENTOR' ? '导师评分榜' : '部门积分榜'}</>} style={{ marginBottom: 16 }}>
{(role === 'STUDENT' ? [
{ r: 1, n: '王同学', s: 980, t: '98分' },
{ r: 2, n: '李同学', s: 920, t: '92分' },
{ r: 3, n: '张同学', s: 880, t: '88分' },
{ r: 4, n: '赵同学', s: 850, t: '85分' },
{ r: 5, n: '钱同学', s: 820, t: '82分' },
{ r: 6, n: '孙同学', s: 780, t: '78分' },
] : role === 'MENTOR' ? [
{ r: 1, n: '陈导师', s: 96, t: '96分' },
{ r: 2, n: '李导师', s: 94, t: '94分' },
{ r: 3, n: '刘导师', s: 92, t: '92分' },
{ r: 4, n: '黄导师', s: 90, t: '90分' },
] : role === 'SUPERVISOR' ? [
{ r: 1, n: '后端开发部', s: 9200, t: '部门得分' },
{ r: 2, n: '前端开发部', s: 8800, t: '部门得分' },
{ r: 3, n: '数据工程部', s: 8600, t: '部门得分' },
{ r: 4, n: '产品设计部', s: 8200, t: '部门得分' },
] : [
{ r: 1, n: '北京研发中心', s: 9800, t: '基地得分' },
{ r: 2, n: '上海研发分中心', s: 9200, t: '基地得分' },
{ r: 3, n: '深圳研发分中心', s: 8800, t: '基地得分' },
]).map((u, i) => (
<div key={i} className="leaderboard-item">
<div className={`rank-badge rank-${u.r <= 3 ? u.r : 'n'}`}>{u.r}</div>
<div style={{ flex: 1 }}>
<div style={{ fontWeight: 500 }}>{u.n}</div>
<div style={{ fontSize: 12, color: '#999' }}>{u.t}</div>
</div>
<div style={{ fontWeight: 600, color: '#667eea' }}>{u.s}</div>
</div>
))}
</Card>
{/* 最新动态 */}
<Card title={<><BellOutlined /> 最新动态</>}>
{[
{ t: '系统公告', d: '2026-07-16 09:00', c: '平台将进行版本升级' },
{ t: '项目通知', d: '2026-07-15 17:30', c: '您的项目已通过立项审批' },
{ t: '训练营', d: '2026-07-14 14:20', c: '新课程《云原生实战》已上线' },
{ t: '答辩通知', d: '2026-07-13 11:00', c: '本周答辩安排已发布' },
].map((n, i) => (
<div key={i} className="timeline-item">
<div className="time">{n.d}</div>
<div className="title">{n.t}</div>
<div style={{ fontSize: 13, color: '#666' }}>{n.c}</div>
</div>
))}
</Card>
</Col>
</Row>
</div>
);
};
/* ============ 项目中心 ============ */
const ProjectPage = ({ role }) => {
const projects = [
{ name: '电商系统订单模块', tech: ['Spring Boot','MySQL','Redis'], status: '进行中', progress: 65, mentor: '李导师', members: ['王同学','张同学','李同学'] },
{ name: '推荐算法系统', tech: ['Python','TensorFlow'], status: '进行中', progress: 40, mentor: '陈导师', members: ['赵同学'] },
{ name: '在线教育平台', tech: ['Vue','Node.js'], status: '已交付', progress: 100, mentor: '刘导师', members: ['钱同学','孙同学'] },
{ name: '智能客服机器人', tech: ['NLP','Flask'], status: '待评审', progress: 90, mentor: '李导师', members: ['周同学'] },
{ name: '移动端App开发', tech: ['React Native'], status: '进行中', progress: 55, mentor: '黄导师', members: ['王同学','陈同学'] },
{ name: '数据分析平台', tech: ['Spark','Hadoop'], status: '已立项', progress: 10, mentor: '陈导师', members: ['李同学'] },
];
return (
<div>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
<h2 style={{ margin: 0 }}>📁 项目中心</h2>
{(role === 'ADMIN' || role === 'SUPERVISOR' || role === 'STUDENT') && (
<Button type="primary" icon={<RocketOutlined />}>新建项目</Button>
)}
</div>
<Row gutter={[16, 16]}>
{projects.map((p, i) => (
<Col xs={24} md={12} lg={8} key={i}>
<div className="project-card">
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 12 }}>
<h3 style={{ margin: 0, fontSize: 16 }}>{p.name}</h3>
<Tag color={p.status === '已交付' ? 'green' : p.status === '进行中' ? 'blue' : p.status === '待评审' ? 'orange' : 'default'}>{p.status}</Tag>
</div>
<Space size={4} wrap style={{ marginBottom: 12 }}>
{p.tech.map((t, j) => <Tag key={j}>{t}</Tag>)}
</Space>
<Progress percent={p.progress} strokeColor={{ '0%': '#667eea', '100%': '#764ba2' }} />
<Divider style={{ margin: '12px 0' }} />
<div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13, color: '#666' }}>
<span>👨‍🏫 {p.mentor}</span>
<span>👥 {p.members.length} 人</span>
</div>
<div style={{ marginTop: 8 }}>
<Avatar.Group size="small">
{p.members.map((m, k) => (
<Tooltip key={k} title={m}>
<Avatar style={{ backgroundColor: '#' + Math.random().toString(16).slice(2,8) }}>{m[0]}</Avatar>
</Tooltip>
))}
</Avatar.Group>
</div>
</div>
</Col>
))}
</Row>
</div>
);
};
/* ============ 训练营 ============ */
const TrainingPage = ({ role }) => {
const courses = [
{ n: 'Java 进阶:并发编程', t: '李导师', dur: '24学时', level: '进阶', c: 'cover-1', tag: '热门' },
{ n: 'Spring Cloud 微服务实战', t: '陈导师', dur: '36学时', level: '高级', c: 'cover-2', tag: '推荐' },
{ n: 'MySQL 性能优化', t: '刘导师', dur: '18学时', level: '进阶', c: 'cover-3' },
{ n: 'React Hooks 深入', t: '黄导师', dur: '20学时', level: '中级', c: 'cover-4', tag: '新课' },
{ n: 'Python 数据分析', t: '陈导师', dur: '30学时', level: '入门', c: 'cover-5' },
{ n: 'Docker 与 Kubernetes', t: '李导师', dur: '28学时', level: '高级', c: 'cover-6', tag: '热门' },
{ n: '系统设计与架构', t: '陈导师', dur: '40学时', level: '高级', c: 'cover-7' },
{ n: '前端性能优化', t: '黄导师', dur: '16学时', level: '中级', c: 'cover-8' },
];
return (
<div>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
<h2 style={{ margin: 0 }}>📚 训练营</h2>
{(role === 'ADMIN' || role === 'SUPERVISOR' || role === 'MENTOR') && (
<Button type="primary" icon={<BulbOutlined />}>发布课程</Button>
)}
</div>
<Row gutter={[16, 16]}>
{courses.map((c, i) => (
<Col xs={24} sm={12} md={8} lg={6} key={i}>
<div className="course-card">
<div className={`course-cover ${c.c}`}>
{c.tag && <Tag color="gold" style={{position:'absolute',right:8,top:8}}>{c.tag}</Tag>}
<div style={{ textAlign: 'center' }}>
<CodeOutlined style={{ fontSize: 36, display: 'block', marginBottom: 4 }} />
<div style={{ fontSize: 14 }}>{c.n}</div>
</div>
</div>
<div style={{ padding: 16 }}>
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
<Tag color="blue">{c.level}</Tag>
<span style={{ fontSize: 12, color: '#999' }}>⏱ {c.dur}</span>
</div>
<div style={{ fontSize: 13, color: '#666' }}>👨‍🏫 {c.t}</div>
<Button type="primary" block style={{ marginTop: 12 }}>
{role === 'STUDENT' ? '开始学习' : '查看详情'}
</Button>
</div>
</div>
</Col>
))}
</Row>
</div>
);
};
/* ============ 答辩中心 ============ */
const DefensePage = ({ role }) => {
const data = [
{ name: '电商系统订单模块', student: '王同学', mentor: '李导师', date: '2026-07-20 14:00', status: '待答辩', score: '-' },
{ name: '推荐算法系统', student: '赵同学', mentor: '陈导师', date: '2026-07-21 10:00', status: '待答辩', score: '-' },
{ name: '智能客服机器人', student: '周同学', mentor: '李导师', date: '2026-07-18 15:00', status: '已答辩', score: 92 },
{ name: '在线教育平台', student: '钱同学', mentor: '刘导师', date: '2026-07-15 14:00', status: '已答辩', score: 88 },
];
const columns = [
{ title: '项目名称', dataIndex: 'name' },
{ title: role === 'STUDENT' ? '我的' : '学员', dataIndex: 'student' },
{ title: '导师', dataIndex: 'mentor' },
{ title: '答辩时间', dataIndex: 'date' },
{ title: '状态', dataIndex: 'status', render: s => <Tag color={s === '已答辩' ? 'green' : 'blue'}>{s}</Tag> },
{ title: '评分', dataIndex: 'score' },
{
title: '操作', render: (_, r) => (
<Space>
{role === 'MENTOR' && r.status === '待答辩' && <Button type="primary" size="small">评分</Button>}
{role === 'SUPERVISOR' && r.status === '待答辩' && <Button size="small">审核</Button>}
{role === 'STUDENT' && r.status === '待答辩' && <Button type="primary" size="small">进入答辩</Button>}
<Button size="small">详情</Button>
</Space>
)
}
];
return (
<Card title="🎯 答辩中心">
<Table dataSource={data} columns={columns} pagination={false} />
</Card>
);
};
/* ============ 审计中心 ============ */
const AuditPage = ({ role }) => {
if (role === 'STUDENT') return <Empty description="您无权访问此模块" />;
const data = [
{ t: '用户:student01 创建项目', u: 'student01', time: '2026-07-16 14:23', type: '项目', status: 'success' },
{ t: '用户:mentor01 批阅作业', u: 'mentor01', time: '2026-07-16 11:05', type: '教学', status: 'success' },
{ t: '用户:supervisor01 审批答辩', u: 'supervisor01', time: '2026-07-16 09:30', type: '审批', status: 'success' },
{ t: '系统:异常登录尝试 (3次)', u: 'system', time: '2026-07-15 23:14', type: '安全', status: 'warning' },
{ t: '用户:admin 修改角色权限', u: 'admin', time: '2026-07-15 17:00', type: '系统', status: 'danger' },
{ t: '用户:student03 提交作业', u: 'student03', time: '2026-07-15 14:20', type: '教学', status: 'success' },
];
const columns = [
{ title: '操作', dataIndex: 't' },
{ title: '操作人', dataIndex: 'u' },
{ title: '时间', dataIndex: 'time' },
{ title: '类型', dataIndex: 'type', render: t => <Tag>{t}</Tag> },
{ title: '状态', dataIndex: 'status', render: s => <Badge status={s} text={s === 'success' ? '正常' : s === 'warning' ? '警告' : '严重'} /> },
];
return (
<div>
<Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
<Col span={6}><div className="stat-card grad-3"><div className="num">1,248</div><div className="label">今日操作总数</div><div className="icon-bg">📊</div></div></Col>
<Col span={6}><div className="stat-card grad-2"><div className="num">12</div><div className="label">异常事件</div><div className="icon-bg">⚠️</div></div></Col>
<Col span={6}><div className="stat-card grad-4"><div className="num">98%</div><div className="label">操作成功率</div><div className="icon-bg">✅</div></div></Col>
<Col span={6}><div className="stat-card grad-1"><div className="num">86</div><div className="label">活跃用户</div><div className="icon-bg">👥</div></div></Col>
</Row>
<Card title="🛡️ 操作审计日志">
<Table dataSource={data} columns={columns} pagination={false} />
</Card>
</div>
);
};
/* ============ 用户管理(仅ADMIN) ============ */
const UserManagementPage = () => {
const data = [
{ id: 1, username: 'admin', realName: '系统管理员', role: 'ADMIN', dept: '总部', status: '正常', last: '2分钟前' },
{ id: 2, username: 'supervisor01', realName: '张主管', role: 'SUPERVISOR', dept: '后端部', status: '正常', last: '1小时前' },
{ id: 3, username: 'mentor01', realName: '李导师', role: 'MENTOR', dept: '后端部', status: '正常', last: '10分钟前' },
{ id: 4, username: 'student01', realName: '王同学', role: 'STUDENT', dept: '后端部', status: '正常', last: '5分钟前' },
{ id: 5, username: 'student02', realName: '赵同学', role: 'STUDENT', dept: '前端部', status: '禁用', last: '3天前' },
];
const columns = [
{ title: 'ID', dataIndex: 'id' },
{ title: '用户名', dataIndex: 'username' },
{ title: '姓名', dataIndex: 'realName' },
{ title: '角色', dataIndex: 'role', render: r => {
const c = { ADMIN: 'red', SUPERVISOR: 'orange', MENTOR: 'blue', STUDENT: 'green' };
return <Tag color={c[r]}>{r}</Tag>;
}},
{ title: '部门', dataIndex: 'dept' },
{ title: '状态', dataIndex: 'status', render: s => <Badge status={s === '正常' ? 'success' : 'error'} text={s} /> },
{ title: '最后登录', dataIndex: 'last' },
{ title: '操作', render: () => <Space><Button size="small">编辑</Button><Button size="small" danger>禁用</Button></Space> },
];
return (
<Card title="👥 用户管理" extra={<Button type="primary">+ 新建用户</Button>}>
<Table dataSource={data} columns={columns} pagination={false} />
</Card>
);
};
/* ============ 角色管理(仅ADMIN) ============ */
const RoleManagementPage = () => {
const data = [
{ name: 'ADMIN', code: '系统管理员', count: 1, perms: 24, desc: '拥有全部权限' },
{ name: 'SUPERVISOR', code: '部门主管', count: 3, perms: 18, desc: '管理部门事务' },
{ name: 'MENTOR', code: '导师', count: 8, perms: 14, desc: '指导学员' },
{ name: 'STUDENT', code: '实习生', count: 144, perms: 6, desc: '学习与项目' },
];
return (
<Row gutter={[16, 16]}>
{data.map((r, i) => (
<Col xs={24} sm={12} lg={6} key={i}>
<Card hoverable>
<div style={{ textAlign: 'center' }}>
<div style={{
width: 64, height: 64, borderRadius: '50%',
background: r.name === 'ADMIN' ? 'linear-gradient(135deg,#ff6b6b,#ee5a6f)' :
r.name === 'SUPERVISOR' ? 'linear-gradient(135deg,#ffa726,#fb8c00)' :
r.name === 'MENTOR' ? 'linear-gradient(135deg,#42a5f5,#1976d2)' :
'linear-gradient(135deg,#66bb6a,#43a047)',
margin: '0 auto 16px', display: 'flex', alignItems: 'center', justifyContent: 'center',
fontSize: 28, color: 'white', fontWeight: 700
}}>{r.name[0]}</div>
<h3 style={{ margin: 0 }}>{r.code}</h3>
<Tag style={{ marginTop: 8 }}>{r.name}</Tag>
<div style={{ marginTop: 16, color: '#666', fontSize: 13 }}>{r.desc}</div>
<Divider />
<Row>
<Col span={12}><Statistic title="用户数" value={r.count} valueStyle={{fontSize:20,color:'#667eea'}} /></Col>
<Col span={12}><Statistic title="权限数" value={r.perms} valueStyle={{fontSize:20,color:'#f5576c'}} /></Col>
</Row>
<Button block style={{ marginTop: 16 }}>配置权限</Button>
</div>
</Card>
</Col>
))}
</Row>
);
};
/* ============ 通知中心 ============ */
const NotificationPage = () => {
return (
<List
itemLayout="horizontal"
dataSource={[
{ t: '🎉 新课程上线通知', d: '《云原生实战》课程已上线,立即学习', time: '2小时前', read: false },
{ t: '📝 答辩安排通知', d: '您的项目答辩已安排在 7月20日 14:00', time: '5小时前', read: false },
{ t: '✅ 项目审批通过', d: '您的项目《电商系统订单模块》已通过立项审批', time: '1天前', read: true },
{ t: '🎯 训练营通知', d: '您的导师已为您分配新的学习任务', time: '2天前', read: true },
]}
renderItem={item => (
<List.Item style={{ background: item.read ? 'white' : '#f0f5ff', padding: 16, borderRadius: 8, marginBottom: 8 }}>
<List.Item.Meta
title={<span><Badge dot={!item.read}><span style={{ fontWeight: 500 }}>{item.t}</span></Badge></span>}
description={<><div>{item.d}</div><div style={{ fontSize: 12, color: '#999', marginTop: 4 }}>{item.time}</div></>}
/>
</List.Item>
)}
/>
);
};
/* ============ 主布局 ============ */
const MainLayout = ({ role, setRole }) => {
const [collapsed, setCollapsed] = useState(false);
const [selectedKey, setSelectedKey] = useState(() => {
const h = window.location.hash.replace('#', '');
if (h) return h;
return '/dashboard';
});
const r = ROLES[role];
const visibleMenus = useMemo(() => {
return ALL_MENUS.filter(m => m.roles.includes(role));
}, [role]);
const userMenuItems = [
{ key: 'profile', icon: <UserOutlined />, label: '个人信息' },
{ key: 'settings', icon: <SettingOutlined />, label: '设置' },
{ type: 'divider' },
{ key: 'switch', icon: <SolutionOutlined />, label: '切换角色' },
{ type: 'divider' },
{ key: 'logout', icon: <LogoutOutlined />, label: '退出登录', danger: true },
];
const handleUserMenuClick = ({ key }) => {
if (key === 'logout' || key === 'switch') setRole(null);
};
const renderPage = () => {
switch (selectedKey) {
case '/dashboard': return <DashboardPage role={role} />;
case '/projects': return <ProjectPage role={role} />;
case '/training': return <TrainingPage role={role} />;
case '/defense': return <DefensePage role={role} />;
case '/audit': return <AuditPage role={role} />;
case '/users': return <UserManagementPage />;
case '/roles': return <RoleManagementPage />;
case '/notifications': return <NotificationPage />;
default: return <DashboardPage role={role} />;
}
};
return (
<Layout style={{ minHeight: '100vh' }}>
<Sider collapsible collapsed={collapsed} onCollapse={setCollapsed} theme="dark">
<div style={{
height: 64, margin: 16, color: '#fff', fontSize: 18, fontWeight: 600,
textAlign: 'center', lineHeight: '32px',
display: 'flex', alignItems: 'center', justifyContent: 'center',
background: 'rgba(255,255,255,0.1)', borderRadius: 8
}}>
{collapsed ? '🎓' : '🎓 实习生训练'}
</div>
<Menu
theme="dark" mode="inline"
selectedKeys={[selectedKey]}
items={visibleMenus.map(m => ({ key: m.key, icon: m.icon, label: m.label }))}
onClick={({ key }) => { setSelectedKey(key); window.location.hash = key; }}
/>
</Sider>
<Layout>
<Header style={{
background: '#fff', padding: '0 24px',
display: 'flex', alignItems: 'center', justifyContent: 'space-between',
boxShadow: '0 1px 4px rgba(0,21,41,.08)'
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
<span style={{ fontSize: 20, fontWeight: 500 }}>👋 欢迎,{r.realName}</span>
<Tag color={r.color}>{r.name}</Tag>
</div>
<Space size={16}>
<Badge count={5}><Button type="text" icon={<BellOutlined />} /></Badge>
<Dropdown menu={{ items: userMenuItems, onClick: handleUserMenuClick }} placement="bottomRight">
<Space style={{ cursor: 'pointer' }}>
<Avatar src={r.avatar} />
<span style={{ fontWeight: 500 }}>{r.realName}</span>
</Space>
</Dropdown>
</Space>
</Header>
{/* 角色快速切换 */}
<div style={{ padding: '12px 16px 0 16px' }}>
<div className="role-switcher">
<span style={{ lineHeight: '32px', marginRight: 8 }}>🎭 快速切换角色:</span>
{Object.entries(ROLES).map(([k, rr]) => (
<div key={k}
className={`role-btn ${role === k ? 'active' : ''}`}
onClick={() => setRole(k)}>
{rr.icon} {rr.name}
</div>
))}
</div>
</div>
<Content className="page-wrap">
{renderPage()}
</Content>
</Layout>
</Layout>
);
};
/* ============ 应用根 ============ */
const App = () => {
// 支持 ?role=STUDENT/MENTOR/SUPERVISOR/ADMIN 直接进入对应角色
const initialRole = (() => {
const params = new URLSearchParams(window.location.search);
const r = params.get('role');
if (r && ROLES[r]) return r;
return null;
})();
const [role, setRole] = useState(initialRole);
if (!role) return <LoginPage onLogin={setRole} />;
return <MainLayout role={role} setRole={setRole} />;
};
ReactDOM.createRoot(document.getElementById('root')).render(<App />);
</script>
</body>
</html>
\ No newline at end of file
import { BrowserRouter, Routes, Route, Navigate, useLocation, useNavigate } from 'react-router-dom';
import { Layout, Menu, Dropdown, Avatar, Button, Space } from 'antd';
import { Layout, Menu, Dropdown, Avatar, Button, Space, Tag, Spin } from 'antd';
import type { MenuProps } from 'antd';
import {
DashboardOutlined,
......@@ -10,26 +10,37 @@ import {
UserOutlined,
LogoutOutlined,
SettingOutlined,
TeamOutlined,
SafetyOutlined,
} from '@ant-design/icons';
import { useState, useEffect } from 'react';
import { useState, useEffect, useMemo } from 'react';
import DashboardPage from './pages/DashboardPage';
import StudentDashboard from './pages/StudentDashboard';
import MentorDashboard from './pages/MentorDashboard';
import SupervisorDashboard from './pages/SupervisorDashboard';
import ProjectPage from './pages/ProjectPage';
import TrainingPage from './pages/TrainingPage';
import DefensePage from './pages/DefensePage';
import AuditPage from './pages/AuditPage';
import NotificationPage from './pages/NotificationPage';
import LoginPage from './pages/LoginPage';
import UserManagementPage from './pages/UserManagementPage';
import RoleManagementPage from './pages/RoleManagementPage';
import { useAuthStore } from './stores/useAuthStore';
import { PERMISSION_CODES, ROLE_NAMES } from './services/permissionApi';
const { Header, Sider, Content } = Layout;
const menuItems = [
{ key: '/dashboard', icon: <DashboardOutlined />, label: '工作台' },
{ key: '/projects', icon: <ProjectOutlined />, label: '项目中心' },
{ key: '/training', icon: <BookOutlined />, label: '训练营' },
{ key: '/defense', icon: <AuditOutlined />, label: '答辩' },
{ key: '/audit', icon: <AuditOutlined />, label: '审计' },
{ key: '/notifications', icon: <BellOutlined />, label: '通知' },
// 菜单配置 - 不在这里做权限控制,统一在页面组件中处理
const menuConfigs = [
{ key: '/dashboard', icon: <DashboardOutlined />, label: '工作台', path: '/dashboard' },
{ key: '/projects', icon: <ProjectOutlined />, label: '项目中心', path: '/projects' },
{ key: '/training', icon: <BookOutlined />, label: '训练营', path: '/training' },
{ key: '/defense', icon: <AuditOutlined />, label: '答辩', path: '/defense' },
{ key: '/audit', icon: <AuditOutlined />, label: '审计', path: '/audit' },
{ key: '/users', icon: <TeamOutlined />, label: '用户管理', path: '/users' },
{ key: '/roles', icon: <SafetyOutlined />, label: '角色管理', path: '/roles' },
{ key: '/notifications', icon: <BellOutlined />, label: '通知', path: '/notifications' },
];
// 受保护的路由组件
......@@ -59,14 +70,85 @@ const PublicRoute: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const MainLayout: React.FC = () => {
const [collapsed, setCollapsed] = useState(false);
const [selectedKey, setSelectedKey] = useState('/dashboard');
const { user, logout } = useAuthStore();
const { user, logout, isLoading, loadPermissions, permissions } = useAuthStore();
const location = useLocation();
const navigate = useNavigate();
// 加载权限
useEffect(() => {
loadPermissions();
}, []);
// 根据用户角色过滤菜单
const visibleMenus = useMemo(() => {
if (!user) return [];
const roles = user.roles || [];
const isAdmin = roles.includes('ADMIN');
const isSupervisor = roles.includes('SUPERVISOR');
const isMentor = roles.includes('MENTOR');
const isStudent = roles.includes('STUDENT');
return menuConfigs.filter((menu) => {
// 工作台 - 根据角色显示不同入口
if (menu.key === '/dashboard') {
return true;
}
// 用户管理和角色管理 - 仅管理员可见
if (menu.key === '/users' || menu.key === '/roles') {
return isAdmin;
}
// 审计页面 - 导师、主管、管理员可见
if (menu.key === '/audit') {
return isAdmin || isSupervisor || isMentor;
}
// 项目中心 - 所有人可见
if (menu.key === '/projects') {
return true;
}
// 训练营 - 导师、学员可见(主管、管理员也可查看全部)
if (menu.key === '/training') {
return isAdmin || isSupervisor || isMentor || isStudent;
}
// 答辩 - 导师、学员可见(主管可审核)
if (menu.key === '/defense') {
return isAdmin || isSupervisor || isMentor || isStudent;
}
// 通知 - 所有人可见
if (menu.key === '/notifications') {
return true;
}
return false;
});
}, [user]);
useEffect(() => {
setSelectedKey(location.pathname);
}, [location.pathname]);
// 角色标签颜色
const getRoleColor = (role: string): string => {
switch (role) {
case 'ADMIN':
return 'red';
case 'SUPERVISOR':
return 'orange';
case 'MENTOR':
return 'blue';
case 'STUDENT':
return 'green';
default:
return 'default';
}
};
const userMenuItems: MenuProps['items'] = [
{
key: 'profile',
......@@ -96,9 +178,34 @@ const MainLayout: React.FC = () => {
}
};
const handleMenuClick = (e: { key: string }) => {
setSelectedKey(e.key);
navigate(e.key);
};
// 等待权限加载完成
if (isLoading || permissions.length === 0) {
return (
<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
<Spin size="large" tip="加载中..." />
</div>
);
}
return (
<Layout style={{ minHeight: '100vh' }}>
<Sider collapsible collapsed={collapsed} onCollapse={setCollapsed}>
<Layout style={{ minHeight: '100vh', height: '100vh', overflow: 'hidden' }}>
<Sider
collapsible
collapsed={collapsed}
onCollapse={setCollapsed}
style={{
overflow: 'auto',
height: '100vh',
position: 'sticky',
top: 0,
left: 0,
}}
>
<div
style={{
height: 64,
......@@ -123,14 +230,15 @@ const MainLayout: React.FC = () => {
theme="dark"
mode="inline"
selectedKeys={[selectedKey]}
items={menuItems}
onClick={(e) => {
setSelectedKey(e.key);
navigate(e.key);
}}
items={visibleMenus.map((menu) => ({
key: menu.key,
icon: menu.icon,
label: menu.label,
}))}
onClick={handleMenuClick}
/>
</Sider>
<Layout>
<Layout style={{ overflow: 'hidden' }}>
<Header
style={{
background: '#fff',
......@@ -139,9 +247,19 @@ const MainLayout: React.FC = () => {
alignItems: 'center',
justifyContent: 'space-between',
boxShadow: '0 1px 4px rgba(0,21,41,.08)',
position: 'sticky',
top: 0,
zIndex: 10,
}}
>
<span style={{ fontSize: 20, fontWeight: 500 }}>实习生训练平台 · MVP</span>
<div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
<span style={{ fontSize: 20, fontWeight: 500 }}>实习生训练平台</span>
{user?.roles?.map((role) => (
<Tag key={role} color={getRoleColor(role)}>
{ROLE_NAMES[role] || role}
</Tag>
))}
</div>
<Space size={16}>
<Button type="text" icon={<BellOutlined />} />
<Dropdown
......@@ -149,10 +267,7 @@ const MainLayout: React.FC = () => {
placement="bottomRight"
>
<Space style={{ cursor: 'pointer' }}>
<Avatar
style={{ backgroundColor: '#667eea' }}
icon={<UserOutlined />}
/>
<Avatar style={{ backgroundColor: '#667eea' }} icon={<UserOutlined />} />
<span style={{ fontWeight: 500 }}>
{user?.realName || user?.username || '用户'}
</span>
......@@ -166,15 +281,23 @@ const MainLayout: React.FC = () => {
padding: 24,
background: '#fff',
borderRadius: 8,
minHeight: 'calc(100vh - 112px)',
overflow: 'auto',
height: 'calc(100vh - 64px)',
}}
>
{selectedKey === '/dashboard' && <DashboardPage />}
{selectedKey === '/projects' && <ProjectPage />}
{selectedKey === '/training' && <TrainingPage />}
{selectedKey === '/defense' && <DefensePage />}
{selectedKey === '/audit' && <AuditPage />}
{selectedKey === '/notifications' && <NotificationPage />}
<Routes>
<Route path="/dashboard" element={<DashboardPage />} />
<Route path="/student-dashboard" element={<StudentDashboard />} />
<Route path="/mentor-dashboard" element={<MentorDashboard />} />
<Route path="/supervisor-dashboard" element={<SupervisorDashboard />} />
<Route path="/projects" element={<ProjectPage />} />
<Route path="/training" element={<TrainingPage />} />
<Route path="/defense" element={<DefensePage />} />
<Route path="/audit" element={<AuditPage />} />
<Route path="/users" element={<UserManagementPage />} />
<Route path="/roles" element={<RoleManagementPage />} />
<Route path="/notifications" element={<NotificationPage />} />
</Routes>
</Content>
</Layout>
</Layout>
......@@ -185,7 +308,6 @@ export default function App() {
return (
<BrowserRouter>
<Routes>
{/* 公共路由 */}
<Route
path="/login"
element={
......@@ -194,8 +316,6 @@ export default function App() {
</PublicRoute>
}
/>
{/* 受保护的路由 */}
<Route
path="/*"
element={
......@@ -204,8 +324,6 @@ export default function App() {
</ProtectedRoute>
}
/>
{/* 默认重定向 */}
<Route path="/" element={<Navigate to="/dashboard" replace />} />
<Route path="*" element={<Navigate to="/dashboard" replace />} />
</Routes>
......
/**
* 权限组件 - 按钮级权限控制
*/
import { FC, ReactNode } from 'react';
import { usePermission } from '../stores/usePermission';
interface HasPermissionProps {
/**
* 权限码
*/
permission: string;
/**
* 子元素
*/
children: ReactNode;
/**
* 无权限时显示的替代内容
*/
fallback?: ReactNode;
/**
* 显示模式:any=任一权限, all=所有权限
*/
mode?: 'any' | 'all';
}
interface HasRoleProps {
/**
* 角色码
*/
role: string;
/**
* 子元素
*/
children: ReactNode;
/**
* 无角色时显示的替代内容
*/
fallback?: ReactNode;
}
/**
* 权限控制组件 - 检查用户是否有指定权限
*/
export const HasPermission: FC<HasPermissionProps> = ({
permission,
children,
fallback = null,
}) => {
const { hasPermission } = usePermission();
if (hasPermission(permission)) {
return <>{children}</>;
}
return <>{fallback}</>;
};
/**
* 权限控制组件 - 检查用户是否有多个权限中的任一权限
*/
export const HasAnyPermission: FC<HasPermissionProps & { permissions: string[] }> = ({
permissions,
children,
fallback = null,
}) => {
const { hasAnyPermission } = usePermission();
if (hasAnyPermission(...permissions)) {
return <>{children}</>;
}
return <>{fallback}</>;
};
/**
* 角色控制组件 - 检查用户是否有指定角色
*/
export const HasRole: FC<HasRoleProps> = ({
role,
children,
fallback = null,
}) => {
const { hasRole } = usePermission();
if (hasRole(role)) {
return <>{children}</>;
}
return <>{fallback}</>;
};
/**
* 角色控制组件 - 检查用户是否有多个角色中的任一角色
*/
export const HasAnyRole: FC<HasRoleProps & { roles: string[] }> = ({
roles,
children,
fallback = null,
}) => {
const { user } = usePermission() as any;
if (roles.some((r) => user?.roles?.includes(r))) {
return <>{children}</>;
}
return <>{fallback}</>;
};
/**
* 权限控制组件 - 仅管理员可见
*/
export const AdminOnly: FC<{ children: ReactNode; fallback?: ReactNode }> = ({
children,
fallback = null,
}) => {
const { isAdmin } = usePermission();
if (isAdmin()) {
return <>{children}</>;
}
return <>{fallback}</>;
};
/**
* 权限控制组件 - 仅主管可见
*/
export const SupervisorOnly: FC<{ children: ReactNode; fallback?: ReactNode }> = ({
children,
fallback = null,
}) => {
const { isSupervisor } = usePermission();
if (isSupervisor()) {
return <>{children}</>;
}
return <>{fallback}</>;
};
/**
* 权限控制组件 - 仅导师可见
*/
export const MentorOnly: FC<{ children: ReactNode; fallback?: ReactNode }> = ({
children,
fallback = null,
}) => {
const { isMentor } = usePermission();
if (isMentor()) {
return <>{children}</>;
}
return <>{fallback}</>;
};
/**
* 权限控制组件 - 仅学员可见
*/
export const StudentOnly: FC<{ children: ReactNode; fallback?: ReactNode }> = ({
children,
fallback = null,
}) => {
const { isStudent } = usePermission();
if (isStudent()) {
return <>{children}</>;
}
return <>{fallback}</>;
};
......@@ -15,6 +15,11 @@ html, body, #root {
flex-direction: column;
}
/* 防止整个页面出现滚动条 */
body {
overflow: hidden;
}
/* 全局滚动条样式 */
::-webkit-scrollbar {
width: 6px;
......
import { Empty } from 'antd';
import { Card, Row, Col, Table, Tag, Timeline, Statistic, List, Avatar, Space, Button, Divider, Typography, Progress, Badge, Tabs, Select, DatePicker, Drawer, Descriptions, Progress as AntdProgress } from 'antd';
import {
HistoryOutlined,
UserOutlined,
TeamOutlined,
RiseOutlined,
TrophyOutlined,
ClockCircleOutlined,
FileTextOutlined,
CalendarOutlined,
FireOutlined,
BulbOutlined,
CheckCircleOutlined,
GlobalOutlined,
DatabaseOutlined,
CodeOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { useState } from 'react';
import { useAuthStore } from '../stores/useAuthStore';
import { PERMISSION_CODES } from '../services/permissionApi';
const { Text, Title, Paragraph } = Typography;
type HistoryItem = {
id: number;
student: string;
training: string;
difficulty: string;
score: number;
mentor: string;
startDate: string;
endDate: string;
status: 'completed' | 'ongoing';
};
type StudentProfile = {
id: number;
name: string;
department: string;
avatar?: string;
overall: number;
skills: Array<{
name: string;
score: number;
icon: React.ReactNode;
}>;
strengths: string[];
weaknesses: string[];
recentTrainings: Array<{
name: string;
score: number;
date: string;
}>;
};
export default function AuditPage() {
return <Empty description="审计 - 待接入" />;
const { user, permissions } = useAuthStore();
const [activeTab, setActiveTab] = useState('history');
const [selectedProfile, setSelectedProfile] = useState<StudentProfile | null>(null);
const [drawerVisible, setDrawerVisible] = useState(false);
// 判断角色
const roles = user?.roles || [];
const isStudent = roles.includes('STUDENT');
const isMentor = roles.includes('MENTOR');
const isSupervisor = roles.includes('SUPERVISOR');
const isAdmin = roles.includes('ADMIN');
// 权限判断
const canViewOwn = permissions.includes(PERMISSION_CODES.HISTORY_VIEW_OWN);
const canViewDepartment = permissions.includes(PERMISSION_CODES.HISTORY_VIEW_DEPARTMENT);
const canViewAll = permissions.includes(PERMISSION_CODES.HISTORY_VIEW_ALL);
const canViewProfile = permissions.includes(PERMISSION_CODES.PROFILE_VIEW);
// 我的历史记录(学员视角)
const myHistory: HistoryItem[] = [
{
id: 1,
student: user?.realName || '我',
training: '企业内部管理系统',
difficulty: 'L3',
score: 92,
mentor: '张导师',
startDate: '2026-06-01',
endDate: '2026-06-30',
status: 'completed',
},
{
id: 2,
student: user?.realName || '我',
training: 'RESTful API设计',
difficulty: 'L2',
score: 88,
mentor: '张导师',
startDate: '2026-05-15',
endDate: '2026-05-30',
status: 'completed',
},
{
id: 3,
student: user?.realName || '我',
training: '数据可视化看板',
difficulty: 'L2',
score: 85,
mentor: '王导师',
startDate: '2026-04-01',
endDate: '2026-04-28',
status: 'completed',
},
];
// 全部历史记录(主管/管理员视角)
const allHistory: HistoryItem[] = [
{
id: 1,
student: '王芳',
training: '企业内部管理系统',
difficulty: 'L3',
score: 95,
mentor: '张导师',
startDate: '2026-06-01',
endDate: '2026-06-30',
status: 'completed',
},
{
id: 2,
student: '李明',
training: '电商平台用户模块',
difficulty: 'L3',
score: 88,
mentor: '张导师',
startDate: '2026-07-10',
endDate: '2026-07-25',
status: 'ongoing',
},
{
id: 3,
student: '张伟',
training: '数据可视化看板',
difficulty: 'L2',
score: 90,
mentor: '王导师',
startDate: '2026-05-15',
endDate: '2026-05-30',
status: 'completed',
},
{
id: 4,
student: '刘洋',
training: '微服务架构实战',
difficulty: 'L4',
score: 85,
mentor: '王导师',
startDate: '2026-04-01',
endDate: '2026-04-28',
status: 'completed',
},
];
// 学员能力画像列表
const studentProfiles: StudentProfile[] = [
{
id: 1,
name: '王芳',
department: '技术部',
overall: 92,
skills: [
{ name: '前端开发', score: 95, icon: <CodeOutlined /> },
{ name: '后端开发', score: 88, icon: <GlobalOutlined /> },
{ name: '数据处理', score: 85, icon: <DatabaseOutlined /> },
{ name: '问题分析', score: 90, icon: <BulbOutlined /> },
],
strengths: ['React技术栈', 'TypeScript', '团队协作', '代码规范'],
weaknesses: ['系统设计', '性能优化'],
recentTrainings: [
{ name: '企业内部管理系统', score: 95, date: '2026-06' },
{ name: 'RESTful API设计', score: 88, date: '2026-05' },
],
},
{
id: 2,
name: '李明',
department: '技术部',
overall: 85,
skills: [
{ name: '前端开发', score: 78, icon: <CodeOutlined /> },
{ name: '后端开发', score: 90, icon: <GlobalOutlined /> },
{ name: '数据处理', score: 82, icon: <DatabaseOutlined /> },
{ name: '问题分析', score: 85, icon: <BulbOutlined /> },
],
strengths: ['后端开发', '数据库设计', 'Java技术栈'],
weaknesses: ['前端开发', '性能优化'],
recentTrainings: [
{ name: '电商平台用户模块', score: 85, date: '2026-07' },
{ name: '企业内部管理系统', score: 82, date: '2026-06' },
],
},
{
id: 3,
name: '张伟',
department: '标注部',
overall: 90,
skills: [
{ name: '前端开发', score: 85, icon: <CodeOutlined /> },
{ name: '后端开发', score: 88, icon: <GlobalOutlined /> },
{ name: '数据处理', score: 95, icon: <DatabaseOutlined /> },
{ name: '问题分析', score: 88, icon: <BulbOutlined /> },
],
strengths: ['标注质量', '团队协作', '数据处理'],
weaknesses: ['新技术学习'],
recentTrainings: [
{ name: '数据可视化看板', score: 90, date: '2026-05' },
{ name: '标注任务管理', score: 92, date: '2026-04' },
],
},
];
const historyColumns: ColumnsType<HistoryItem> = [
{
title: '学员',
dataIndex: 'student',
render: (student) => (
<Space>
<Avatar style={{ background: '#667eea' }}>{student.charAt(0)}</Avatar>
<Text>{student}</Text>
</Space>
),
},
{
title: '实训项目',
dataIndex: 'training',
},
{
title: '难度',
dataIndex: 'difficulty',
render: (level) => (
<Tag color={
level === 'L1' ? 'green' :
level === 'L2' ? 'cyan' :
level === 'L3' ? 'blue' :
level === 'L4' ? 'orange' : 'red'
}>
{level}
</Tag>
),
},
{
title: '导师',
dataIndex: 'mentor',
render: (mentor) => <Tag>{mentor}</Tag>,
},
{
title: '得分',
dataIndex: 'score',
render: (score) => (
<Text strong style={{ color: score >= 90 ? '#10b981' : score >= 80 ? '#f59e0b' : '#ef4444' }}>
{score}分
</Text>
),
},
{
title: '开始日期',
dataIndex: 'startDate',
render: (date) => <Text type="secondary">{date}</Text>,
},
{
title: '结束日期',
dataIndex: 'endDate',
render: (date) => <Text type="secondary">{date}</Text>,
},
{
title: '状态',
dataIndex: 'status',
render: (status) => (
<Badge status={status === 'completed' ? 'success' : 'processing'} />
),
},
{
title: '操作',
render: (_, record) => (
<Space>
<Button size="small" icon={<FileTextOutlined />}>详情</Button>
{canViewProfile && (
<Button size="small" type="link" onClick={() => {
const profile = studentProfiles.find(p => p.name === record.student);
if (profile) {
setSelectedProfile(profile);
setDrawerVisible(true);
}
}}>
能力画像
</Button>
)}
</Space>
),
},
];
const handleViewProfile = (profile: StudentProfile) => {
setSelectedProfile(profile);
setDrawerVisible(true);
};
// 渲染我的历史
const renderMyHistory = () => (
<div>
<Card style={{ borderRadius: 12, marginBottom: 16 }}>
<Row gutter={[24, 16]}>
<Col span={8}>
<Statistic
title="已完成实训"
value={myHistory.length}
prefix={<CheckCircleOutlined style={{ color: '#10b981' }} />}
suffix="个"
valueStyle={{ color: '#10b981' }}
/>
</Col>
<Col span={8}>
<Statistic
title="平均得分"
value={myHistory.reduce((acc, h) => acc + h.score, 0) / myHistory.length}
precision={1}
prefix={<TrophyOutlined style={{ color: '#f59e0b' }} />}
suffix="分"
valueStyle={{ color: '#f59e0b' }}
/>
</Col>
<Col span={8}>
<Statistic
title="最高得分"
value={Math.max(...myHistory.map(h => h.score))}
prefix={<FireOutlined style={{ color: '#ef4444' }} />}
suffix="分"
valueStyle={{ color: '#ef4444' }}
/>
</Col>
</Row>
</Card>
<Card style={{ borderRadius: 12 }}>
<Timeline
items={myHistory.map((item) => ({
color: 'blue',
children: (
<Card size="small" style={{ borderRadius: 8, marginBottom: 8 }}>
<Row gutter={16} align="middle">
<Col flex="auto">
<Space>
<Text strong>{item.training}</Text>
<Tag color={
item.difficulty === 'L1' ? 'green' :
item.difficulty === 'L2' ? 'cyan' :
item.difficulty === 'L3' ? 'blue' :
item.difficulty === 'L4' ? 'orange' : 'red'
}>
{item.difficulty}
</Tag>
<Tag>{item.mentor}</Tag>
</Space>
<br />
<Text type="secondary">{item.startDate} - {item.endDate}</Text>
</Col>
<Col flex="none">
<Tag color="green" style={{ fontSize: 16, padding: '4px 12px' }}>
{item.score}分
</Tag>
</Col>
</Row>
</Card>
),
}))}
/>
</Card>
</div>
);
// 渲染全部历史(主管/管理员)
const renderAllHistory = () => (
<div>
<Card style={{ borderRadius: 12 }}>
<Space style={{ marginBottom: 16 }}>
<Select defaultValue="all" style={{ width: 120 }}>
<Select.Option value="all">全部部门</Select.Option>
<Select.Option value="tech">技术部</Select.Option>
<Select.Option value="annotation">标注部</Select.Option>
</Select>
<Select defaultValue="all" style={{ width: 120 }}>
<Select.Option value="all">全部难度</Select.Option>
<Select.Option value="L1">L1</Select.Option>
<Select.Option value="L2">L2</Select.Option>
<Select.Option value="L3">L3</Select.Option>
<Select.Option value="L4">L4</Select.Option>
</Select>
<DatePicker.RangePicker />
<Button icon={<FileTextOutlined />}>导出</Button>
</Space>
<Table
columns={historyColumns}
dataSource={allHistory}
rowKey="id"
pagination={{ pageSize: 10 }}
/>
</Card>
</div>
);
// 渲染能力画像
const renderProfile = () => (
<div>
<Row gutter={[16, 16]}>
{studentProfiles.map((profile) => (
<Col key={profile.id} xs={24} sm={12} lg={8}>
<Card
hoverable
style={{ borderRadius: 12 }}
onClick={() => handleViewProfile(profile)}
>
<div style={{ textAlign: 'center', marginBottom: 16 }}>
<Avatar
size={80}
style={{
background: 'linear-gradient(135deg, #667eea, #764ba2)',
fontSize: 32
}}
>
{profile.name.charAt(0)}
</Avatar>
<Title level={4} style={{ marginTop: 12, marginBottom: 4 }}>
{profile.name}
</Title>
<Space>
<Tag>{profile.department}</Tag>
<Tag color="gold">综合 {profile.overall}分</Tag>
</Space>
</div>
<div style={{ marginBottom: 12 }}>
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4 }}>
<Text type="secondary">综合能力</Text>
<Text strong style={{ color: '#667eea' }}>{profile.overall}分</Text>
</div>
<AntdProgress percent={profile.overall} showInfo={false} strokeColor="#667eea" />
</div>
<Divider style={{ margin: '12px 0' }} />
<div style={{ marginBottom: 8 }}>
<Text type="secondary" style={{ fontSize: 12 }}>优势:</Text>
<div style={{ marginTop: 4 }}>
{profile.strengths.slice(0, 3).map((s) => (
<Tag key={s} color="green" style={{ marginBottom: 4 }}>{s}</Tag>
))}
</div>
</div>
<div>
<Text type="secondary" style={{ fontSize: 12 }}>待提升:</Text>
<div style={{ marginTop: 4 }}>
{profile.weaknesses.map((w) => (
<Tag key={w} color="orange" style={{ marginBottom: 4 }}>{w}</Tag>
))}
</div>
</div>
<Button block style={{ marginTop: 16 }} icon={<RiseOutlined />}>
查看详情
</Button>
</Card>
</Col>
))}
</Row>
</div>
);
return (
<div style={{ padding: '0 0 24px' }}>
<Title level={4} style={{ marginBottom: 16 }}>审计管理</Title>
<Tabs
activeKey={activeTab}
onChange={setActiveTab}
items={[
{
key: 'history',
label: (
<span>
<HistoryOutlined />
历史记录
</span>
),
children: canViewAll ? renderAllHistory() : renderMyHistory(),
},
...(canViewProfile ? [{
key: 'profile',
label: (
<span>
<UserOutlined />
能力画像
</span>
),
children: renderProfile(),
}] : []),
]}
/>
{/* 能力画像详情抽屉 */}
<Drawer
title="学员能力画像详情"
width={600}
open={drawerVisible}
onClose={() => setDrawerVisible(false)}
>
{selectedProfile && (
<div>
<Card style={{ marginBottom: 16, background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)', color: 'white' }}>
<Row gutter={16} align="middle">
<Col>
<Avatar
size={80}
style={{
background: 'rgba(255,255,255,0.2)',
fontSize: 32
}}
>
{selectedProfile.name.charAt(0)}
</Avatar>
</Col>
<Col flex="auto">
<Title level={3} style={{ color: 'white', marginBottom: 4 }}>
{selectedProfile.name}
</Title>
<Space>
<Tag style={{ background: 'rgba(255,255,255,0.2)', border: 'none', color: 'white' }}>
{selectedProfile.department}
</Tag>
<Tag style={{ background: 'rgba(255,255,255,0.2)', border: 'none', color: 'white' }}>
综合 {selectedProfile.overall}分
</Tag>
</Space>
</Col>
</Row>
</Card>
<Card title="能力分析" style={{ marginBottom: 16 }}>
<Row gutter={[16, 16]}>
<Col span={8}>
<div style={{ textAlign: 'center' }}>
<AntdProgress
type="circle"
percent={selectedProfile.overall}
strokeColor="#667eea"
size={80}
/>
<Text style={{ display: 'block', marginTop: 8 }}>综合能力</Text>
</div>
</Col>
<Col span={16}>
{selectedProfile.skills.map((skill) => (
<div key={skill.name} style={{ marginBottom: 12 }}>
<Space>
{skill.icon}
<Text>{skill.name}</Text>
</Space>
<AntdProgress
percent={skill.score}
strokeColor="#10b981"
showInfo={false}
size="small"
/>
</div>
))}
</Col>
</Row>
</Card>
<Card title="能力特点" style={{ marginBottom: 16 }}>
<div style={{ marginBottom: 12 }}>
<Text type="secondary" style={{ marginBottom: 8, display: 'block' }}>优势领域:</Text>
<Space wrap>
{selectedProfile.strengths.map((s) => (
<Tag key={s} color="green" style={{ marginBottom: 4 }}>{s}</Tag>
))}
</Space>
</div>
<div>
<Text type="secondary" style={{ marginBottom: 8, display: 'block' }}>待提升:</Text>
<Space wrap>
{selectedProfile.weaknesses.map((w) => (
<Tag key={w} color="orange" style={{ marginBottom: 4 }}>{w}</Tag>
))}
</Space>
</div>
</Card>
<Card title="近期实训">
<Timeline
items={selectedProfile.recentTrainings.map((training) => ({
color: 'blue',
children: (
<div>
<Text strong>{training.name}</Text>
<div>
<Space>
<Tag color="green">{training.score}分</Tag>
<Text type="secondary">{training.date}</Text>
</Space>
</div>
</div>
),
}))}
/>
</Card>
</div>
)}
</Drawer>
</div>
);
}
import { Card, Col, Row, Statistic } from 'antd';
import { Card, Row, Col, Statistic, Space, Typography, Tag, Badge } from 'antd';
import {
DashboardOutlined,
TeamOutlined,
ProjectOutlined,
BookOutlined,
AuditOutlined,
TrophyOutlined,
BellOutlined,
SafetyOutlined
} from '@ant-design/icons';
import { useAuthStore } from '../stores/useAuthStore';
import StudentDashboard from './StudentDashboard';
import MentorDashboard from './MentorDashboard';
import SupervisorDashboard from './SupervisorDashboard';
const { Text } = Typography;
export default function DashboardPage() {
const { user, permissions } = useAuthStore();
// 判断用户角色
const roles = user?.roles || [];
const isAdmin = roles.includes('ADMIN');
const isSupervisor = roles.includes('SUPERVISOR');
const isMentor = roles.includes('MENTOR');
const isStudent = roles.includes('STUDENT');
// 根据角色渲染对应的工作台
if (isStudent && !isAdmin && !isSupervisor && !isMentor) {
return <StudentDashboard />;
}
if (isMentor && !isAdmin && !isSupervisor) {
return <MentorDashboard />;
}
if (isSupervisor && !isAdmin) {
return <SupervisorDashboard />;
}
// 管理员工作台
return <AdminDashboard />;
}
// 管理员工作台组件
function AdminDashboard() {
const { user } = useAuthStore();
return (
<div>
<h2 style={{ marginBottom: 16 }}>工作台</h2>
<Row gutter={16}>
<Col span={6}>
<Card>
<Statistic title="进行中项目" value={3} suffix="个" />
<div style={{ padding: '0 0 24px' }}>
{/* 欢迎区域 */}
<div style={{
background: 'linear-gradient(135deg, #1a1a2e 0%, #16213e 100%)',
borderRadius: 16,
padding: 32,
marginBottom: 24,
color: 'white',
position: 'relative',
overflow: 'hidden'
}}>
<div style={{
position: 'absolute',
top: -50,
right: -50,
width: 300,
height: 300,
borderRadius: '50%',
background: 'rgba(102, 126, 234, 0.2)'
}} />
<div style={{
position: 'absolute',
bottom: -30,
left: '20%',
width: 150,
height: 150,
borderRadius: '50%',
background: 'rgba(118, 75, 162, 0.15)'
}} />
<Row gutter={24} align="middle" style={{ position: 'relative', zIndex: 1 }}>
<Col flex="none">
<div style={{
width: 80,
height: 80,
borderRadius: '50%',
background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
fontSize: 32,
color: 'white',
fontWeight: 'bold'
}}>
{user?.realName?.charAt(0) || '管'}
</div>
</Col>
<Col flex="auto">
<Text style={{ fontSize: 28, fontWeight: 600, color: 'white', display: 'block' }}>
欢迎回来,{user?.realName || '管理员'}!
</Text>
<Text style={{ color: 'rgba(255,255,255,0.7)', fontSize: 16 }}>
系统运行正常,所有服务已就绪
</Text>
</Col>
<Col flex="none">
<Space direction="vertical" align="end">
<Tag color="gold" style={{ fontSize: 14, padding: '4px 12px' }}>
管理员
</Tag>
<Text style={{ color: 'rgba(255,255,255,0.6)', fontSize: 12 }}>
拥有全部权限
</Text>
</Space>
</Col>
</Row>
</div>
{/* 统计卡片 */}
<Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
<Col xs={24} sm={12} lg={6}>
<Card hoverable style={{ borderRadius: 12, borderLeft: '4px solid #667eea' }}>
<Statistic
title={<Text type="secondary">系统用户</Text>}
value={156}
prefix={<TeamOutlined style={{ color: '#667eea' }} />}
suffix="人"
/>
<Text type="secondary" style={{ fontSize: 12 }}>技术部 98 / 标注部 58</Text>
</Card>
</Col>
<Col span={6}>
<Card>
<Statistic title="待办训练任务" value={5} suffix="项" />
<Col xs={24} sm={12} lg={6}>
<Card hoverable style={{ borderRadius: 12, borderLeft: '4px solid #10b981' }}>
<Statistic
title={<Text type="secondary">项目总数</Text>}
value={328}
prefix={<ProjectOutlined style={{ color: '#10b981' }} />}
suffix="个"
/>
<Text type="secondary" style={{ fontSize: 12 }}>内部项目 120 / GitHub 208</Text>
</Card>
</Col>
<Col span={6}>
<Card>
<Statistic title="待答辩" value={1} suffix="场" />
<Col xs={24} sm={12} lg={6}>
<Card hoverable style={{ borderRadius: 12, borderLeft: '4px solid #f59e0b' }}>
<Statistic
title={<Text type="secondary">进行中实训</Text>}
value={48}
prefix={<BookOutlined style={{ color: '#f59e0b' }} />}
suffix="项"
/>
<Text type="secondary" style={{ fontSize: 12 }}>本周新增 12 项</Text>
</Card>
</Col>
<Col span={6}>
<Card>
<Statistic title="未读通知" value={2} suffix="条" />
<Col xs={24} sm={12} lg={6}>
<Card hoverable style={{ borderRadius: 12, borderLeft: '4px solid #ef4444' }}>
<Statistic
title={<Text type="secondary">待答辩</Text>}
value={8}
prefix={<AuditOutlined style={{ color: '#ef4444' }} />}
suffix="场"
/>
<Text type="secondary" style={{ fontSize: 12 }}>本周安排 5 场</Text>
</Card>
</Col>
</Row>
{/* 系统状态 */}
<Row gutter={[16, 16]}>
<Col xs={24} lg={16}>
<Card
title={
<Space>
<DashboardOutlined style={{ color: '#667eea' }} />
<span>系统概览</span>
</Space>
}
style={{ borderRadius: 12 }}
>
<Row gutter={[16, 16]}>
<Col xs={12} sm={6}>
<Card size="small" style={{ borderRadius: 8, textAlign: 'center' }}>
<Statistic
title="活跃导师"
value={15}
prefix={<TeamOutlined style={{ color: '#667eea' }} />}
/>
</Card>
</Col>
<Col xs={12} sm={6}>
<Card size="small" style={{ borderRadius: 8, textAlign: 'center' }}>
<Statistic
title="本月毕业"
value={12}
prefix={<TrophyOutlined style={{ color: '#10b981' }} />}
/>
</Card>
</Col>
<Col xs={12} sm={6}>
<Card size="small" style={{ borderRadius: 8, textAlign: 'center' }}>
<Statistic
title="平均分数"
value={85.6}
precision={1}
prefix={<AuditOutlined style={{ color: '#f59e0b' }} />}
/>
</Card>
</Col>
<Col xs={12} sm={6}>
<Card size="small" style={{ borderRadius: 8, textAlign: 'center' }}>
<Statistic
title="完成率"
value={92}
suffix="%"
prefix={<ProjectOutlined style={{ color: '#ef4444' }} />}
/>
</Card>
</Col>
</Row>
</Card>
</Col>
<Col xs={24} lg={8}>
<Card
title={
<Space>
<BellOutlined style={{ color: '#667eea' }} />
<span>系统公告</span>
</Space>
}
style={{ borderRadius: 12, height: '100%' }}
>
<Space direction="vertical" style={{ width: '100%' }}>
<div style={{ padding: '8px 0', borderBottom: '1px solid #f0f0f0' }}>
<Tag color="blue" style={{ marginRight: 8 }}>新功能</Tag>
<Text>新增AI智能推荐功能</Text>
<br />
<Text type="secondary" style={{ fontSize: 11 }}>2026-07-15</Text>
</div>
<div style={{ padding: '8px 0', borderBottom: '1px solid #f0f0f0' }}>
<Tag color="green" style={{ marginRight: 8 }}>通知</Tag>
<Text>实训平台将于本周更新</Text>
<br />
<Text type="secondary" style={{ fontSize: 11 }}>2026-07-14</Text>
</div>
<div style={{ padding: '8px 0' }}>
<Tag color="orange" style={{ marginRight: 8 }}>维护</Tag>
<Text>系统将于周末进行例行维护</Text>
<br />
<Text type="secondary" style={{ fontSize: 11 }}>2026-07-13</Text>
</div>
</Space>
</Card>
</Col>
</Row>
{/* 快捷入口 */}
<Card
title={
<Space>
<SafetyOutlined style={{ color: '#667eea' }} />
<span>管理功能</span>
</Space>
}
style={{ borderRadius: 12, marginTop: 16 }}
>
<Row gutter={[16, 16]}>
<Col xs={12} sm={8} md={4}>
<Card
hoverable
style={{ borderRadius: 12, textAlign: 'center' }}
cover={
<div style={{
padding: 24,
background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
borderRadius: '12px 12px 0 0',
color: 'white'
}}>
<TeamOutlined style={{ fontSize: 32 }} />
</div>
}
>
<Text strong>用户管理</Text>
</Card>
</Col>
<Col xs={12} sm={8} md={4}>
<Card
hoverable
style={{ borderRadius: 12, textAlign: 'center' }}
cover={
<div style={{
padding: 24,
background: 'linear-gradient(135deg, #11998e 0%, #38ef7d 100%)',
borderRadius: '12px 12px 0 0',
color: 'white'
}}>
<ProjectOutlined style={{ fontSize: 32 }} />
</div>
}
>
<Text strong>项目管理</Text>
</Card>
</Col>
<Col xs={12} sm={8} md={4}>
<Card
hoverable
style={{ borderRadius: 12, textAlign: 'center' }}
cover={
<div style={{
padding: 24,
background: 'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)',
borderRadius: '12px 12px 0 0',
color: 'white'
}}>
<BookOutlined style={{ fontSize: 32 }} />
</div>
}
>
<Text strong>实训管理</Text>
</Card>
</Col>
<Col xs={12} sm={8} md={4}>
<Card
hoverable
style={{ borderRadius: 12, textAlign: 'center' }}
cover={
<div style={{
padding: 24,
background: 'linear-gradient(135deg, #fa709a 0%, #fee140 100%)',
borderRadius: '12px 12px 0 0',
color: 'white'
}}>
<AuditOutlined style={{ fontSize: 32 }} />
</div>
}
>
<Text strong>答辩管理</Text>
</Card>
</Col>
<Col xs={12} sm={8} md={4}>
<Card
hoverable
style={{ borderRadius: 12, textAlign: 'center' }}
cover={
<div style={{
padding: 24,
background: 'linear-gradient(135deg, #30cfd0 0%, #330867 100%)',
borderRadius: '12px 12px 0 0',
color: 'white'
}}>
<TrophyOutlined style={{ fontSize: 32 }} />
</div>
}
>
<Text strong>难度校准</Text>
</Card>
</Col>
<Col xs={12} sm={8} md={4}>
<Card
hoverable
style={{ borderRadius: 12, textAlign: 'center' }}
cover={
<div style={{
padding: 24,
background: 'linear-gradient(135deg, #a8edea 0%, #fed6e3 100%)',
borderRadius: '12px 12px 0 0',
color: '#333'
}}>
<DashboardOutlined style={{ fontSize: 32 }} />
</div>
}
>
<Text strong>系统设置</Text>
</Card>
</Col>
</Row>
</Card>
</div>
);
}
import { Empty } from 'antd';
import { Card, Row, Col, Table, Tag, Timeline, Statistic, List, Avatar, Space, Button, Divider, Typography, Progress, Badge, Tabs, Modal, Form, Input, Select, DatePicker, Steps, Rate, message, Alert } from 'antd';
import {
AuditOutlined,
CheckCircleOutlined,
ClockCircleOutlined,
TeamOutlined,
TrophyOutlined,
VideoCameraOutlined,
FileTextOutlined,
MessageOutlined,
SmileOutlined,
ExclamationCircleOutlined,
PlayCircleOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { useState } from 'react';
import { useAuthStore } from '../stores/useAuthStore';
import { PERMISSION_CODES } from '../services/permissionApi';
const { Text, Title, Paragraph } = Typography;
const { TextArea } = Input;
type DefenseItem = {
id: number;
student: string;
training: string;
difficulty: string;
applyTime: string;
defenseTime?: string;
status: 'pending' | 'approved' | 'rejected' | 'completed';
score?: number;
mentors: string[];
};
type MyDefense = {
id: number;
training: string;
project: string;
applyTime: string;
status: 'pending' | 'approved' | 'rejected' | 'completed';
defenseTime?: string;
score?: number;
feedback?: string;
};
export default function DefensePage() {
return <Empty description="答辩 - 待接入" />;
const { user, permissions } = useAuthStore();
const [activeTab, setActiveTab] = useState('apply');
const [applyModalVisible, setApplyModalVisible] = useState(false);
const [reviewModalVisible, setReviewModalVisible] = useState(false);
const [selectedDefense, setSelectedDefense] = useState<DefenseItem | null>(null);
// 判断角色
const roles = user?.roles || [];
const isStudent = roles.includes('STUDENT');
const isMentor = roles.includes('MENTOR');
const isSupervisor = roles.includes('SUPERVISOR');
const isAdmin = roles.includes('ADMIN');
// 权限判断
const canApply = permissions.includes(PERMISSION_CODES.DEFENSE_APPLY);
const canReview = permissions.includes(PERMISSION_CODES.DEFENSE_REVIEW);
const canAudit = permissions.includes(PERMISSION_CODES.DEFENSE_AUDIT);
const canViewPending = permissions.includes(PERMISSION_CODES.DEFENSE_PENDING_LIST);
// 我的答辩申请
const myDefenses: MyDefense[] = [
{
id: 1,
training: '企业内部管理系统',
project: 'L3管理系统开发',
applyTime: '2026-07-10',
status: 'approved',
defenseTime: '2026-07-20 14:00',
},
{
id: 2,
training: 'RESTful API设计',
project: 'L2接口开发',
applyTime: '2026-07-01',
status: 'completed',
score: 92,
feedback: '答辩表现优秀,代码规范良好',
},
];
// 待评审列表(导师)
const pendingDefenses: DefenseItem[] = [
{
id: 1,
student: '王芳',
training: '数据可视化看板',
difficulty: 'L2',
applyTime: '2026-07-16',
mentors: ['张导师'],
status: 'pending',
},
{
id: 2,
student: '李明',
training: '电商平台用户模块',
difficulty: 'L3',
applyTime: '2026-07-15',
mentors: ['张导师', '王导师'],
status: 'pending',
},
{
id: 3,
student: '刘洋',
training: '微服务架构实战',
difficulty: 'L4',
applyTime: '2026-07-14',
mentors: ['王导师'],
status: 'pending',
},
];
// 待审核列表(主管)
const pendingAudits: DefenseItem[] = [
{
id: 1,
student: '王芳',
training: '数据可视化看板',
difficulty: 'L2',
applyTime: '2026-07-16',
defenseTime: '2026-07-19 10:00',
mentors: ['张导师'],
status: 'approved',
score: 88,
},
];
// 答辩记录
const defenseHistory: DefenseItem[] = [
{
id: 1,
student: '张伟',
training: '企业内部管理系统',
difficulty: 'L3',
applyTime: '2026-06-28',
defenseTime: '2026-07-05 14:00',
status: 'completed',
score: 95,
mentors: ['张导师'],
},
{
id: 2,
student: '陈静',
training: '数据标注工具开发',
difficulty: 'L2',
applyTime: '2026-06-20',
defenseTime: '2026-06-28 09:00',
status: 'completed',
score: 90,
mentors: ['王导师'],
},
];
const defenseColumns: ColumnsType<DefenseItem> = [
{
title: '学员',
dataIndex: 'student',
render: (student) => (
<Space>
<Avatar style={{ background: '#667eea' }}>{student.charAt(0)}</Avatar>
<Text>{student}</Text>
</Space>
),
},
{
title: '实训项目',
dataIndex: 'training',
},
{
title: '难度',
dataIndex: 'difficulty',
render: (level) => (
<Tag color={
level === 'L1' ? 'green' :
level === 'L2' ? 'cyan' :
level === 'L3' ? 'blue' :
level === 'L4' ? 'orange' : 'red'
}>
{level}
</Tag>
),
},
{
title: '申请时间',
dataIndex: 'applyTime',
render: (time) => <Text type="secondary">{time}</Text>,
},
{
title: '答辩时间',
dataIndex: 'defenseTime',
render: (time) => time ? <Text>{time}</Text> : <Text type="secondary">待安排</Text>,
},
{
title: '评审导师',
dataIndex: 'mentors',
render: (mentors: string[]) => (
<Space>
{mentors.map((m: string) => <Tag key={m}>{m}</Tag>)}
</Space>
),
},
{
title: '评分',
dataIndex: 'score',
render: (score) => score ? (
<Text strong style={{ color: '#10b981' }}>{score}分</Text>
) : '-',
},
{
title: '状态',
dataIndex: 'status',
render: (status: 'pending' | 'approved' | 'rejected' | 'completed') => {
const statusMap: Record<string, { color: 'default' | 'processing' | 'error' | 'success'; text: string }> = {
pending: { color: 'default', text: '待评审' },
approved: { color: 'processing', text: '已安排' },
rejected: { color: 'error', text: '已驳回' },
completed: { color: 'success', text: '已完成' },
};
return <Badge status={statusMap[status]?.color} text={statusMap[status]?.text} />;
},
},
{
title: '操作',
width: 180,
render: (_, record) => (
<Space>
<Button size="small" icon={<FileTextOutlined />}>详情</Button>
{record.status === 'pending' && (canReview || canAudit) && (
<Button size="small" type="primary" onClick={() => {
setSelectedDefense(record);
setReviewModalVisible(true);
}}>
{canAudit ? '审核' : '评审'}
</Button>
)}
{record.status === 'approved' && (
<Button size="small" icon={<VideoCameraOutlined />}>加入答辩</Button>
)}
</Space>
),
},
];
const myDefenseColumns: ColumnsType<MyDefense> = [
{
title: '实训项目',
dataIndex: 'training',
},
{
title: '难度',
dataIndex: 'project',
render: (text) => <Tag color="blue">{text}</Tag>,
},
{
title: '申请时间',
dataIndex: 'applyTime',
},
{
title: '答辩时间',
dataIndex: 'defenseTime',
render: (time) => time ? (
<Space>
<ClockCircleOutlined style={{ color: '#667eea' }} />
{time}
</Space>
) : <Text type="secondary">待安排</Text>,
},
{
title: '得分',
dataIndex: 'score',
render: (score) => score ? (
<Tag color="green">{score}分</Tag>
) : '-',
},
{
title: '状态',
dataIndex: 'status',
render: (status: 'pending' | 'approved' | 'rejected' | 'completed') => {
const statusMap: Record<string, { color: 'default' | 'processing' | 'error' | 'success'; text: string }> = {
pending: { color: 'default', text: '待安排' },
approved: { color: 'processing', text: '已安排' },
rejected: { color: 'error', text: '已驳回' },
completed: { color: 'success', text: '已完成' },
};
return <Badge status={statusMap[status]?.color} text={statusMap[status]?.text} />;
},
},
{
title: '操作',
render: (_, record) => (
<Space>
<Button size="small">详情</Button>
{record.status === 'approved' && (
<Button size="small" type="primary" icon={<VideoCameraOutlined />}>答辩入口</Button>
)}
{record.status === 'completed' && (
<Button size="small" icon={<FileTextOutlined />}>查看报告</Button>
)}
</Space>
),
},
];
// 学员视角 - 我的答辩
const renderMyDefense = () => (
<div>
{canApply && (
<Button
type="primary"
icon={<AuditOutlined />}
style={{ marginBottom: 16 }}
onClick={() => setApplyModalVisible(true)}
>
申请答辩
</Button>
)}
<Card style={{ borderRadius: 12, marginBottom: 16 }}>
<List
dataSource={myDefenses}
renderItem={(item) => (
<List.Item
actions={[
item.status === 'completed' && (
<Button type="primary" size="small" key="report">查看答辩报告</Button>
),
].filter(Boolean)}
>
<List.Item.Meta
avatar={
<Avatar
size={56}
style={{
background: item.status === 'completed' ? '#10b981' :
item.status === 'approved' ? '#667eea' : '#f5f5f5',
color: item.status === 'pending' ? '#666' : 'white'
}}
>
{item.status === 'completed' ? '✓' : item.status === 'approved' ? '📅' : '⏳'}
</Avatar>
}
title={
<Space>
<Text strong>{item.training}</Text>
<Tag>{item.project}</Tag>
{item.status === 'completed' && item.score && (
<Tag color="gold">{item.score}分</Tag>
)}
</Space>
}
description={
<div>
<Text type="secondary">申请时间: {item.applyTime}</Text>
{item.defenseTime && (
<>
<br />
<Text>答辩时间: {item.defenseTime}</Text>
</>
)}
{item.feedback && (
<>
<br />
<Text type="secondary">导师点评: {item.feedback}</Text>
</>
)}
</div>
}
/>
</List.Item>
)}
/>
</Card>
</div>
);
// 导师视角 - 待评审
const renderMentorReview = () => (
<div>
<Alert
message="您有新的答辩评审任务"
description="请及时评审学员的答辩申请,安排答辩时间并给出评审意见。"
type="info"
showIcon
icon={<ExclamationCircleOutlined />}
style={{ marginBottom: 16 }}
/>
<Table
columns={defenseColumns}
dataSource={pendingDefenses}
rowKey="id"
pagination={false}
/>
</div>
);
// 主管视角 - 待审核
const renderSupervisorAudit = () => (
<div>
<Alert
message="主管审核入口"
description="审核导师提交的答辩评审结果,确认最终成绩。"
type="warning"
showIcon
style={{ marginBottom: 16 }}
/>
<Table
columns={defenseColumns}
dataSource={pendingAudits}
rowKey="id"
pagination={false}
/>
</div>
);
// 答辩记录
const renderHistory = () => (
<div>
<Card style={{ borderRadius: 12 }}>
<Table
columns={defenseColumns}
dataSource={defenseHistory}
rowKey="id"
pagination={{ pageSize: 10 }}
/>
</Card>
</div>
);
// 统计卡片
const renderStats = () => {
const stats = {
pending: pendingDefenses.length,
scheduled: pendingAudits.length,
completed: defenseHistory.length,
avgScore: 91.2,
};
return (
<Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
<Col xs={12} sm={6}>
<Card hoverable style={{ borderRadius: 12 }}>
<Statistic
title="待评审"
value={stats.pending}
prefix={<ClockCircleOutlined style={{ color: '#f59e0b' }} />}
valueStyle={{ color: '#f59e0b' }}
/>
</Card>
</Col>
<Col xs={12} sm={6}>
<Card hoverable style={{ borderRadius: 12 }}>
<Statistic
title="已安排"
value={stats.scheduled}
prefix={<AuditOutlined style={{ color: '#667eea' }} />}
valueStyle={{ color: '#667eea' }}
/>
</Card>
</Col>
<Col xs={12} sm={6}>
<Card hoverable style={{ borderRadius: 12 }}>
<Statistic
title="已完成"
value={stats.completed}
prefix={<CheckCircleOutlined style={{ color: '#10b981' }} />}
valueStyle={{ color: '#10b981' }}
/>
</Card>
</Col>
<Col xs={12} sm={6}>
<Card hoverable style={{ borderRadius: 12 }}>
<Statistic
title="平均分"
value={stats.avgScore}
precision={1}
suffix="分"
prefix={<TrophyOutlined style={{ color: '#ef4444' }} />}
valueStyle={{ color: '#ef4444' }}
/>
</Card>
</Col>
</Row>
);
};
return (
<div style={{ padding: '0 0 24px' }}>
<Title level={4} style={{ marginBottom: 16 }}>答辩管理</Title>
{/* 统计 */}
{renderStats()}
{/* Tab切换 */}
<Tabs
activeKey={activeTab}
onChange={setActiveTab}
items={[
{
key: 'apply',
label: '我的答辩',
children: renderMyDefense(),
},
...(canReview ? [{
key: 'review',
label: (
<span>
待评审
{pendingDefenses.length > 0 && (
<Badge count={pendingDefenses.length} style={{ marginLeft: 8 }} />
)}
</span>
),
children: renderMentorReview(),
}] : []),
...(canAudit ? [{
key: 'audit',
label: (
<span>
主管审核
{pendingAudits.length > 0 && (
<Badge count={pendingAudits.length} style={{ marginLeft: 8 }} />
)}
</span>
),
children: renderSupervisorAudit(),
}] : []),
{
key: 'history',
label: '答辩记录',
children: renderHistory(),
},
]}
/>
{/* 申请答辩弹窗 */}
<Modal
title="申请答辩"
open={applyModalVisible}
onCancel={() => setApplyModalVisible(false)}
footer={null}
width={600}
>
<Form layout="vertical">
<Form.Item label="选择实训" required>
<Select placeholder="请选择已完成实操的实训">
<Select.Option value="1">企业内部管理系统 - L3</Select.Option>
<Select.Option value="2">RESTful API设计 - L2</Select.Option>
</Select>
</Form.Item>
<Form.Item label="答辩时间意向">
<DatePicker showTime style={{ width: '100%' }} />
</Form.Item>
<Form.Item label="自我总结">
<TextArea rows={4} placeholder="请简要描述你的实训成果..." />
</Form.Item>
<Form.Item label="备注">
<TextArea rows={2} placeholder="其他需要说明的事项" />
</Form.Item>
<Form.Item>
<Space>
<Button type="primary">提交申请</Button>
<Button onClick={() => setApplyModalVisible(false)}>取消</Button>
</Space>
</Form.Item>
</Form>
</Modal>
{/* 评审/审核弹窗 */}
<Modal
title={canAudit ? "审核答辩申请" : "评审答辩申请"}
open={reviewModalVisible}
onCancel={() => {
setReviewModalVisible(false);
setSelectedDefense(null);
}}
footer={null}
width={600}
>
{selectedDefense && (
<div>
<Card style={{ marginBottom: 16 }}>
<Row gutter={[16, 16]}>
<Col span={12}>
<Text type="secondary">学员</Text>
<br />
<Text strong>{selectedDefense.student}</Text>
</Col>
<Col span={12}>
<Text type="secondary">实训项目</Text>
<br />
<Text>{selectedDefense.training}</Text>
</Col>
<Col span={12}>
<Text type="secondary">难度</Text>
<br />
<Tag color="blue">{selectedDefense.difficulty}</Tag>
</Col>
<Col span={12}>
<Text type="secondary">申请时间</Text>
<br />
<Text>{selectedDefense.applyTime}</Text>
</Col>
</Row>
</Card>
<Form layout="vertical">
{canAudit ? (
<>
<Form.Item label="审核意见" required>
<Select placeholder="请选择审核意见">
<Select.Option value="approved">通过,安排答辩</Select.Option>
<Select.Option value="rejected">驳回,需补充材料</Select.Option>
</Select>
</Form.Item>
<Form.Item label="答辩时间安排">
<DatePicker showTime style={{ width: '100%' }} />
</Form.Item>
</>
) : (
<>
<Form.Item label="评分" required>
<Rate />
</Form.Item>
<Form.Item label="评审意见">
<TextArea rows={4} placeholder="请输入评审意见..." />
</Form.Item>
</>
)}
<Form.Item>
<Space>
<Button type="primary">提交</Button>
<Button onClick={() => setReviewModalVisible(false)}>取消</Button>
</Space>
</Form.Item>
</Form>
</div>
)}
</Modal>
</div>
);
}
import { Card, Row, Col, Table, Tag, Timeline, Statistic, List, Avatar, Space, Button, Divider, Typography, Progress, Badge, Rate } from 'antd';
import {
TeamOutlined,
FileTextOutlined,
CheckCircleOutlined,
ClockCircleOutlined,
AlertOutlined,
TrophyOutlined,
StarOutlined,
RiseOutlined,
EyeOutlined,
MessageOutlined,
DesktopOutlined,
DashboardOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { useAuthStore } from '../stores/useAuthStore';
const { Text, Title } = Typography;
type StudentItem = {
id: number;
name: string;
avatar?: string;
training: string;
progress: number;
stage: string;
lastActive: string;
score: number;
status: 'pending' | 'active' | 'completed';
};
export default function MentorDashboard() {
const { user } = useAuthStore();
// 模拟数据
const statsData = {
totalStudents: 12,
pendingReviews: 5,
activeTrainings: 8,
completedThisMonth: 3,
};
const myStudents: StudentItem[] = [
{
id: 1,
name: '李明',
training: '电商平台用户模块',
progress: 65,
stage: '实操阶段',
lastActive: '刚刚',
score: 88,
status: 'active',
},
{
id: 2,
name: '王芳',
training: '数据可视化看板',
progress: 85,
stage: '答辩阶段',
lastActive: '10分钟前',
score: 92,
status: 'pending',
},
{
id: 3,
name: '张伟',
training: '企业内部管理系统',
progress: 100,
stage: '已完成',
lastActive: '昨天',
score: 95,
status: 'completed',
},
{
id: 4,
name: '刘洋',
training: 'RESTful API设计',
progress: 45,
stage: '预览阶段',
lastActive: '1小时前',
score: 78,
status: 'active',
},
{
id: 5,
name: '陈静',
training: '微服务架构实战',
progress: 30,
stage: '需求分析',
lastActive: '2小时前',
score: 82,
status: 'active',
},
];
const pendingTasks = [
{
id: 1,
type: 'review',
title: '王芳 - 答辩评审',
student: '王芳',
training: '数据可视化看板',
deadline: '今天',
priority: 'high',
},
{
id: 2,
type: 'feedback',
title: '李明 - 阶段点评',
student: '李明',
training: '电商平台用户模块',
deadline: '明天',
priority: 'medium',
},
{
id: 3,
type: 'defense',
title: '答辩安排确认',
student: '王芳',
training: '数据可视化看板',
deadline: '3天后',
priority: 'medium',
},
{
id: 4,
type: 'question',
title: '张伟 - 问题回复',
student: '张伟',
training: '企业内部管理系统',
deadline: '本周内',
priority: 'low',
},
];
const recentActivities = [
{ action: '李明 提交了实操产物', time: '30分钟前', type: 'submit' },
{ action: '王芳 申请了答辩', time: '2小时前', type: 'apply' },
{ action: '张伟 完成了实训', time: '昨天', type: 'complete' },
{ action: '刘洋 查看了实训资料', time: '昨天', type: 'view' },
];
const studentColumns: ColumnsType<StudentItem> = [
{
title: '学员',
dataIndex: 'name',
render: (name, record) => (
<Space>
<Avatar style={{ background: 'linear-gradient(135deg, #667eea, #764ba2)' }}>
{name.charAt(0)}
</Avatar>
<div>
<Text strong>{name}</Text>
<br />
<Text type="secondary" style={{ fontSize: 12 }}>{record.lastActive}</Text>
</div>
</Space>
),
},
{
title: '当前实训',
dataIndex: 'training',
render: (training) => <Text>{training}</Text>,
},
{
title: '阶段',
dataIndex: 'stage',
render: (stage, record) => (
<Tag color={record.status === 'pending' ? 'orange' : record.status === 'completed' ? 'green' : 'blue'}>
{stage}
</Tag>
),
},
{
title: '进度',
dataIndex: 'progress',
width: 150,
render: (progress) => (
<Progress percent={progress} size="small" strokeColor="#667eea" />
),
},
{
title: '得分',
dataIndex: 'score',
render: (score) => (
<Space>
<Text strong style={{ color: score >= 90 ? '#10b981' : score >= 80 ? '#f59e0b' : '#ef4444' }}>
{score}
</Text>
<Text type="secondary">分</Text>
</Space>
),
},
{
title: '操作',
width: 180,
render: (_, record) => (
<Space>
<Button size="small" icon={<EyeOutlined />}>查看</Button>
<Button size="small" type="primary" icon={<MessageOutlined />}>指导</Button>
</Space>
),
},
];
const getPriorityColor = (priority: string): 'success' | 'warning' | 'error' | 'default' => {
const colors: Record<string, 'success' | 'warning' | 'error' | 'default'> = {
high: 'error',
medium: 'warning',
low: 'success',
};
return colors[priority] || 'default';
};
const getTaskIcon = (type: string) => {
const icons: Record<string, React.ReactNode> = {
review: <StarOutlined style={{ color: '#f59e0b' }} />,
feedback: <MessageOutlined style={{ color: '#667eea' }} />,
defense: <TrophyOutlined style={{ color: '#10b981' }} />,
question: <AlertOutlined style={{ color: '#ef4444' }} />,
};
return icons[type] || <ClockCircleOutlined />;
};
return (
<div style={{ padding: '0 0 24px' }}>
{/* 欢迎区域 */}
<div style={{
background: 'linear-gradient(135deg, #11998e 0%, #38ef7d 100%)',
borderRadius: 16,
padding: 32,
marginBottom: 24,
color: 'white',
position: 'relative',
overflow: 'hidden'
}}>
<div style={{
position: 'absolute',
top: -50,
right: 100,
width: 200,
height: 200,
borderRadius: '50%',
background: 'rgba(255,255,255,0.1)'
}} />
<Row gutter={24} align="middle" style={{ position: 'relative', zIndex: 1 }}>
<Col flex="none">
<Avatar size={80} style={{ background: 'rgba(255,255,255,0.2)', fontSize: 32 }}>
{user?.realName?.charAt(0) || '导'}
</Avatar>
</Col>
<Col flex="auto">
<Title level={2} style={{ color: 'white', margin: 0 }}>
导师工作台,{user?.realName || '导师'}!
</Title>
<Text style={{ color: 'rgba(255,255,255,0.85)', fontSize: 16 }}>
有效指导,助力每位学员成长 🚀
</Text>
</Col>
<Col flex="none">
<Space size={24}>
<div style={{ textAlign: 'center' }}>
<Statistic
value={statsData.pendingReviews}
suffix="项"
valueStyle={{ color: 'white', fontSize: 36 }}
/>
<Text style={{ color: 'rgba(255,255,255,0.7)' }}>待评审</Text>
</div>
<div style={{ textAlign: 'center' }}>
<Statistic
value={statsData.totalStudents}
valueStyle={{ color: 'white', fontSize: 36 }}
/>
<Text style={{ color: 'rgba(255,255,255,0.7)' }}>我的学员</Text>
</div>
</Space>
</Col>
</Row>
</div>
{/* 统计卡片 */}
<Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
<Col xs={24} sm={12} lg={6}>
<Card hoverable style={{ borderRadius: 12 }}>
<Statistic
title="指导学员"
value={statsData.totalStudents}
suffix="人"
prefix={<TeamOutlined style={{ color: '#667eea' }} />}
valueStyle={{ color: '#667eea' }}
/>
<Tag color="green" style={{ marginTop: 8 }}>在线 8人</Tag>
</Card>
</Col>
<Col xs={24} sm={12} lg={6}>
<Card hoverable style={{ borderRadius: 12 }}>
<Statistic
title="待评审"
value={statsData.pendingReviews}
suffix="项"
prefix={<StarOutlined style={{ color: '#f59e0b' }} />}
valueStyle={{ color: '#f59e0b' }}
/>
<Text type="secondary">含答辩和作业</Text>
</Card>
</Col>
<Col xs={24} sm={12} lg={6}>
<Card hoverable style={{ borderRadius: 12 }}>
<Statistic
title="进行中实训"
value={statsData.activeTrainings}
suffix="个"
prefix={<DesktopOutlined style={{ color: '#10b981' }} />}
valueStyle={{ color: '#10b981' }}
/>
<Text type="secondary">本周新增 2 个</Text>
</Card>
</Col>
<Col xs={24} sm={12} lg={6}>
<Card hoverable style={{ borderRadius: 12 }}>
<Statistic
title="本月完成"
value={statsData.completedThisMonth}
suffix="人"
prefix={<TrophyOutlined style={{ color: '#ef4444' }} />}
valueStyle={{ color: '#ef4444' }}
/>
<Tag color="gold" style={{ marginTop: 8 }}>优秀率 67%</Tag>
</Card>
</Col>
</Row>
<Row gutter={[16, 16]}>
{/* 待办任务 */}
<Col xs={24} lg={10}>
<Card
title={
<Space>
<AlertOutlined style={{ color: '#ef4444' }} />
<span>待办任务</span>
<Badge count={pendingTasks.length} style={{ backgroundColor: '#ef4444' }} />
</Space>
}
style={{ borderRadius: 12 }}
>
<List
dataSource={pendingTasks}
renderItem={(item) => (
<List.Item
actions={[
<Button type="primary" size="small" key="handle">处理</Button>
]}
>
<List.Item.Meta
avatar={getTaskIcon(item.type)}
title={
<Space>
<Text>{item.title}</Text>
<Badge status={getPriorityColor(item.priority)} />
</Space>
}
description={
<Space>
<Text type="secondary">{item.student}</Text>
<Divider type="vertical" />
<Text type="secondary">{item.training}</Text>
<Divider type="vertical" />
<Text type="secondary">截止: {item.deadline}</Text>
</Space>
}
/>
</List.Item>
)}
/>
</Card>
</Col>
{/* 学员列表 */}
<Col xs={24} lg={14}>
<Card
title={
<Space>
<TeamOutlined style={{ color: '#667eea' }} />
<span>我的学员</span>
</Space>
}
style={{ borderRadius: 12 }}
extra={
<Space>
<Button>全部学员</Button>
<Button type="primary">添加学员</Button>
</Space>
}
>
<Table
columns={studentColumns}
dataSource={myStudents}
rowKey="id"
pagination={false}
size="small"
/>
</Card>
</Col>
{/* 近期活动 */}
<Col xs={24} lg={12}>
<Card
title={
<Space>
<ClockCircleOutlined style={{ color: '#6366f1' }} />
<span>学员动态</span>
</Space>
}
style={{ borderRadius: 12 }}
>
<Timeline
items={recentActivities.map((activity) => ({
color: 'blue',
children: (
<Space>
<Text>{activity.action}</Text>
<Text type="secondary">{activity.time}</Text>
</Space>
),
}))}
/>
</Card>
</Col>
{/* 答辩安排 */}
<Col xs={24} lg={12}>
<Card
title={
<Space>
<TrophyOutlined style={{ color: '#10b981' }} />
<span>近期答辩安排</span>
</Space>
}
style={{ borderRadius: 12 }}
>
<List
dataSource={[
{
student: '王芳',
training: '数据可视化看板',
time: '2026-07-20 14:00',
status: '待确认',
},
{
student: '张伟',
training: '企业内部管理系统',
time: '2026-07-22 10:00',
status: '已确认',
},
]}
renderItem={(item) => (
<List.Item>
<List.Item.Meta
avatar={<Avatar style={{ background: '#667eea' }}>{item.student.charAt(0)}</Avatar>}
title={item.student}
description={
<Space direction="vertical" size={0}>
<Text type="secondary">{item.training}</Text>
<Text type="secondary">{item.time}</Text>
</Space>
}
/>
<Tag color={item.status === '待确认' ? 'orange' : 'green'}>{item.status}</Tag>
</List.Item>
)}
/>
<Button block style={{ marginTop: 16 }}>查看全部答辩</Button>
</Card>
</Col>
</Row>
</div>
);
}
import { Empty } from 'antd';
import { Card, Row, Col, List, Avatar, Space, Button, Typography, Tag, Badge, Empty, Tabs, Modal, Form, Input, Select, DatePicker, Statistic } from 'antd';
import {
BellOutlined,
MailOutlined,
MessageOutlined,
CheckCircleOutlined,
ClockCircleOutlined,
TeamOutlined,
TrophyOutlined,
BookOutlined,
WarningOutlined,
SettingOutlined,
DeleteOutlined,
EyeOutlined,
ReloadOutlined
} from '@ant-design/icons';
import { useState } from 'react';
import { useAuthStore } from '../stores/useAuthStore';
const { Text, Title, Paragraph } = Typography;
const { TextArea } = Input;
type Notification = {
id: number;
type: 'system' | 'training' | 'defense' | 'message' | 'announcement';
title: string;
content: string;
sender?: string;
time: string;
isRead: boolean;
priority?: 'high' | 'normal' | 'low';
actions?: string[];
};
export default function NotificationPage() {
return <Empty description="通知 - 待接入" />;
const { user } = useAuthStore();
const [activeTab, setActiveTab] = useState('all');
const [selectedNotification, setSelectedNotification] = useState<Notification | null>(null);
const [detailModalVisible, setDetailModalVisible] = useState(false);
const [settingsModalVisible, setSettingsModalVisible] = useState(false);
// 通知数据
const notifications: Notification[] = [
{
id: 1,
type: 'defense',
title: '答辩时间已安排',
content: '您的"企业内部管理系统"实训答辩已安排在2026年7月20日 14:00,请准时参加。',
sender: '系统',
time: '30分钟前',
isRead: false,
priority: 'high',
actions: ['查看详情', '确认参加'],
},
{
id: 2,
type: 'training',
title: '导师点评已更新',
content: '您的实操报告已收到导师点评,请及时查看并根据反馈进行改进。',
sender: '张导师',
time: '2小时前',
isRead: false,
priority: 'normal',
actions: ['查看点评'],
},
{
id: 3,
type: 'system',
title: '实训进度提醒',
content: '您的"电商平台用户模块开发"实训还剩8天,请加快进度。',
time: '3小时前',
isRead: true,
priority: 'normal',
},
{
id: 4,
type: 'announcement',
title: '平台功能更新通知',
content: '实习生训练平台已更新至V2.1版本,新增AI智能推荐、难度自动校准等功能。',
time: '昨天',
isRead: true,
priority: 'low',
},
{
id: 5,
type: 'training',
title: '新实训已分配',
content: '您被分配到新的实训项目"微服务架构实战",难度L4,请及时查看。',
sender: '管理员',
time: '2天前',
isRead: true,
priority: 'normal',
},
{
id: 6,
type: 'message',
title: '导师消息',
content: '张导师:关于你的实操报告,技术方案部分需要补充时序图。',
sender: '张导师',
time: '3天前',
isRead: true,
},
{
id: 7,
type: 'system',
title: '密码修改成功',
content: '您的账号密码已成功修改,如非本人操作请联系管理员。',
time: '1周前',
isRead: true,
priority: 'low',
},
];
const unreadCount = notifications.filter(n => !n.isRead).length;
const getNotificationIcon = (type: string) => {
const icons: Record<string, React.ReactNode> = {
system: <BellOutlined style={{ color: '#667eea' }} />,
training: <BookOutlined style={{ color: '#10b981' }} />,
defense: <TrophyOutlined style={{ color: '#f59e0b' }} />,
message: <MessageOutlined style={{ color: '#ef4444' }} />,
announcement: <TeamOutlined style={{ color: '#6366f1' }} />,
};
return icons[type] || <BellOutlined />;
};
const getNotificationColor = (type: string) => {
const colors: Record<string, string> = {
system: '#667eea',
training: '#10b981',
defense: '#f59e0b',
message: '#ef4444',
announcement: '#6366f1',
};
return colors[type] || '#667eea';
};
const getPriorityTag = (priority?: string) => {
if (!priority || priority === 'normal') return null;
const tags: Record<string, { color: string; text: string }> = {
high: { color: 'red', text: '紧急' },
low: { color: 'default', text: '一般' },
};
const tag = tags[priority];
return <Tag color={tag.color}>{tag.text}</Tag>;
};
const handleNotificationClick = (notification: Notification) => {
setSelectedNotification(notification);
setDetailModalVisible(true);
// 实际应该调用API标记已读
};
const renderNotificationList = (filter: 'all' | 'unread') => {
const filteredNotifications = filter === 'all'
? notifications
: notifications.filter(n => !n.isRead);
if (filteredNotifications.length === 0) {
return (
<Empty
description={filter === 'unread' ? "暂无未读通知" : "暂无通知"}
image={Empty.PRESENTED_IMAGE_SIMPLE}
/>
);
}
return (
<List
dataSource={filteredNotifications}
renderItem={(item) => (
<List.Item
style={{
cursor: 'pointer',
background: item.isRead ? 'transparent' : 'rgba(102, 126, 234, 0.05)',
padding: '16px',
borderRadius: 8,
marginBottom: 8,
border: item.isRead ? '1px solid #f0f0f0' : '1px solid rgba(102, 126, 234, 0.2)',
}}
onClick={() => handleNotificationClick(item)}
>
<List.Item.Meta
avatar={
<Avatar
size={48}
style={{
background: `${getNotificationColor(item.type)}15`,
color: getNotificationColor(item.type)
}}
icon={getNotificationIcon(item.type)}
/>
}
title={
<Space>
{!item.isRead && <Badge status="processing" />}
<Text strong={!item.isRead}>{item.title}</Text>
{getPriorityTag(item.priority)}
</Space>
}
description={
<div>
<Paragraph
type="secondary"
ellipsis={{ rows: 2 }}
style={{ marginBottom: 8 }}
>
{item.content}
</Paragraph>
<Space size={16}>
<Text type="secondary" style={{ fontSize: 12 }}>
<ClockCircleOutlined /> {item.time}
</Text>
{item.sender && (
<Text type="secondary" style={{ fontSize: 12 }}>
<TeamOutlined /> {item.sender}
</Text>
)}
</Space>
</div>
}
/>
{!item.isRead && (
<Tag color="blue" style={{ position: 'absolute', top: 16, right: 16 }}>
新
</Tag>
)}
</List.Item>
)}
/>
);
};
// 统计卡片
const statsData = {
total: notifications.length,
unread: unreadCount,
system: notifications.filter(n => n.type === 'system').length,
training: notifications.filter(n => n.type === 'training').length,
defense: notifications.filter(n => n.type === 'defense').length,
};
return (
<div style={{ padding: '0 0 24px' }}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
<Title level={4} style={{ margin: 0 }}>通知中心</Title>
<Space>
<Badge count={unreadCount}>
<Button icon={<ReloadOutlined />}>刷新</Button>
</Badge>
<Button icon={<SettingOutlined />} onClick={() => setSettingsModalVisible(true)}>
通知设置
</Button>
</Space>
</div>
<Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
<Col xs={12} sm={6}>
<Card hoverable style={{ borderRadius: 12, textAlign: 'center' }}>
<Statistic
value={statsData.total}
prefix={<BellOutlined style={{ color: '#667eea' }} />}
suffix="条"
valueStyle={{ color: '#667eea' }}
/>
<Text type="secondary">全部通知</Text>
</Card>
</Col>
<Col xs={12} sm={6}>
<Card hoverable style={{ borderRadius: 12, textAlign: 'center' }}>
<Statistic
value={statsData.unread}
prefix={<WarningOutlined style={{ color: '#ef4444' }} />}
suffix="条"
valueStyle={{ color: '#ef4444' }}
/>
<Text type="secondary">未读通知</Text>
</Card>
</Col>
<Col xs={12} sm={6}>
<Card hoverable style={{ borderRadius: 12, textAlign: 'center' }}>
<Statistic
value={statsData.training}
prefix={<BookOutlined style={{ color: '#10b981' }} />}
suffix="条"
valueStyle={{ color: '#10b981' }}
/>
<Text type="secondary">实训通知</Text>
</Card>
</Col>
<Col xs={12} sm={6}>
<Card hoverable style={{ borderRadius: 12, textAlign: 'center' }}>
<Statistic
value={statsData.defense}
prefix={<TrophyOutlined style={{ color: '#f59e0b' }} />}
suffix="条"
valueStyle={{ color: '#f59e0b' }}
/>
<Text type="secondary">答辩通知</Text>
</Card>
</Col>
</Row>
<Card style={{ borderRadius: 12 }}>
<Tabs
activeKey={activeTab}
onChange={setActiveTab}
items={[
{
key: 'all',
label: (
<span>
<BellOutlined />
全部通知
</span>
),
children: renderNotificationList('all'),
},
{
key: 'unread',
label: (
<span>
<WarningOutlined />
未读通知
{unreadCount > 0 && (
<Badge count={unreadCount} style={{ marginLeft: 8 }} />
)}
</span>
),
children: renderNotificationList('unread'),
},
{
key: 'system',
label: (
<span>
<SettingOutlined />
系统通知
</span>
),
children: <div>{notifications.filter(n => n.type === 'system').length} 条系统通知</div>,
},
{
key: 'training',
label: (
<span>
<BookOutlined />
实训通知
</span>
),
children: null,
},
{
key: 'defense',
label: (
<span>
<TrophyOutlined />
答辩通知
</span>
),
children: null,
},
]}
/>
<div style={{ marginTop: 16, textAlign: 'center' }}>
<Space>
<Button icon={<CheckCircleOutlined />}>全部标为已读</Button>
<Button icon={<DeleteOutlined />} danger>清空已读</Button>
</Space>
</div>
</Card>
{/* 通知详情弹窗 */}
<Modal
title={
<Space>
<Avatar
size={40}
style={{
background: selectedNotification ? `${getNotificationColor(selectedNotification.type)}15` : '#f5f5f5',
color: selectedNotification ? getNotificationColor(selectedNotification.type) : '#666'
}}
icon={selectedNotification ? getNotificationIcon(selectedNotification.type) : <BellOutlined />}
/>
<div>
<Text strong>{selectedNotification?.title}</Text>
<br />
<Text type="secondary" style={{ fontSize: 12 }}>
{selectedNotification?.time}
</Text>
</div>
</Space>
}
open={detailModalVisible}
onCancel={() => setDetailModalVisible(false)}
footer={
<Space>
{selectedNotification?.actions?.map((action, index) => (
<Button
key={action}
type={index === 0 ? 'primary' : 'default'}
onClick={() => setDetailModalVisible(false)}
>
{action}
</Button>
))}
<Button onClick={() => setDetailModalVisible(false)}>关闭</Button>
</Space>
}
width={600}
>
{selectedNotification && (
<div>
<Paragraph style={{ fontSize: 16, lineHeight: 1.8 }}>
{selectedNotification.content}
</Paragraph>
{selectedNotification.sender && (
<div style={{ marginTop: 16 }}>
<Text type="secondary">发送人:{selectedNotification.sender}</Text>
</div>
)}
</div>
)}
</Modal>
{/* 通知设置弹窗 */}
<Modal
title="通知设置"
open={settingsModalVisible}
onCancel={() => setSettingsModalVisible(false)}
footer={null}
width={500}
>
<Form layout="vertical">
<Form.Item label="通知方式">
<Space direction="vertical">
<Form.Item name="email" valuePropName="checked" noStyle>
<Space>
<BellOutlined /> 系统通知 <Tag color="green">默认开启</Tag>
</Space>
</Form.Item>
<Form.Item name="app" valuePropName="checked" noStyle>
<Space>
<MailOutlined /> 邮件通知 <Tag>可选</Tag>
</Space>
</Form.Item>
</Space>
</Form.Item>
<Form.Item label="通知类型">
<Space direction="vertical">
<Form.Item name="systemNotify" valuePropName="checked" initialValue={true} noStyle>
<Space>
<SettingOutlined /> 系统通知
</Space>
</Form.Item>
<Form.Item name="trainingNotify" valuePropName="checked" initialValue={true} noStyle>
<Space>
<BookOutlined /> 实训通知
</Space>
</Form.Item>
<Form.Item name="defenseNotify" valuePropName="checked" initialValue={true} noStyle>
<Space>
<TrophyOutlined /> 答辩通知
</Space>
</Form.Item>
<Form.Item name="messageNotify" valuePropName="checked" initialValue={true} noStyle>
<Space>
<MessageOutlined /> 导师消息
</Space>
</Form.Item>
</Space>
</Form.Item>
<Form.Item label="免打扰时间">
<Space>
<DatePicker.RangePicker />
<Text type="secondary">设置后将不在此时间段内推送通知</Text>
</Space>
</Form.Item>
<Form.Item>
<Space>
<Button type="primary">保存设置</Button>
<Button onClick={() => setSettingsModalVisible(false)}>取消</Button>
</Space>
</Form.Item>
</Form>
</Modal>
</div>
);
}
/**
* 角色管理页面
* 支持角色 CRUD 和权限分配
*/
import { useState, useEffect } from 'react';
import {
Table,
Button,
Space,
Modal,
Form,
Input,
Select,
message,
Popconfirm,
Tag,
Card,
Tree,
Divider,
Alert,
} from 'antd';
import {
PlusOutlined,
EditOutlined,
DeleteOutlined,
SafetyOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import type { DataNode } from 'antd/es/tree';
import {
roleApi,
PERMISSION_CODES,
MODULE_NAMES,
Permission,
Role,
} from '../services/permissionApi';
import { HasPermission } from '../components/PermissionGuard';
const RoleManagementPage: React.FC = () => {
const [roles, setRoles] = useState<Role[]>([]);
const [permissions, setPermissions] = useState<Permission[]>([]);
const [loading, setLoading] = useState(false);
const [modalVisible, setModalVisible] = useState(false);
const [permModalVisible, setPermModalVisible] = useState(false);
const [editingRole, setEditingRole] = useState<Role | null>(null);
const [selectedRole, setSelectedRole] = useState<Role | null>(null);
const [selectedPermIds, setSelectedPermIds] = useState<number[]>([]);
const [form] = Form.useForm();
const [loadingPerms, setLoadingPerms] = useState(false);
// 加载角色列表
const loadRoles = async () => {
setLoading(true);
try {
const result = await roleApi.listRoles();
setRoles(result);
} catch (error) {
message.error('加载角色列表失败');
} finally {
setLoading(false);
}
};
// 加载权限列表
const loadPermissions = async () => {
try {
const result = await roleApi.listPermissions();
setPermissions(result);
} catch (error) {
message.error('加载权限列表失败');
}
};
useEffect(() => {
loadRoles();
loadPermissions();
}, []);
// 构建权限树形数据
const buildPermissionTree = (): DataNode[] => {
// 按模块分组
const moduleMap = new Map<string, Permission[]>();
permissions.forEach((perm) => {
const module = perm.module || 'other';
if (!moduleMap.has(module)) {
moduleMap.set(module, []);
}
moduleMap.get(module)!.push(perm);
});
// 构建树节点
const nodes: DataNode[] = [];
moduleMap.forEach((perms, module) => {
nodes.push({
title: MODULE_NAMES[module] || module,
key: `module_${module}`,
selectable: false,
children: perms.map((perm) => ({
title: perm.permissionName,
key: perm.id.toString(),
})),
});
});
return nodes;
};
// 打开创建角色弹窗
const handleCreate = () => {
setEditingRole(null);
form.resetFields();
setModalVisible(true);
};
// 打开编辑角色弹窗
const handleEdit = (role: Role) => {
setEditingRole(role);
form.setFieldsValue({
roleName: role.roleName,
description: role.description,
sort: role.sort,
status: role.status,
});
setModalVisible(true);
};
// 提交表单
const handleSubmit = async () => {
try {
const values = await form.validateFields();
if (editingRole) {
await roleApi.updateRole(editingRole.id, values);
message.success('更新角色成功');
} else {
await roleApi.createRole(values);
message.success('创建角色成功');
}
setModalVisible(false);
loadRoles();
} catch (error: any) {
if (error.errorFields) return;
message.error(error.response?.data?.message || '操作失败');
}
};
// 删除角色
const handleDelete = async (roleId: number) => {
try {
await roleApi.deleteRole(roleId);
message.success('删除角色成功');
loadRoles();
} catch (error: any) {
message.error(error.response?.data?.message || '删除角色失败');
}
};
// 打开权限分配弹窗
const handleAssignPermissions = async (role: Role) => {
setSelectedRole(role);
setLoadingPerms(true);
setPermModalVisible(true);
try {
// 获取角色详情(含权限)
const roleDetail = await roleApi.getRoleById(role.id);
setSelectedPermIds(
roleDetail.permissions?.map((p) => p.id) || []
);
} catch (error) {
message.error('加载角色权限失败');
} finally {
setLoadingPerms(false);
}
};
// 提交权限分配
const handlePermSubmit = async () => {
try {
// 先更新角色信息(如果需要)
// 然后分配权限
await roleApi.updateRole(selectedRole!.id, {
permissionIds: selectedPermIds,
});
message.success('权限分配成功');
setPermModalVisible(false);
loadRoles();
} catch (error: any) {
message.error(error.response?.data?.message || '权限分配失败');
}
};
// 表格列定义
const columns: ColumnsType<Role> = [
{
title: 'ID',
dataIndex: 'id',
key: 'id',
width: 80,
},
{
title: '角色名称',
dataIndex: 'roleName',
key: 'roleName',
},
{
title: '角色编码',
dataIndex: 'roleCode',
key: 'roleCode',
},
{
title: '描述',
dataIndex: 'description',
key: 'description',
},
{
title: '类型',
dataIndex: 'isPreset',
key: 'isPreset',
render: (isPreset: boolean) => (
<Tag color={isPreset ? 'blue' : 'default'}>
{isPreset ? '预置角色' : '自定义'}
</Tag>
),
},
{
title: '状态',
dataIndex: 'status',
key: 'status',
render: (status: number) => (
<Tag color={status === 1 ? 'success' : 'error'}>
{status === 1 ? '启用' : '禁用'}
</Tag>
),
},
{
title: '用户数',
dataIndex: 'userCount',
key: 'userCount',
},
{
title: '操作',
key: 'action',
width: 250,
render: (_, record) => (
<Space size="small">
<Button
type="link"
size="small"
icon={<SafetyOutlined />}
onClick={() => handleAssignPermissions(record)}
>
分配权限
</Button>
{!record.isPreset && (
<>
<Button
type="link"
size="small"
icon={<EditOutlined />}
onClick={() => handleEdit(record)}
>
编辑
</Button>
<Popconfirm
title="确定删除该角色?"
onConfirm={() => handleDelete(record.id)}
okText="确定"
cancelText="取消"
>
<Button type="link" size="small" danger icon={<DeleteOutlined />}>
删除
</Button>
</Popconfirm>
</>
)}
</Space>
),
},
];
return (
<div>
<Card
title="角色管理"
extra={
<HasPermission permission={PERMISSION_CODES.ROLE_CREATE}>
<Button type="primary" icon={<PlusOutlined />} onClick={handleCreate}>
创建角色
</Button>
</HasPermission>
}
>
{/* 角色表格 */}
<Table
columns={columns}
dataSource={roles}
rowKey="id"
loading={loading}
pagination={false}
/>
</Card>
{/* 创建/编辑角色弹窗 */}
<Modal
title={editingRole ? '编辑角色' : '创建角色'}
open={modalVisible}
onOk={handleSubmit}
onCancel={() => setModalVisible(false)}
width={500}
>
<Form form={form} layout="vertical">
<Form.Item
name="roleName"
label="角色名称"
rules={[{ required: true, message: '请输入角色名称' }]}
>
<Input disabled={editingRole?.isPreset} />
</Form.Item>
<Form.Item name="description" label="描述">
<Input.TextArea rows={3} />
</Form.Item>
<Form.Item name="sort" label="排序" initialValue={0}>
<Input type="number" />
</Form.Item>
<Form.Item name="status" label="状态" initialValue={1}>
<Select>
<Select.Option value={1}>启用</Select.Option>
<Select.Option value={0}>禁用</Select.Option>
</Select>
</Form.Item>
</Form>
</Modal>
{/* 权限分配弹窗 */}
<Modal
title={
<span>
分配权限 - <strong>{selectedRole?.roleName}</strong>
</span>
}
open={permModalVisible}
onOk={handlePermSubmit}
onCancel={() => setPermModalVisible(false)}
width={600}
okText="保存"
cancelText="取消"
>
{selectedRole?.isPreset && (
<Alert
message="预置角色"
description="预置角色的权限分配将影响所有该角色的用户,请谨慎操作。"
type="warning"
showIcon
style={{ marginBottom: 16 }}
/>
)}
<Divider>选择权限</Divider>
<div style={{ maxHeight: 400, overflow: 'auto' }}>
<Tree
checkable
selectable={false}
defaultExpandAll
checkedKeys={selectedPermIds.map((id) => id.toString())}
onCheck={(checked) => {
const keys = checked as string[];
setSelectedPermIds(
keys
.filter((k) => !k.startsWith('module_'))
.map((k) => parseInt(k))
);
}}
treeData={buildPermissionTree()}
/>
</div>
<Divider />
<div style={{ color: '#666', fontSize: 12 }}>
已选择 {selectedPermIds.length} 个权限
</div>
</Modal>
</div>
);
};
export default RoleManagementPage;
import { Card, Row, Col, Progress, Tag, Timeline, Statistic, List, Avatar, Space, Button, Divider, Typography, Empty, Badge } from 'antd';
import {
BookOutlined,
TrophyOutlined,
ClockCircleOutlined,
CheckCircleOutlined,
RocketOutlined,
TeamOutlined,
FireOutlined,
RiseOutlined,
AimOutlined,
BulbOutlined,
GlobalOutlined,
DatabaseOutlined,
CodeOutlined
} from '@ant-design/icons';
import { useAuthStore } from '../stores/useAuthStore';
const { Text, Title } = Typography;
export default function StudentDashboard() {
const { user } = useAuthStore();
// 模拟数据
const profileData = {
overall: 78,
skills: [
{ name: '前端开发', score: 85, icon: <CodeOutlined /> },
{ name: '后端开发', score: 72, icon: <GlobalOutlined /> },
{ name: '数据处理', score: 68, icon: <DatabaseOutlined /> },
{ name: '问题分析', score: 82, icon: <BulbOutlined /> },
],
strengths: ['React技术栈', 'TypeScript', '团队协作'],
weaknesses: ['系统设计', '性能优化'],
};
const currentTraining = {
name: '电商平台用户模块开发',
progress: 65,
stage: '实操阶段',
stageProgress: 40,
deadline: '2026-07-25',
daysLeft: 8,
mentor: '张导师',
};
const trainingHistory = [
{
name: '企业内部管理系统',
difficulty: 'L3',
score: 92,
date: '2026-06-15',
status: '已完成',
badge: '优秀',
},
{
name: '数据可视化看板',
difficulty: 'L2',
score: 85,
date: '2026-05-20',
status: '已完成',
badge: '良好',
},
{
name: 'RESTful API设计',
difficulty: 'L2',
score: 88,
date: '2026-04-28',
status: '已完成',
badge: '优秀',
},
];
const pendingTasks = [
{ title: '完成模块接口文档', deadline: '明天', priority: 'high' },
{ title: '提交实操产物', deadline: '3天后', priority: 'medium' },
{ title: '完成预习小测', deadline: '1天后', priority: 'low' },
];
const recentActivities = [
{ action: '完成预览任务', time: '2小时前', icon: <CheckCircleOutlined /> },
{ action: '收到导师点评', time: '昨天', icon: <TeamOutlined /> },
{ action: '提交实操报告', time: '2天前', icon: <RocketOutlined /> },
{ action: '通过答辩评审', time: '上周', icon: <TrophyOutlined /> },
];
const difficultyColor = (level: string) => {
const colors: Record<string, string> = {
'L1': 'green', 'L2': 'cyan', 'L3': 'blue', 'L4': 'orange', 'L5': 'red'
};
return colors[level] || 'default';
};
return (
<div style={{ padding: '0 0 24px' }}>
{/* 欢迎区域 */}
<div style={{
background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
borderRadius: 16,
padding: 32,
marginBottom: 24,
color: 'white',
position: 'relative',
overflow: 'hidden'
}}>
<div style={{
position: 'absolute',
top: -50,
right: -50,
width: 200,
height: 200,
borderRadius: '50%',
background: 'rgba(255,255,255,0.1)'
}} />
<div style={{
position: 'absolute',
bottom: -30,
left: '30%',
width: 100,
height: 100,
borderRadius: '50%',
background: 'rgba(255,255,255,0.05)'
}} />
<Row gutter={24} align="middle" style={{ position: 'relative', zIndex: 1 }}>
<Col flex="none">
<Avatar size={80} style={{ background: 'rgba(255,255,255,0.2)', fontSize: 32 }}>
{user?.realName?.charAt(0) || '学'}
</Avatar>
</Col>
<Col flex="auto">
<Title level={2} style={{ color: 'white', margin: 0 }}>
欢迎回来,{user?.realName || '学员'}!
</Title>
<Text style={{ color: 'rgba(255,255,255,0.85)', fontSize: 16 }}>
继续加油,保持你的学习节奏 💪
</Text>
</Col>
<Col flex="none">
<div style={{ textAlign: 'center' }}>
<Statistic
value={currentTraining.daysLeft}
suffix="天"
valueStyle={{ color: 'white', fontSize: 36 }}
prefix={<ClockCircleOutlined />}
/>
<Text style={{ color: 'rgba(255,255,255,0.7)' }}>当前实训剩余</Text>
</div>
</Col>
</Row>
</div>
{/* 统计卡片 */}
<Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
<Col xs={24} sm={12} lg={6}>
<Card hoverable style={{ borderRadius: 12 }}>
<Statistic
title="我的实训"
value={3}
suffix="个"
prefix={<BookOutlined style={{ color: '#667eea' }} />}
valueStyle={{ color: '#667eea' }}
/>
<Text type="secondary">已完成 3 个实训项目</Text>
</Card>
</Col>
<Col xs={24} sm={12} lg={6}>
<Card hoverable style={{ borderRadius: 12 }}>
<Statistic
title="平均得分"
value={88}
suffix="分"
prefix={<TrophyOutlined style={{ color: '#f59e0b' }} />}
valueStyle={{ color: '#f59e0b' }}
/>
<Text type="secondary">较上月提升 +5 分</Text>
</Card>
</Col>
<Col xs={24} sm={12} lg={6}>
<Card hoverable style={{ borderRadius: 12 }}>
<Statistic
title="能力等级"
value="L3"
prefix={<RiseOutlined style={{ color: '#10b981' }} />}
valueStyle={{ color: '#10b981' }}
/>
<Text type="secondary">建议挑战 L4 项目</Text>
</Card>
</Col>
<Col xs={24} sm={12} lg={6}>
<Card hoverable style={{ borderRadius: 12 }}>
<Statistic
title="待办任务"
value={pendingTasks.length}
suffix="项"
prefix={<ClockCircleOutlined style={{ color: '#ef4444' }} />}
valueStyle={{ color: '#ef4444' }}
/>
<Text type="secondary">点击查看详情</Text>
</Card>
</Col>
</Row>
<Row gutter={[16, 16]}>
{/* 当前实训进度 */}
<Col xs={24} lg={16}>
<Card
title={
<Space>
<RocketOutlined style={{ color: '#667eea' }} />
<span>当前实训</span>
<Tag color="blue">{currentTraining.stage}</Tag>
</Space>
}
style={{ borderRadius: 12, height: '100%' }}
extra={<Button type="link">查看详情</Button>}
>
<div style={{ marginBottom: 24 }}>
<Title level={4}>{currentTraining.name}</Title>
<Space style={{ marginBottom: 16 }}>
<Tag color="orange">L3 中等难度</Tag>
<Tag icon={<TeamOutlined />}>导师: {currentTraining.mentor}</Tag>
<Tag icon={<ClockCircleOutlined />}>截止: {currentTraining.deadline}</Tag>
</Space>
</div>
<Row gutter={16} style={{ marginBottom: 24 }}>
<Col span={12}>
<div style={{ marginBottom: 8 }}>
<Text strong>整体进度</Text>
<Text type="secondary" style={{ float: 'right' }}>{currentTraining.progress}%</Text>
</div>
<Progress percent={currentTraining.progress} strokeColor="#667eea" showInfo={false} />
</Col>
<Col span={12}>
<div style={{ marginBottom: 8 }}>
<Text strong>阶段进度</Text>
<Text type="secondary" style={{ float: 'right' }}>{currentTraining.stageProgress}%</Text>
</div>
<Progress percent={currentTraining.stageProgress} strokeColor="#10b981" showInfo={false} />
</Col>
</Row>
<Divider style={{ margin: '16px 0' }} />
<Title level={5} style={{ marginBottom: 16 }}>实训阶段</Title>
<Timeline
items={[
{ color: 'green', children: (
<div>
<Text strong>需求分析</Text>
<Tag color="green" style={{ marginLeft: 8 }}>已完成</Tag>
</div>
)},
{ color: 'green', children: (
<div>
<Text strong>预览阶段</Text>
<Tag color="green" style={{ marginLeft: 8 }}>已完成</Tag>
</div>
)},
{ color: 'blue', children: (
<div>
<Text strong>实操阶段</Text>
<Tag color="blue" style={{ marginLeft: 8 }}>进行中</Tag>
<Text type="secondary" style={{ display: 'block', fontSize: 12 }}>完成容器环境搭建和核心代码编写</Text>
</div>
)},
{ color: 'gray', children: (
<div>
<Text type="secondary">答辩评审</Text>
<Tag style={{ marginLeft: 8 }}>待开始</Tag>
</div>
)},
]}
/>
</Card>
</Col>
{/* 待办任务 */}
<Col xs={24} lg={8}>
<Card
title={
<Space>
<AimOutlined style={{ color: '#ef4444' }} />
<span>待办任务</span>
<Badge count={pendingTasks.length} style={{ backgroundColor: '#ef4444' }} />
</Space>
}
style={{ borderRadius: 12, height: '100%' }}
>
<List
dataSource={pendingTasks}
renderItem={(item) => (
<List.Item style={{ padding: '12px 0' }}>
<List.Item.Meta
avatar={
<Badge status={item.priority === 'high' ? 'error' : item.priority === 'medium' ? 'warning' : 'success'} />
}
title={<Text>{item.title}</Text>}
description={<Text type="secondary">{item.deadline}</Text>}
/>
</List.Item>
)}
/>
<Button block style={{ marginTop: 16 }}>查看全部待办</Button>
</Card>
</Col>
{/* 能力画像 */}
<Col xs={24} lg={12}>
<Card
title={
<Space>
<FireOutlined style={{ color: '#f59e0b' }} />
<span>能力画像</span>
</Space>
}
style={{ borderRadius: 12 }}
>
<Row gutter={[16, 16]}>
<Col span={8}>
<div style={{ textAlign: 'center' }}>
<Progress type="circle" percent={profileData.overall} strokeColor="#667eea" />
<Text style={{ display: 'block', marginTop: 8 }}>综合能力</Text>
</div>
</Col>
<Col span={16}>
{profileData.skills.map((skill) => (
<div key={skill.name} style={{ marginBottom: 12 }}>
<Space>
{skill.icon}
<Text>{skill.name}</Text>
</Space>
<Progress percent={skill.score} strokeColor="#10b981" showInfo={false} size="small" />
</div>
))}
</Col>
</Row>
<Divider style={{ margin: '16px 0' }} />
<Space wrap>
<Text type="secondary">优势:</Text>
{profileData.strengths.map((s) => (
<Tag key={s} color="green">{s}</Tag>
))}
</Space>
<div style={{ marginTop: 8 }}>
<Space wrap>
<Text type="secondary">待提升:</Text>
{profileData.weaknesses.map((w) => (
<Tag key={w} color="orange">{w}</Tag>
))}
</Space>
</div>
</Card>
</Col>
{/* 近期活动 */}
<Col xs={24} lg={12}>
<Card
title={
<Space>
<ClockCircleOutlined style={{ color: '#6366f1' }} />
<span>近期活动</span>
</Space>
}
style={{ borderRadius: 12 }}
>
<Timeline
items={recentActivities.map((activity) => ({
color: 'blue',
icon: activity.icon,
children: (
<Space>
<Text>{activity.action}</Text>
<Text type="secondary">{activity.time}</Text>
</Space>
),
}))}
/>
</Card>
</Col>
{/* 实训历史 */}
<Col span={24}>
<Card
title={
<Space>
<TrophyOutlined style={{ color: '#10b981' }} />
<span>实训历史</span>
</Space>
}
style={{ borderRadius: 12 }}
>
<List
dataSource={trainingHistory}
renderItem={(item) => (
<List.Item
actions={[
<Button type="link" key="view">查看详情</Button>,
<Button type="link" key="review">回顾总结</Button>
]}
>
<List.Item.Meta
avatar={<Avatar size={48} style={{ background: 'linear-gradient(135deg, #667eea, #764ba2)' }}>{item.score}</Avatar>}
title={
<Space>
<Text strong>{item.name}</Text>
<Tag color={difficultyColor(item.difficulty)}>{item.difficulty}</Tag>
{item.badge && <Tag color="gold">{item.badge}</Tag>}
</Space>
}
description={
<Space>
<Text type="secondary">完成日期: {item.date}</Text>
<Divider type="vertical" />
<Text type="secondary">得分: {item.score}分</Text>
</Space>
}
/>
</List.Item>
)}
/>
</Card>
</Col>
</Row>
</div>
);
}
import { Card, Row, Col, Table, Tag, Timeline, Statistic, List, Avatar, Space, Button, Divider, Typography, Progress, Badge, Select, DatePicker, Drawer, Descriptions, Rate } from 'antd';
import {
SafetyOutlined,
TeamOutlined,
TrophyOutlined,
ClockCircleOutlined,
AlertOutlined,
CheckCircleOutlined,
RiseOutlined,
FileTextOutlined,
CalendarOutlined,
PieChartOutlined,
EyeOutlined,
EditOutlined,
AuditOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { useState } from 'react';
import { useAuthStore } from '../stores/useAuthStore';
const { Text, Title } = Typography;
type AuditItem = {
id: number;
type: 'defense' | 'training' | 'calibration';
student: string;
training: string;
mentor: string;
status: 'pending' | 'approved' | 'rejected';
score?: number;
applyTime: string;
};
type StudentProfile = {
id: number;
name: string;
department: string;
training: string;
score: number;
progress: number;
strengths: string[];
weaknesses: string[];
history: Array<{
training: string;
score: number;
date: string;
}>;
};
export default function SupervisorDashboard() {
const { user } = useAuthStore();
const [selectedStudent, setSelectedStudent] = useState<StudentProfile | null>(null);
const [drawerVisible, setDrawerVisible] = useState(false);
// 统计数据
const statsData = {
totalStudents: 48,
pendingAudits: 12,
completedThisMonth: 8,
averageScore: 86.5,
difficultyStats: {
L1: 15, L2: 20, L3: 10, L4: 3, L5: 0
}
};
// 待审核列表
const auditItems: AuditItem[] = [
{
id: 1,
type: 'defense',
student: '王芳',
training: '数据可视化看板',
mentor: '张导师',
status: 'pending',
score: 92,
applyTime: '2026-07-17 09:00',
},
{
id: 2,
type: 'calibration',
student: '李明',
training: '电商平台用户模块',
mentor: '张导师',
status: 'pending',
applyTime: '2026-07-17 10:30',
},
{
id: 3,
type: 'defense',
student: '刘洋',
training: '企业内部管理系统',
mentor: '王导师',
status: 'pending',
score: 88,
applyTime: '2026-07-16 14:00',
},
{
id: 4,
type: 'training',
student: '陈静',
training: '微服务架构实战',
mentor: '王导师',
status: 'pending',
applyTime: '2026-07-16 16:00',
},
];
// 学员能力总览
const studentProfiles: StudentProfile[] = [
{
id: 1,
name: '王芳',
department: '技术部',
training: '数据可视化看板',
score: 92,
progress: 100,
strengths: ['前端开发', '数据可视化', 'React'],
weaknesses: ['系统设计'],
history: [
{ training: '企业内部管理系统', score: 95, date: '2026-06' },
{ training: 'RESTful API设计', score: 88, date: '2026-05' },
]
},
{
id: 2,
name: '李明',
department: '技术部',
training: '电商平台用户模块',
score: 85,
progress: 65,
strengths: ['后端开发', '数据库设计'],
weaknesses: ['性能优化', '前端开发'],
history: [
{ training: '数据可视化看板', score: 85, date: '2026-06' },
]
},
{
id: 3,
name: '张伟',
department: '标注部',
training: '已完成',
score: 90,
progress: 100,
strengths: ['标注质量', '团队协作'],
weaknesses: ['新技术学习'],
history: [
{ training: '企业内部管理系统', score: 90, date: '2026-05' },
{ training: '标注任务管理', score: 92, date: '2026-04' },
]
},
];
const auditColumns: ColumnsType<AuditItem> = [
{
title: '类型',
dataIndex: 'type',
width: 100,
render: (type) => (
<Tag color={
type === 'defense' ? 'blue' :
type === 'calibration' ? 'purple' : 'green'
}>
{type === 'defense' ? '答辩' : type === 'calibration' ? '校准' : '实训'}
</Tag>
),
},
{
title: '学员',
dataIndex: 'student',
render: (student) => <Text strong>{student}</Text>,
},
{
title: '实训项目',
dataIndex: 'training',
},
{
title: '导师',
dataIndex: 'mentor',
render: (mentor) => <Tag>{mentor}</Tag>,
},
{
title: '评分',
dataIndex: 'score',
render: (score) => score ? (
<Text strong style={{ color: score >= 90 ? '#10b981' : score >= 80 ? '#f59e0b' : '#ef4444' }}>
{score}分
</Text>
) : '-',
},
{
title: '申请时间',
dataIndex: 'applyTime',
render: (time) => <Text type="secondary">{time}</Text>,
},
{
title: '操作',
width: 180,
render: (_, record) => (
<Space>
<Button size="small" icon={<EyeOutlined />}>查看</Button>
<Button size="small" type="primary" icon={<CheckCircleOutlined />}>通过</Button>
<Button size="small" danger icon={<EditOutlined />}>驳回</Button>
</Space>
),
},
];
const handleViewProfile = (profile: StudentProfile) => {
setSelectedStudent(profile);
setDrawerVisible(true);
};
return (
<div style={{ padding: '0 0 24px' }}>
{/* 欢迎区域 */}
<div style={{
background: 'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)',
borderRadius: 16,
padding: 32,
marginBottom: 24,
color: 'white',
position: 'relative',
overflow: 'hidden'
}}>
<div style={{
position: 'absolute',
top: -50,
right: 50,
width: 200,
height: 200,
borderRadius: '50%',
background: 'rgba(255,255,255,0.1)'
}} />
<Row gutter={24} align="middle" style={{ position: 'relative', zIndex: 1 }}>
<Col flex="none">
<Avatar size={80} style={{ background: 'rgba(255,255,255,0.2)', fontSize: 32 }}>
{user?.realName?.charAt(0) || '管'}
</Avatar>
</Col>
<Col flex="auto">
<Title level={2} style={{ color: 'white', margin: 0 }}>
主管工作台,{user?.realName || '主管'}!
</Title>
<Text style={{ color: 'rgba(255,255,255,0.85)', fontSize: 16 }}>
全面把控实训质量,助力人才培养 🎯
</Text>
</Col>
<Col flex="none">
<Space size={24}>
<div style={{ textAlign: 'center' }}>
<Statistic
value={statsData.pendingAudits}
suffix="项"
valueStyle={{ color: 'white', fontSize: 36 }}
/>
<Text style={{ color: 'rgba(255,255,255,0.7)' }}>待审核</Text>
</div>
<div style={{ textAlign: 'center' }}>
<Statistic
value={statsData.averageScore}
suffix="分"
precision={1}
valueStyle={{ color: 'white', fontSize: 36 }}
/>
<Text style={{ color: 'rgba(255,255,255,0.7)' }}>平均分</Text>
</div>
</Space>
</Col>
</Row>
</div>
{/* 统计概览 */}
<Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
<Col xs={24} sm={12} lg={6}>
<Card hoverable style={{ borderRadius: 12 }}>
<Statistic
title="总学员数"
value={statsData.totalStudents}
suffix="人"
prefix={<TeamOutlined style={{ color: '#667eea' }} />}
valueStyle={{ color: '#667eea' }}
/>
<Text type="secondary">技术部 32 人 / 标注部 16 人</Text>
</Card>
</Col>
<Col xs={24} sm={12} lg={6}>
<Card hoverable style={{ borderRadius: 12 }}>
<Statistic
title="待审核"
value={statsData.pendingAudits}
suffix="项"
prefix={<AuditOutlined style={{ color: '#f5576c' }} />}
valueStyle={{ color: '#f5576c' }}
/>
<Tag color="red" style={{ marginTop: 8 }}>需尽快处理</Tag>
</Card>
</Col>
<Col xs={24} sm={12} lg={6}>
<Card hoverable style={{ borderRadius: 12 }}>
<Statistic
title="本月完成"
value={statsData.completedThisMonth}
suffix="人"
prefix={<TrophyOutlined style={{ color: '#10b981' }} />}
valueStyle={{ color: '#10b981' }}
/>
<Text type="secondary">通过率 87.5%</Text>
</Card>
</Col>
<Col xs={24} sm={12} lg={6}>
<Card hoverable style={{ borderRadius: 12 }}>
<Statistic
title="平均得分"
value={statsData.averageScore}
suffix="分"
precision={1}
prefix={<RiseOutlined style={{ color: '#f59e0b' }} />}
valueStyle={{ color: '#f59e0b' }}
/>
<Text type="secondary" style={{ color: '#10b981' }}>较上季度 +2.3 分</Text>
</Card>
</Col>
</Row>
{/* 难度分布 */}
<Card
title={
<Space>
<PieChartOutlined style={{ color: '#667eea' }} />
<span>实训难度分布</span>
</Space>
}
style={{ borderRadius: 12, marginBottom: 24 }}
>
<Row gutter={[16, 16]}>
{Object.entries(statsData.difficultyStats).map(([level, count]) => (
<Col key={level} xs={12} sm={8} md={4}>
<Card size="small" style={{ borderRadius: 8, textAlign: 'center' }}>
<Tag color={
level === 'L1' ? 'green' :
level === 'L2' ? 'cyan' :
level === 'L3' ? 'blue' :
level === 'L4' ? 'orange' : 'red'
} style={{ marginBottom: 8 }}>
{level}
</Tag>
<Statistic value={count} suffix="人" />
</Card>
</Col>
))}
</Row>
</Card>
<Row gutter={[16, 16]}>
{/* 待审核列表 */}
<Col xs={24} lg={14}>
<Card
title={
<Space>
<AlertOutlined style={{ color: '#f5576c' }} />
<span>待审核事项</span>
<Badge count={statsData.pendingAudits} style={{ backgroundColor: '#f5576c' }} />
</Space>
}
style={{ borderRadius: 12 }}
extra={
<Space>
<Select defaultValue="all" style={{ width: 120 }}>
<Select.Option value="all">全部类型</Select.Option>
<Select.Option value="defense">答辩审核</Select.Option>
<Select.Option value="calibration">难度校准</Select.Option>
<Select.Option value="training">实训审核</Select.Option>
</Select>
<Button>导出</Button>
</Space>
}
>
<Table
columns={auditColumns}
dataSource={auditItems}
rowKey="id"
pagination={false}
size="small"
/>
</Card>
</Col>
{/* 快捷入口 */}
<Col xs={24} lg={10}>
<Card
title={
<Space>
<SafetyOutlined style={{ color: '#667eea' }} />
<span>管理功能</span>
</Space>
}
style={{ borderRadius: 12 }}
>
<Space direction="vertical" style={{ width: '100%' }} size={12}>
<Button block size="large" icon={<TeamOutlined />}>
学员管理
</Button>
<Button block size="large" icon={<CalendarOutlined />}>
答辩安排
</Button>
<Button block size="large" icon={<FileTextOutlined />}>
难度校准
</Button>
<Button block size="large" icon={<PieChartOutlined />}>
数据统计
</Button>
</Space>
</Card>
</Col>
{/* 学员能力总览 */}
<Col span={24}>
<Card
title={
<Space>
<RiseOutlined style={{ color: '#10b981' }} />
<span>学员能力总览</span>
</Space>
}
style={{ borderRadius: 12 }}
extra={
<Space>
<Select defaultValue="all" style={{ width: 120 }}>
<Select.Option value="all">全部部门</Select.Option>
<Select.Option value="tech">技术部</Select.Option>
<Select.Option value="annotation">标注部</Select.Option>
</Select>
<Button type="primary">查看全部</Button>
</Space>
}
>
<Row gutter={[16, 16]}>
{studentProfiles.map((profile) => (
<Col key={profile.id} xs={24} sm={12} lg={8}>
<Card
hoverable
style={{ borderRadius: 12 }}
onClick={() => handleViewProfile(profile)}
>
<div style={{ textAlign: 'center', marginBottom: 16 }}>
<Avatar size={64} style={{ background: 'linear-gradient(135deg, #667eea, #764ba2)', fontSize: 24 }}>
{profile.name.charAt(0)}
</Avatar>
<Title level={4} style={{ marginTop: 12, marginBottom: 4 }}>
{profile.name}
</Title>
<Space>
<Tag>{profile.department}</Tag>
<Tag color={profile.progress === 100 ? 'green' : 'blue'}>
{profile.progress === 100 ? '已完成' : '进行中'}
</Tag>
</Space>
</div>
<div style={{ marginBottom: 12 }}>
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4 }}>
<Text type="secondary">当前实训</Text>
<Text>{profile.training}</Text>
</div>
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4 }}>
<Text type="secondary">综合评分</Text>
<Text strong style={{ color: '#10b981' }}>{profile.score}分</Text>
</div>
<div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4 }}>
<Text type="secondary">实训进度</Text>
<Text>{profile.progress}%</Text>
</div>
<Progress percent={profile.progress} size="small" strokeColor="#667eea" />
</div>
<Divider style={{ margin: '12px 0' }} />
<div style={{ marginBottom: 8 }}>
<Text type="secondary" style={{ fontSize: 12 }}>优势:</Text>
<div style={{ marginTop: 4 }}>
{profile.strengths.map((s) => (
<Tag key={s} color="green" style={{ marginBottom: 4 }}>{s}</Tag>
))}
</div>
</div>
<div>
<Text type="secondary" style={{ fontSize: 12 }}>待提升:</Text>
<div style={{ marginTop: 4 }}>
{profile.weaknesses.map((w) => (
<Tag key={w} color="orange" style={{ marginBottom: 4 }}>{w}</Tag>
))}
</div>
</div>
<Button block style={{ marginTop: 16 }} icon={<EyeOutlined />}>
查看详情
</Button>
</Card>
</Col>
))}
</Row>
</Card>
</Col>
</Row>
{/* 学员详情抽屉 */}
<Drawer
title="学员能力画像"
width={600}
open={drawerVisible}
onClose={() => setDrawerVisible(false)}
>
{selectedStudent && (
<div>
<Card style={{ marginBottom: 16 }}>
<Row gutter={16} align="middle">
<Col>
<Avatar size={80} style={{ background: 'linear-gradient(135deg, #667eea, #764ba2)', fontSize: 32 }}>
{selectedStudent.name.charAt(0)}
</Avatar>
</Col>
<Col flex="auto">
<Title level={3} style={{ marginBottom: 4 }}>{selectedStudent.name}</Title>
<Space>
<Tag>{selectedStudent.department}</Tag>
<Tag color="green">综合评分: {selectedStudent.score}分</Tag>
</Space>
</Col>
</Row>
</Card>
<Descriptions bordered column={2} style={{ marginBottom: 16 }}>
<Descriptions.Item label="当前实训" span={2}>
{selectedStudent.training}
</Descriptions.Item>
<Descriptions.Item label="实训进度">
<Progress percent={selectedStudent.progress} size="small" />
</Descriptions.Item>
<Descriptions.Item label="实训状态">
<Tag color={selectedStudent.progress === 100 ? 'green' : 'blue'}>
{selectedStudent.progress === 100 ? '已完成' : '进行中'}
</Tag>
</Descriptions.Item>
</Descriptions>
<Card title="能力分析" style={{ marginBottom: 16 }}>
<div style={{ marginBottom: 12 }}>
<Text type="secondary">优势领域:</Text>
<div style={{ marginTop: 8 }}>
{selectedStudent.strengths.map((s) => (
<Tag key={s} color="green" style={{ marginBottom: 4 }}>{s}</Tag>
))}
</div>
</div>
<div>
<Text type="secondary">待提升:</Text>
<div style={{ marginTop: 8 }}>
{selectedStudent.weaknesses.map((w) => (
<Tag key={w} color="orange" style={{ marginBottom: 4 }}>{w}</Tag>
))}
</div>
</div>
</Card>
<Card title="实训历史">
<Timeline
items={selectedStudent.history.map((h) => ({
color: 'blue',
children: (
<div>
<Text strong>{h.training}</Text>
<div>
<Text type="secondary">得分: {h.score}分 | {h.date}</Text>
</div>
</div>
),
}))}
/>
</Card>
</div>
)}
</Drawer>
</div>
);
}
import { Empty } from 'antd';
import { Card, Row, Col, Table, Tag, Timeline, Statistic, List, Avatar, Space, Button, Divider, Typography, Progress, Badge, Steps, Tabs, Modal, Form, Input, Select, Upload, Alert } from 'antd';
import {
BookOutlined,
RocketOutlined,
CheckCircleOutlined,
ClockCircleOutlined,
EyeOutlined,
PlayCircleOutlined,
FileTextOutlined,
LaptopOutlined,
DesktopOutlined,
CloudServerOutlined,
MessageOutlined,
TrophyOutlined,
ThunderboltOutlined,
PlusOutlined,
UploadOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { useState } from 'react';
import { useAuthStore } from '../stores/useAuthStore';
import { PERMISSION_CODES } from '../services/permissionApi';
const { Text, Title, Paragraph } = Typography;
const { TextArea } = Input;
type TrainingItem = {
id: number;
name: string;
project: string;
difficulty: string;
progress: number;
stage: 'preview' | 'practice' | 'defense';
startDate: string;
deadline: string;
mentor: string;
status: 'ongoing' | 'completed' | 'pending';
};
type PreviewTask = {
id: number;
title: string;
description: string;
type: 'knowledge' | 'quiz' | 'reading';
status: 'pending' | 'completed';
completedAt?: string;
};
type PracticeTask = {
id: number;
title: string;
description: string;
type: 'artifact' | 'report';
status: 'pending' | 'submitted' | 'reviewed';
submittedAt?: string;
score?: number;
feedback?: string;
};
export default function TrainingPage() {
return <Empty description="训练营 - 待接入" />;
const { user, permissions } = useAuthStore();
const [activeTab, setActiveTab] = useState('my-training');
const [selectedTraining, setSelectedTraining] = useState<TrainingItem | null>(null);
const [practiceModalVisible, setPracticeModalVisible] = useState(false);
const [practiceType, setPracticeType] = useState<'artifact' | 'report'>('artifact');
// 判断角色
const roles = user?.roles || [];
const isStudent = roles.includes('STUDENT');
const isMentor = roles.includes('MENTOR');
const isSupervisor = roles.includes('SUPERVISOR');
const isAdmin = roles.includes('ADMIN');
// 权限判断
const canCreate = permissions.includes(PERMISSION_CODES.TRAINING_CREATE);
const canAssign = permissions.includes(PERMISSION_CODES.TRAINING_ASSIGN_MENTOR);
// 我的实训列表
const myTrainings: TrainingItem[] = [
{
id: 1,
name: '电商平台用户模块开发',
project: '电商系统实战',
difficulty: 'L3',
progress: 65,
stage: 'practice',
startDate: '2026-07-10',
deadline: '2026-07-25',
mentor: '张导师',
status: 'ongoing',
},
{
id: 2,
name: '企业内部管理系统',
project: '管理系统开发',
difficulty: 'L3',
progress: 100,
stage: 'defense',
startDate: '2026-06-01',
deadline: '2026-06-30',
mentor: '张导师',
status: 'completed',
},
];
// 预览任务
const previewTasks: PreviewTask[] = [
{
id: 1,
title: '学习用户认证机制',
description: '阅读JWT认证相关文档,完成认证流程图绘制',
type: 'knowledge',
status: 'completed',
completedAt: '2026-07-12',
},
{
id: 2,
title: '预习小测',
description: '完成用户模块相关知识点测试,80分及以上通过',
type: 'quiz',
status: 'completed',
completedAt: '2026-07-13',
},
{
id: 3,
title: '技术方案预研',
description: '阅读项目技术栈文档,了解技术选型理由',
type: 'reading',
status: 'pending',
},
];
// 实操任务
const practiceTasks: PracticeTask[] = [
{
id: 1,
title: '用户注册接口开发',
description: '实现用户注册功能,包含参数校验、密码加密存储',
type: 'artifact',
status: 'submitted',
submittedAt: '2026-07-15',
score: 88,
},
{
id: 2,
title: '用户登录功能',
description: '实现JWT Token登录,支持刷新Token机制',
type: 'artifact',
status: 'reviewed',
submittedAt: '2026-07-14',
score: 92,
feedback: '代码规范良好,Token刷新逻辑完善',
},
{
id: 3,
title: '实操报告',
description: '撰写本次实训的实操报告,包含技术方案、遇到的问题及解决方案',
type: 'report',
status: 'pending',
},
];
// 分配给我的实训(导师视角)
const assignedTrainings = [
{
id: 3,
student: '李明',
name: '电商平台用户模块开发',
project: '电商系统实战',
difficulty: 'L3',
progress: 65,
stage: 'practice',
lastActive: '刚刚',
},
{
id: 4,
student: '王芳',
name: '数据可视化看板',
project: '数据分析系统',
difficulty: 'L2',
progress: 85,
stage: 'defense',
lastActive: '10分钟前',
},
];
const trainingColumns: ColumnsType<TrainingItem> = [
{
title: '实训名称',
dataIndex: 'name',
render: (name, record) => (
<div>
<Text strong>{name}</Text>
<br />
<Text type="secondary" style={{ fontSize: 12 }}>{record.project}</Text>
</div>
),
},
{
title: '难度',
dataIndex: 'difficulty',
render: (level) => (
<Tag color={
level === 'L1' ? 'green' :
level === 'L2' ? 'cyan' :
level === 'L3' ? 'blue' :
level === 'L4' ? 'orange' : 'red'
}>
{level}
</Tag>
),
},
{
title: '阶段',
dataIndex: 'stage',
render: (stage) => (
<Tag color={
stage === 'preview' ? 'purple' :
stage === 'practice' ? 'blue' : 'orange'
}>
{stage === 'preview' ? '预览' : stage === 'practice' ? '实操' : '答辩'}
</Tag>
),
},
{
title: '导师',
dataIndex: 'mentor',
render: (mentor) => <Tag icon={<BookOutlined />}>{mentor}</Tag>,
},
{
title: '进度',
dataIndex: 'progress',
width: 150,
render: (progress) => <Progress percent={progress} size="small" strokeColor="#667eea" />,
},
{
title: '截止日期',
dataIndex: 'deadline',
render: (date) => <Text type="secondary">{date}</Text>,
},
{
title: '状态',
dataIndex: 'status',
render: (status) => (
<Badge status={status === 'completed' ? 'success' : status === 'ongoing' ? 'processing' : 'default'} />
),
},
{
title: '操作',
width: 150,
render: (_, record) => (
<Space>
<Button size="small" icon={<EyeOutlined />} onClick={() => setSelectedTraining(record)}>查看</Button>
{record.status === 'completed' && (
<Button size="small" type="primary" icon={<RocketOutlined />}>答辩</Button>
)}
</Space>
),
},
];
const getTaskStatusColor = (status: string): 'success' | 'warning' | 'error' | 'default' | 'processing' => {
const colors: Record<string, 'success' | 'warning' | 'error' | 'default' | 'processing'> = {
pending: 'default',
completed: 'success',
submitted: 'processing',
reviewed: 'success',
};
return colors[status] || 'default';
};
const getTaskStatusText = (status: string) => {
const texts: Record<string, string> = {
pending: '待完成',
completed: '已完成',
submitted: '已提交',
reviewed: '已点评',
};
return texts[status] || status;
};
const renderMyTraining = () => (
<div>
<Alert
message="当前实训:电商平台用户模块开发"
description={
<Space>
<Tag icon={<ClockCircleOutlined />} color="blue">实操阶段</Tag>
<Tag icon={<BookOutlined />} color="purple">L3 中等难度</Tag>
<Tag icon={<ClockCircleOutlined />} color="orange">剩余 8 天</Tag>
</Space>
}
type="info"
showIcon
style={{ marginBottom: 16 }}
/>
<Card style={{ borderRadius: 12, marginBottom: 16 }}>
<Row gutter={[16, 16]}>
<Col span={24}>
<Steps
current={1}
items={[
{
title: '需求分析',
status: 'finish',
icon: <FileTextOutlined />,
},
{
title: '预览阶段',
status: 'finish',
icon: <EyeOutlined />,
},
{
title: '实操阶段',
status: 'process',
icon: <LaptopOutlined />,
},
{
title: '答辩评审',
status: 'wait',
icon: <TrophyOutlined />,
},
]}
/>
</Col>
</Row>
</Card>
<Tabs
defaultActiveKey="preview"
items={[
{
key: 'preview',
label: (
<span>
<EyeOutlined />
预览阶段
</span>
),
children: (
<Card style={{ borderRadius: 12 }}>
<List
dataSource={previewTasks}
renderItem={(task) => (
<List.Item
actions={[
task.status === 'pending' && (
<Button type="primary" size="small" key="start">开始</Button>
),
task.status === 'completed' && (
<Button size="small" key="review">回顾</Button>
),
].filter(Boolean)}
>
<List.Item.Meta
avatar={
<Avatar
style={{
background: task.status === 'completed' ? '#10b981' : '#667eea'
}}
>
{task.type === 'knowledge' ? '📚' : task.type === 'quiz' ? '📝' : '📖'}
</Avatar>
}
title={
<Space>
<Text>{task.title}</Text>
<Tag>{task.type === 'knowledge' ? '知识点' : task.type === 'quiz' ? '小测' : '阅读'}</Tag>
<Badge status={getTaskStatusColor(task.status)} text={getTaskStatusText(task.status)} />
</Space>
}
description={
<div>
<Paragraph type="secondary" ellipsis={{ rows: 1 }}>{task.description}</Paragraph>
{task.completedAt && (
<Text type="secondary" style={{ fontSize: 12 }}>
完成时间: {task.completedAt}
</Text>
)}
</div>
}
/>
</List.Item>
)}
/>
</Card>
),
},
{
key: 'practice',
label: (
<span>
<DesktopOutlined />
实操阶段
</span>
),
children: (
<Card style={{ borderRadius: 12 }}>
<List
dataSource={practiceTasks}
renderItem={(task) => (
<List.Item
actions={[
task.status === 'pending' && (
<Button
type="primary"
size="small"
key="submit"
onClick={() => {
setPracticeType(task.type);
setPracticeModalVisible(true);
}}
>
提交
</Button>
),
task.status === 'submitted' && (
<Tag color="processing">待点评</Tag>
),
task.status === 'reviewed' && (
<Button size="small" key="view">查看点评</Button>
),
].filter(Boolean)}
>
<List.Item.Meta
avatar={
<Avatar
style={{
background: task.status === 'reviewed' ? '#10b981' :
task.status === 'submitted' ? '#f59e0b' : '#667eea'
}}
>
{task.type === 'artifact' ? '💻' : '📄'}
</Avatar>
}
title={
<Space>
<Text>{task.title}</Text>
<Tag>{task.type === 'artifact' ? '产物' : '报告'}</Tag>
<Badge status={getTaskStatusColor(task.status)} text={getTaskStatusText(task.status)} />
</Space>
}
description={
<div>
<Paragraph type="secondary" ellipsis={{ rows: 1 }}>{task.description}</Paragraph>
{task.score && (
<Text style={{ color: '#10b981', fontWeight: 500 }}>
得分: {task.score}分
</Text>
)}
{task.feedback && (
<Text type="secondary" style={{ display: 'block', fontSize: 12 }}>
导师点评: {task.feedback}
</Text>
)}
</div>
}
/>
</List.Item>
)}
/>
</Card>
),
},
{
key: 'defense',
label: (
<span>
<TrophyOutlined />
答辩准备
</span>
),
children: (
<Card style={{ borderRadius: 12 }}>
<div style={{ textAlign: 'center', padding: '40px 0' }}>
<RocketOutlined style={{ fontSize: 64, color: '#667eea', marginBottom: 16 }} />
<Title level={4}>准备答辩</Title>
<Paragraph type="secondary">
完成实操阶段后,你可以申请答辩。导师将评审你的成果,并给出最终评分。
</Paragraph>
<Space style={{ marginTop: 16 }}>
<Button icon={<FileTextOutlined />}>查看答辩要求</Button>
<Button type="primary" icon={<RocketOutlined />}>申请答辩</Button>
</Space>
</div>
</Card>
),
},
]}
/>
</div>
);
const renderMentorView = () => (
<div>
<Card
title="分配给我的实训"
style={{ borderRadius: 12 }}
extra={<Button type="primary">查看全部</Button>}
>
<Table
columns={[
{
title: '学员',
dataIndex: 'student',
render: (student) => (
<Space>
<Avatar style={{ background: '#667eea' }}>{student.charAt(0)}</Avatar>
<Text>{student}</Text>
</Space>
),
},
{ title: '实训名称', dataIndex: 'name' },
{
title: '阶段',
dataIndex: 'stage',
render: (stage) => (
<Tag color={stage === 'preview' ? 'purple' : stage === 'practice' ? 'blue' : 'orange'}>
{stage === 'preview' ? '预览' : stage === 'practice' ? '实操' : '答辩'}
</Tag>
),
},
{
title: '进度',
dataIndex: 'progress',
render: (progress) => <Progress percent={progress} size="small" />,
},
{
title: '最近活跃',
dataIndex: 'lastActive',
render: (time) => <Text type="secondary">{time}</Text>,
},
{
title: '操作',
render: () => (
<Space>
<Button size="small">查看</Button>
<Button size="small" type="primary">指导</Button>
</Space>
),
},
]}
dataSource={assignedTrainings}
rowKey="id"
pagination={false}
size="small"
/>
</Card>
</div>
);
const renderAllTrainings = () => (
<div>
<Card
title="所有实训"
style={{ borderRadius: 12 }}
extra={
<Space>
{canCreate && <Button type="primary" icon={<PlusOutlined />}>创建实训</Button>}
</Space>
}
>
<Table
columns={trainingColumns}
dataSource={myTrainings}
rowKey="id"
pagination={{ pageSize: 10 }}
/>
</Card>
</div>
);
return (
<div style={{ padding: '0 0 24px' }}>
<Title level={4} style={{ marginBottom: 16 }}>训练营</Title>
{/* 角色化Tab展示 */}
<Tabs
activeKey={activeTab}
onChange={setActiveTab}
items={[
{
key: 'my-training',
label: isStudent ? '我的实训' : '分配给我的',
children: isStudent ? renderMyTraining() : renderMentorView(),
},
...(isMentor || isSupervisor || isAdmin ? [{
key: 'all-training',
label: '全部实训',
children: renderAllTrainings(),
}] : []),
]}
/>
{/* 提交产物弹窗 */}
<Modal
title={practiceType === 'artifact' ? '提交实操产物' : '提交实操报告'}
open={practiceModalVisible}
onCancel={() => setPracticeModalVisible(false)}
footer={null}
width={600}
>
<Form layout="vertical">
{practiceType === 'artifact' ? (
<>
<Form.Item label="产物名称" required>
<Input placeholder="如:用户注册接口" />
</Form.Item>
<Form.Item label="代码仓库地址">
<Input placeholder="Git 仓库 URL" />
</Form.Item>
<Form.Item label="产物描述">
<TextArea rows={4} placeholder="描述你完成的工作..." />
</Form.Item>
<Form.Item label="上传文件">
<Upload>
<Button icon={<UploadOutlined />}>上传代码压缩包</Button>
</Upload>
</Form.Item>
</>
) : (
<>
<Form.Item label="报告标题" required>
<Input placeholder="实操报告标题" />
</Form.Item>
<Form.Item label="技术方案">
<TextArea rows={4} placeholder="描述技术实现方案..." />
</Form.Item>
<Form.Item label="遇到的问题">
<TextArea rows={3} placeholder="描述遇到的问题及解决方案..." />
</Form.Item>
<Form.Item label="收获与总结">
<TextArea rows={3} placeholder="本次实训的收获..." />
</Form.Item>
</>
)}
<Form.Item>
<Space>
<Button type="primary" onClick={() => setPracticeModalVisible(false)}>提交</Button>
<Button onClick={() => setPracticeModalVisible(false)}>取消</Button>
</Space>
</Form.Item>
</Form>
</Modal>
</div>
);
}
/**
* 用户管理页面
* 仅管理员可见
*/
import { useState, useEffect } from 'react';
import {
Table,
Button,
Space,
Input,
Modal,
Form,
Select,
message,
Popconfirm,
Tag,
Card,
Row,
Col,
} from 'antd';
import {
PlusOutlined,
SearchOutlined,
EditOutlined,
DeleteOutlined,
KeyOutlined,
UnlockOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { userApi, roleApi, ROLE_NAMES, PERMISSION_CODES } from '../services/permissionApi';
import { HasPermission } from '../components/PermissionGuard';
import { usePermission } from '../stores/usePermission';
interface User {
id: number;
username: string;
realName: string;
email?: string;
phone?: string;
roleId: number;
roleName?: string;
departmentId?: number;
departmentName?: string;
status: number;
createdAt: string;
}
interface Role {
id: number;
roleName: string;
roleCode: string;
}
const UserManagementPage: React.FC = () => {
const [users, setUsers] = useState<User[]>([]);
const [roles, setRoles] = useState<Role[]>([]);
const [loading, setLoading] = useState(false);
const [modalVisible, setModalVisible] = useState(false);
const [resetPwdModalVisible, setResetPwdModalVisible] = useState(false);
const [editingUser, setEditingUser] = useState<User | null>(null);
const [selectedUser, setSelectedUser] = useState<User | null>(null);
const [form] = Form.useForm();
const [resetPwdForm] = Form.useForm();
const [pagination, setPagination] = useState({ current: 1, pageSize: 10, total: 0 });
const [searchKeyword, setSearchKeyword] = useState('');
const { isAdmin } = usePermission();
// 加载用户列表
const loadUsers = async (page = 1, pageSize = 10, keyword = '') => {
setLoading(true);
try {
const result = await userApi.listUsers({
page,
size: pageSize,
keyword: keyword || undefined,
});
setUsers(result.items);
setPagination({ ...pagination, total: result.total, current: page, pageSize });
} catch (error) {
message.error('加载用户列表失败');
} finally {
setLoading(false);
}
};
// 加载角色列表
const loadRoles = async () => {
try {
const result = await roleApi.listRoles();
setRoles(result);
} catch (error) {
message.error('加载角色列表失败');
}
};
useEffect(() => {
loadUsers();
loadRoles();
}, []);
// 搜索
const handleSearch = () => {
loadUsers(1, pagination.pageSize, searchKeyword);
};
// 打开创建用户弹窗
const handleCreate = () => {
setEditingUser(null);
form.resetFields();
setModalVisible(true);
};
// 打开编辑用户弹窗
const handleEdit = (user: User) => {
setEditingUser(user);
form.setFieldsValue({
username: user.username,
realName: user.realName,
email: user.email,
phone: user.phone,
roleId: user.roleId,
status: user.status,
});
setModalVisible(true);
};
// 提交表单
const handleSubmit = async () => {
try {
const values = await form.validateFields();
if (editingUser) {
await userApi.updateUser(editingUser.id, values);
message.success('更新用户成功');
} else {
await userApi.createUser(values);
message.success('创建用户成功');
}
setModalVisible(false);
loadUsers(pagination.current, pagination.pageSize, searchKeyword);
} catch (error: any) {
if (error.errorFields) return;
message.error(error.response?.data?.message || '操作失败');
}
};
// 删除用户
const handleDelete = async (userId: number) => {
try {
await userApi.deleteUser(userId);
message.success('删除用户成功');
loadUsers(pagination.current, pagination.pageSize, searchKeyword);
} catch (error: any) {
message.error(error.response?.data?.message || '删除用户失败');
}
};
// 打开重置密码弹窗
const handleResetPassword = (user: User) => {
setSelectedUser(user);
resetPwdForm.resetFields();
setResetPwdModalVisible(true);
};
// 重置密码
const handleResetPasswordSubmit = async () => {
try {
const values = await resetPwdForm.validateFields();
await userApi.resetPassword(selectedUser!.id, values.newPassword);
message.success('密码重置成功');
setResetPwdModalVisible(false);
} catch (error: any) {
if (error.errorFields) return;
message.error(error.response?.data?.message || '密码重置失败');
}
};
// 表格列定义
const columns: ColumnsType<User> = [
{
title: 'ID',
dataIndex: 'id',
key: 'id',
width: 80,
},
{
title: '用户名',
dataIndex: 'username',
key: 'username',
},
{
title: '姓名',
dataIndex: 'realName',
key: 'realName',
},
{
title: '角色',
dataIndex: 'roleName',
key: 'roleName',
render: (roleName: string) => {
const colorMap: Record<string, string> = {
'管理员': 'red',
'主管': 'orange',
'导师': 'blue',
'学员': 'green',
};
return <Tag color={colorMap[roleName] || 'default'}>{roleName || '-'}</Tag>;
},
},
{
title: '手机号',
dataIndex: 'phone',
key: 'phone',
render: (phone: string) => phone ? phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2') : '-',
},
{
title: '邮箱',
dataIndex: 'email',
key: 'email',
},
{
title: '状态',
dataIndex: 'status',
key: 'status',
render: (status: number) => (
<Tag color={status === 1 ? 'success' : 'error'}>
{status === 1 ? '启用' : '禁用'}
</Tag>
),
},
{
title: '创建时间',
dataIndex: 'createdAt',
key: 'createdAt',
render: (date: string) => new Date(date).toLocaleString('zh-CN'),
},
{
title: '操作',
key: 'action',
width: 200,
render: (_, record) => (
<Space size="small">
<Button
type="link"
size="small"
icon={<EditOutlined />}
onClick={() => handleEdit(record)}
>
编辑
</Button>
<Button
type="link"
size="small"
icon={<KeyOutlined />}
onClick={() => handleResetPassword(record)}
>
重置密码
</Button>
<Popconfirm
title="确定删除该用户?"
onConfirm={() => handleDelete(record.id)}
okText="确定"
cancelText="取消"
>
<Button type="link" size="small" danger icon={<DeleteOutlined />}>
删除
</Button>
</Popconfirm>
</Space>
),
},
];
return (
<div>
<Card
title="用户管理"
extra={
<HasPermission permission={PERMISSION_CODES.USER_CREATE}>
<Button type="primary" icon={<PlusOutlined />} onClick={handleCreate}>
创建用户
</Button>
</HasPermission>
}
>
{/* 搜索栏 */}
<div style={{ marginBottom: 16 }}>
<Space>
<Input.Search
placeholder="搜索用户名/姓名/手机号"
value={searchKeyword}
onChange={(e) => setSearchKeyword(e.target.value)}
onSearch={handleSearch}
style={{ width: 300 }}
allowClear
/>
</Space>
</div>
{/* 用户表格 */}
<Table
columns={columns}
dataSource={users}
rowKey="id"
loading={loading}
pagination={{
current: pagination.current,
pageSize: pagination.pageSize,
total: pagination.total,
showSizeChanger: true,
showQuickJumper: true,
showTotal: (total) => `共 ${total} 条`,
onChange: (page, pageSize) => loadUsers(page, pageSize, searchKeyword),
}}
/>
</Card>
{/* 创建/编辑用户弹窗 */}
<Modal
title={editingUser ? '编辑用户' : '创建用户'}
open={modalVisible}
onOk={handleSubmit}
onCancel={() => setModalVisible(false)}
width={500}
>
<Form form={form} layout="vertical">
<Form.Item
name="username"
label="用户名"
rules={[{ required: true, message: '请输入用户名' }]}
>
<Input disabled={!!editingUser} />
</Form.Item>
{!editingUser && (
<Form.Item
name="password"
label="密码"
rules={[
{ required: true, message: '请输入密码' },
{ min: 8, message: '密码至少8位' },
]}
>
<Input.Password />
</Form.Item>
)}
<Form.Item
name="realName"
label="姓名"
rules={[{ required: true, message: '请输入姓名' }]}
>
<Input />
</Form.Item>
<Form.Item name="phone" label="手机号">
<Input />
</Form.Item>
<Form.Item name="email" label="邮箱">
<Input />
</Form.Item>
<Form.Item
name="roleId"
label="角色"
rules={[{ required: true, message: '请选择角色' }]}
>
<Select>
{roles.map((role) => (
<Select.Option key={role.id} value={role.id}>
{ROLE_NAMES[role.roleCode] || role.roleName}
</Select.Option>
))}
</Select>
</Form.Item>
<Form.Item name="status" label="状态" initialValue={1}>
<Select>
<Select.Option value={1}>启用</Select.Option>
<Select.Option value={0}>禁用</Select.Option>
</Select>
</Form.Item>
</Form>
</Modal>
{/* 重置密码弹窗 */}
<Modal
title="重置密码"
open={resetPwdModalVisible}
onOk={handleResetPasswordSubmit}
onCancel={() => setResetPwdModalVisible(false)}
>
<p>为用户 <strong>{selectedUser?.realName}</strong> 重置密码</p>
<Form form={resetPwdForm} layout="vertical">
<Form.Item
name="newPassword"
label="新密码"
rules={[
{ required: true, message: '请输入新密码' },
{ min: 8, message: '密码至少8位' },
]}
>
<Input.Password />
</Form.Item>
</Form>
</Modal>
</div>
);
};
export default UserManagementPage;
/**
* Axios 实例配置
*/
import axios from 'axios';
const API_BASE_URL = '/api/v1';
const instance = axios.create({
baseURL: API_BASE_URL,
timeout: 10000,
headers: {
'Content-Type': 'application/json',
},
});
// 请求拦截器 - 添加 Token
instance.interceptors.request.use(
(config) => {
const token = localStorage.getItem('accessToken');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
},
(error) => Promise.reject(error)
);
// 响应拦截器 - 处理 Token 过期
instance.interceptors.response.use(
(response) => response,
async (error) => {
const originalRequest = error.config;
// Token 过期,尝试刷新
if (error.response?.status === 401 && !originalRequest._retry) {
originalRequest._retry = true;
const refreshToken = localStorage.getItem('refreshToken');
if (refreshToken) {
try {
const response = await axios.post(`${API_BASE_URL}/auth/refresh`, {
refreshToken,
});
const { accessToken, refreshToken: nextRefreshToken } = response.data.data;
localStorage.setItem('accessToken', accessToken);
if (nextRefreshToken) {
localStorage.setItem('refreshToken', nextRefreshToken);
}
originalRequest.headers.Authorization = `Bearer ${accessToken}`;
return instance(originalRequest);
} catch (refreshError) {
localStorage.removeItem('accessToken');
localStorage.removeItem('refreshToken');
window.location.href = '/login';
return Promise.reject(refreshError);
}
}
}
return Promise.reject(error);
}
);
export default instance;
/**
* 权限相关 API 服务
* 基于 RBAC 设计文档实现
*/
import axios from './axios';
// ============ 类型定义 ============
// 用户类型
export interface User {
id: number;
username: string;
realName: string;
email?: string;
phone?: string;
avatar?: string;
roleId: number;
roleName?: string;
departmentId?: number;
departmentName?: string;
status: number;
createdAt: string;
roles?: string[];
}
// 角色类型
export interface Role {
id: number;
roleName: string;
roleCode: string;
description: string;
isPreset: boolean;
dataScope: number;
sort: number;
status: number;
userCount?: number;
permissions?: Permission[];
}
// 权限类型
export interface Permission {
id: number;
permissionCode: string;
permissionName: string;
module: string;
description?: string;
}
// 菜单类型
export interface MenuItem {
id: number;
parentId: number;
name: string;
title: string;
icon?: string;
path?: string;
component?: string;
permissionCode?: string;
type: number; // 1=目录, 2=菜单, 3=按钮
sort: number;
visible: number;
status: number;
children?: MenuItem[];
}
// ============ API 接口 ============
// 用户管理 API
export const userApi = {
// 获取当前用户信息
getCurrentUser: async (): Promise<User> => {
const response = await axios.get('/users/me');
return response.data.data;
},
// 获取用户详情
getUserById: async (id: number): Promise<User> => {
const response = await axios.get(`/users/${id}`);
return response.data.data;
},
// 获取用户列表
listUsers: async (params?: {
page?: number;
size?: number;
keyword?: string;
roleId?: number;
departmentId?: number;
status?: number;
}): Promise<{ total: number; items: User[] }> => {
const response = await axios.get('/users', { params });
return {
total: response.data.data.total,
items: response.data.data.items,
};
},
// 创建用户
createUser: async (data: {
username: string;
password: string;
realName: string;
phone?: string;
email?: string;
roleIds?: number[];
}): Promise<User> => {
const response = await axios.post('/users', data);
return response.data.data;
},
// 更新用户
updateUser: async (id: number, data: Partial<User>): Promise<User> => {
const response = await axios.put(`/users/${id}`, data);
return response.data.data;
},
// 删除用户(软删除)
deleteUser: async (id: number): Promise<void> => {
await axios.delete(`/users/${id}`);
},
// 分配用户角色
assignRoles: async (userId: number, roleIds: number[]): Promise<void> => {
await axios.put(`/users/${userId}/roles`, { roleIds });
},
// 重置密码
resetPassword: async (userId: number, newPassword: string): Promise<void> => {
await axios.put(`/users/${userId}/password/reset`, { newPassword });
},
// 解锁用户
unlockUser: async (userId: number): Promise<void> => {
await axios.put(`/users/${userId}/unlock`);
},
};
// 角色管理 API
export const roleApi = {
// 获取角色列表
listRoles: async (): Promise<Role[]> => {
const response = await axios.get('/roles');
return response.data.data;
},
// 获取角色详情(含权限)
getRoleById: async (id: number): Promise<Role> => {
const response = await axios.get(`/roles/${id}`);
return response.data.data;
},
// 创建角色
createRole: async (data: {
roleName: string;
roleCode?: string;
description?: string;
dataScope?: number;
sort?: number;
status?: number;
permissionIds?: number[];
}): Promise<Role> => {
const response = await axios.post('/roles', data);
return response.data.data;
},
// 更新角色
updateRole: async (id: number, data: Partial<Role> & { permissionIds?: number[] }): Promise<void> => {
await axios.put(`/roles/${id}`, data);
},
// 删除角色
deleteRole: async (id: number): Promise<void> => {
await axios.delete(`/roles/${id}`);
},
// 获取权限列表
listPermissions: async (): Promise<Permission[]> => {
const response = await axios.get('/roles/permissions');
return response.data.data;
},
// 分配角色菜单
assignMenus: async (roleId: number, menuIds: number[]): Promise<void> => {
await axios.put(`/roles/${roleId}/menus`, { menuIds });
},
// 获取角色自定义部门权限
getCustomDepts: async (roleId: number): Promise<number[]> => {
const response = await axios.get(`/roles/${roleId}/custom-depts`);
return response.data.data;
},
// 分配角色自定义部门权限
assignCustomDepts: async (roleId: number, departmentIds: number[]): Promise<void> => {
await axios.put(`/roles/${roleId}/custom-depts`, { departmentIds });
},
};
// 菜单管理 API
export const menuApi = {
// 获取当前用户菜单
getUserMenus: async (): Promise<MenuItem[]> => {
const response = await axios.get('/menus');
return response.data.data;
},
// 获取完整菜单树(Admin)
getMenuTree: async (status?: number): Promise<MenuItem[]> => {
const response = await axios.get('/menus/tree', { params: { status } });
return response.data.data;
},
// 获取菜单详情
getMenuById: async (id: number): Promise<MenuItem> => {
const response = await axios.get(`/menus/${id}`);
return response.data.data;
},
// 创建菜单
createMenu: async (data: Omit<MenuItem, 'id'>): Promise<MenuItem> => {
const response = await axios.post('/menus', data);
return response.data.data;
},
// 更新菜单
updateMenu: async (id: number, data: Partial<MenuItem>): Promise<void> => {
await axios.put(`/menus/${id}`, data);
},
// 删除菜单
deleteMenu: async (id: number): Promise<void> => {
await axios.delete(`/menus/${id}`);
},
};
// ============ 权限常量 ============
export const PERMISSION_CODES = {
// 项目管理
PROJECT_VIEW: 'project:view',
PROJECT_CREATE: 'project:create',
PROJECT_UPDATE: 'project:update',
PROJECT_DELETE: 'project:delete',
PROJECT_SIMPLE_LIST: 'project:simple_list',
// 标签管理
TAG_VIEW: 'tag:view',
TAG_CREATE: 'tag:create',
TAG_UPDATE: 'tag:update',
TAG_DELETE: 'tag:delete',
// 难度配置
DIFFICULTY_VIEW: 'difficulty:view',
DIFFICULTY_CONFIG: 'difficulty:config',
DIFFICULTY_CALIBRATE: 'difficulty:calibrate',
DIFFICULTY_AI_SCORE_VIEW: 'difficulty:ai_score_view',
// 项目推荐
RECOMMEND_REQUEST: 'recommend:request',
RECOMMEND_VIEW: 'recommend:view',
RECOMMEND_CHOOSE: 'recommend:choose',
RECOMMEND_IGNORE: 'recommend:ignore',
// 知识点
KNOWLEDGE_VIEW: 'knowledge:view',
KNOWLEDGE_CREATE: 'knowledge:create',
KNOWLEDGE_UPDATE: 'knowledge:update',
KNOWLEDGE_DELETE: 'knowledge:delete',
KNOWLEDGE_AI_EXTRACT: 'knowledge:ai_extract',
// 文件管理
FILE_UPLOAD: 'file:upload',
FILE_DOWNLOAD: 'file:download',
// 实训任务
TRAINING_CREATE: 'training:create',
TRAINING_VIEW_OWN: 'training:view_own',
TRAINING_VIEW_ASSIGNED: 'training:view_assigned',
TRAINING_VIEW_ALL: 'training:view_all',
TRAINING_UPDATE: 'training:update',
TRAINING_DELETE: 'training:delete',
TRAINING_ASSIGN_MENTOR: 'training:assign_mentor',
TRAINING_VIEW_DETAIL: 'training:view_detail',
// 预览管理
PREVIEW_VIEW_KNOWLEDGE: 'preview:view_knowledge',
PREVIEW_SUBMIT: 'preview:submit',
PREVIEW_TAK_QUIZ: 'preview:tak_quiz',
PREVIEW_VIEW_PROGRESS: 'preview:view_progress',
// 实操管理
PRACTICE_SUBMIT_ARTIFACT: 'practice:submit_artifact',
PRACTICE_WRITE_REPORT: 'practice:write_report',
PRACTICE_SUBMIT_REPORT: 'practice:submit_report',
// 答辩管理
DEFENSE_APPLY: 'defense:apply',
DEFENSE_REVIEW: 'defense:review',
DEFENSE_AUDIT: 'defense:audit',
DEFENSE_VIEW: 'defense:view',
DEFENSE_PENDING_LIST: 'defense:pending_list',
// 历史记录
HISTORY_VIEW_OWN: 'history:view_own',
HISTORY_VIEW_DEPARTMENT: 'history:view_department',
HISTORY_VIEW_ALL: 'history:view_all',
// 容器管理
CONTAINER_USE: 'container:use',
CONTAINER_MANAGE: 'container:manage',
// 缺陷记录
DEFECT_VIEW: 'defect:view',
DEFECT_ADD: 'defect:add',
// 进阶匹配
ADVANCED_ACCEPT: 'advanced:accept',
ADVANCED_REJECT: 'advanced:reject',
ADVANCED_VIEW: 'advanced:view',
// 能力画像
PROFILE_VIEW: 'profile:view',
// 用户管理
USER_VIEW_LIST: 'user:view_list',
USER_CREATE: 'user:create',
USER_UPDATE: 'user:update',
USER_DELETE: 'user:delete',
USER_VIEW_DETAIL: 'user:view_detail',
// 角色管理
ROLE_VIEW: 'role:view',
ROLE_CREATE: 'role:create',
ROLE_UPDATE: 'role:update',
ROLE_DELETE: 'role:delete',
ROLE_ASSIGN_USER: 'role:assign_user',
PERMISSION_ASSIGN: 'permission:assign',
// 部门管理
DEPT_CREATE: 'dept:create',
DEPT_UPDATE: 'dept:update',
DEPT_DELETE: 'dept:delete',
// 菜单管理
MENU_VIEW: 'menu:view',
MENU_CREATE: 'menu:create',
MENU_UPDATE: 'menu:update',
MENU_DELETE: 'menu:delete',
// 导师工作台
MENTOR_DASHBOARD: 'mentor:dashboard',
} as const;
// 角色枚举
export const ROLE_CODES = {
ADMIN: 'ADMIN',
SUPERVISOR: 'SUPERVISOR',
MENTOR: 'MENTOR',
STUDENT: 'STUDENT',
} as const;
// 角色名称映射
export const ROLE_NAMES: Record<string, string> = {
ADMIN: '管理员',
SUPERVISOR: '主管',
MENTOR: '导师',
STUDENT: '学员',
};
// 模块名称映射
export const MODULE_NAMES: Record<string, string> = {
project: '项目管理',
tag: '标签管理',
difficulty: '难度配置',
recommend: '项目推荐',
knowledge: '知识点',
file: '文件管理',
training: '实训任务',
preview: '预览管理',
practice: '实操管理',
defense: '答辩管理',
history: '历史记录',
container: '容器管理',
defect: '缺陷记录',
advanced: '进阶匹配',
profile: '能力画像',
user: '用户管理',
role: '角色管理',
dept: '部门管理',
menu: '菜单管理',
mentor_dashboard: '导师工作台',
};
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { login as loginApi, logout as logoutApi, phoneLogin as phoneLoginApi, LoginResponse } from '../services/authApi';
interface User {
id: number;
username: string;
realName: string;
roles: string[];
}
import { userApi, menuApi, PERMISSION_CODES, User } from '../services/permissionApi';
interface AuthState {
user: User | null;
user: LoginResponse['user'] | null;
permissions: string[];
menus: any[];
accessToken: string | null;
refreshToken: string | null;
isAuthenticated: boolean;
isLoading: boolean;
// Actions
setAuth: (data: LoginResponse) => void;
login: (username: string, password: string) => Promise<void>;
phoneLogin: (phone: string, smsCode: string) => Promise<void>;
logout: () => Promise<void>;
clearAuth: () => void;
loadPermissions: () => Promise<void>;
loadMenus: () => Promise<void>;
}
export const useAuthStore = create<AuthState>()(
persist(
(set, get) => ({
user: null,
permissions: [],
menus: [],
accessToken: null,
refreshToken: null,
isAuthenticated: false,
isLoading: false,
setAuth: (data: LoginResponse) => {
localStorage.setItem('accessToken', data.accessToken);
......@@ -43,20 +45,34 @@ export const useAuthStore = create<AuthState>()(
},
login: async (username: string, password: string) => {
const response = await loginApi({ username, password });
get().setAuth(response);
set({ isLoading: true });
try {
const response = await loginApi({ username, password });
get().setAuth(response);
// 登录后加载权限和菜单
await get().loadPermissions();
await get().loadMenus();
} finally {
set({ isLoading: false });
}
},
phoneLogin: async (phone: string, smsCode: string) => {
const response = await phoneLoginApi({ phone, smsCode });
get().setAuth(response);
set({ isLoading: true });
try {
const response = await phoneLoginApi({ phone, smsCode });
get().setAuth(response);
await get().loadPermissions();
await get().loadMenus();
} finally {
set({ isLoading: false });
}
},
logout: async () => {
try {
await logoutApi();
} catch (error) {
// 即使 API 调用失败,也清除本地状态
console.error('Logout API error:', error);
} finally {
get().clearAuth();
......@@ -68,16 +84,46 @@ export const useAuthStore = create<AuthState>()(
localStorage.removeItem('refreshToken');
set({
user: null,
permissions: [],
menus: [],
accessToken: null,
refreshToken: null,
isAuthenticated: false,
});
},
// 加载用户权限
loadPermissions: async () => {
try {
// 获取用户详情,包含权限信息
const userDetail = await userApi.getCurrentUser();
// 根据用户角色预设默认权限
const roles = userDetail.roles || [];
const defaultPermissions = getDefaultPermissionsByRoles(roles);
set({ permissions: defaultPermissions });
} catch (error) {
console.error('加载权限失败:', error);
set({ permissions: [] });
}
},
// 加载用户菜单
loadMenus: async () => {
try {
const menus = await menuApi.getUserMenus();
set({ menus });
} catch (error) {
console.error('加载菜单失败:', error);
set({ menus: [] });
}
},
}),
{
name: 'auth-storage',
partialize: (state) => ({
user: state.user,
permissions: state.permissions,
menus: state.menus,
accessToken: state.accessToken,
refreshToken: state.refreshToken,
isAuthenticated: state.isAuthenticated,
......@@ -85,3 +131,95 @@ export const useAuthStore = create<AuthState>()(
}
)
);
// 根据用户角色获取默认权限
function getDefaultPermissionsByRoles(roles: string[]): string[] {
const allPermissions: string[] = [];
const roleSet = new Set(roles);
// ADMIN 拥有所有权限
if (roleSet.has('ADMIN')) {
return Object.values(PERMISSION_CODES);
}
// 公共权限 - 所有人都有的权限
const publicPermissions = [
PERMISSION_CODES.PROJECT_VIEW,
PERMISSION_CODES.PROJECT_SIMPLE_LIST,
PERMISSION_CODES.TAG_VIEW,
PERMISSION_CODES.RECOMMEND_VIEW,
PERMISSION_CODES.KNOWLEDGE_VIEW,
PERMISSION_CODES.DEFENSE_VIEW,
PERMISSION_CODES.PROFILE_VIEW,
PERMISSION_CODES.DEFECT_VIEW,
PERMISSION_CODES.ADVANCED_VIEW,
PERMISSION_CODES.ROLE_VIEW,
];
allPermissions.push(...publicPermissions);
// 主管权限
if (roleSet.has('SUPERVISOR')) {
const supervisorPermissions = [
PERMISSION_CODES.DIFFICULTY_VIEW,
PERMISSION_CODES.DIFFICULTY_CALIBRATE,
PERMISSION_CODES.DIFFICULTY_AI_SCORE_VIEW,
PERMISSION_CODES.TRAINING_VIEW_ALL,
PERMISSION_CODES.TRAINING_VIEW_DETAIL,
PERMISSION_CODES.PREVIEW_VIEW_PROGRESS,
PERMISSION_CODES.DEFENSE_AUDIT,
PERMISSION_CODES.DEFENSE_PENDING_LIST,
PERMISSION_CODES.HISTORY_VIEW_ALL,
PERMISSION_CODES.CONTAINER_MANAGE,
PERMISSION_CODES.USER_VIEW_LIST,
PERMISSION_CODES.USER_VIEW_DETAIL,
PERMISSION_CODES.MENTOR_DASHBOARD,
];
allPermissions.push(...supervisorPermissions);
}
// 导师权限
if (roleSet.has('MENTOR')) {
const mentorPermissions = [
PERMISSION_CODES.DIFFICULTY_VIEW,
PERMISSION_CODES.TRAINING_VIEW_ASSIGNED,
PERMISSION_CODES.TRAINING_VIEW_DETAIL,
PERMISSION_CODES.PREVIEW_VIEW_PROGRESS,
PERMISSION_CODES.DEFENSE_REVIEW,
PERMISSION_CODES.DEFENSE_PENDING_LIST,
PERMISSION_CODES.HISTORY_VIEW_DEPARTMENT,
PERMISSION_CODES.DEFECT_ADD,
PERMISSION_CODES.USER_VIEW_DETAIL,
PERMISSION_CODES.MENTOR_DASHBOARD,
];
allPermissions.push(...mentorPermissions);
}
// 学员权限
if (roleSet.has('STUDENT')) {
const studentPermissions = [
PERMISSION_CODES.RECOMMEND_REQUEST,
PERMISSION_CODES.RECOMMEND_CHOOSE,
PERMISSION_CODES.RECOMMEND_IGNORE,
PERMISSION_CODES.TRAINING_CREATE,
PERMISSION_CODES.TRAINING_VIEW_OWN,
PERMISSION_CODES.TRAINING_UPDATE,
PERMISSION_CODES.TRAINING_DELETE,
PERMISSION_CODES.TRAINING_VIEW_DETAIL,
PERMISSION_CODES.PREVIEW_VIEW_KNOWLEDGE,
PERMISSION_CODES.PREVIEW_SUBMIT,
PERMISSION_CODES.PREVIEW_TAK_QUIZ,
PERMISSION_CODES.PRACTICE_SUBMIT_ARTIFACT,
PERMISSION_CODES.PRACTICE_WRITE_REPORT,
PERMISSION_CODES.PRACTICE_SUBMIT_REPORT,
PERMISSION_CODES.DEFENSE_APPLY,
PERMISSION_CODES.HISTORY_VIEW_OWN,
PERMISSION_CODES.CONTAINER_USE,
PERMISSION_CODES.ADVANCED_ACCEPT,
PERMISSION_CODES.ADVANCED_REJECT,
];
allPermissions.push(...studentPermissions);
}
// 去重
return [...new Set(allPermissions)];
}
/**
* 权限 Hook - 按钮级权限控制
*/
import { useAuthStore } from './useAuthStore';
import { PERMISSION_CODES, ROLE_CODES } from '../services/permissionApi';
/**
* 权限 Hook
*/
export const usePermission = () => {
const { user, permissions } = useAuthStore();
/**
* 检查是否有指定权限
*/
const hasPermission = (permission: string): boolean => {
return permissions?.includes(permission) ?? false;
};
/**
* 检查是否有所有指定权限
*/
const hasAllPermissions = (...perms: string[]): boolean => {
return perms.every((p) => permissions?.includes(p) ?? false);
};
/**
* 检查是否有任一指定权限
*/
const hasAnyPermission = (...perms: string[]): boolean => {
return perms.some((p) => permissions?.includes(p) ?? false);
};
/**
* 检查是否是管理员
*/
const isAdmin = (): boolean => {
return user?.roles?.includes(ROLE_CODES.ADMIN) ?? false;
};
/**
* 检查是否是主管
*/
const isSupervisor = (): boolean => {
return user?.roles?.includes(ROLE_CODES.SUPERVISOR) ?? false;
};
/**
* 检查是否是导师
*/
const isMentor = (): boolean => {
return user?.roles?.includes(ROLE_CODES.MENTOR) ?? false;
};
/**
* 检查是否是学员
*/
const isStudent = (): boolean => {
return user?.roles?.includes(ROLE_CODES.STUDENT) ?? false;
};
/**
* 检查是否有指定角色
*/
const hasRole = (role: string): boolean => {
return user?.roles?.includes(role) ?? false;
};
return {
permissions,
hasPermission,
hasAllPermissions,
hasAnyPermission,
isAdmin,
isSupervisor,
isMentor,
isStudent,
hasRole,
};
};
export default usePermission;
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论