first commit
This commit is contained in:
591
frontend/js/admin.js
Normal file
591
frontend/js/admin.js
Normal file
@@ -0,0 +1,591 @@
|
||||
class AdminDashboard {
|
||||
constructor() {
|
||||
// 动态设置API基础URL,支持file:///协议和localhost:3000访问
|
||||
this.apiBase = window.location.protocol === 'file:' ? 'http://localhost:3000/api' : '/api';
|
||||
this.currentUser = null;
|
||||
this.stats = {};
|
||||
this.users = [];
|
||||
this.students = [];
|
||||
this.teachers = [];
|
||||
this.init();
|
||||
}
|
||||
|
||||
async init() {
|
||||
// 检查登录状态
|
||||
if (!await this.checkAuth()) {
|
||||
window.location.href = '/frontend/html/login.html';
|
||||
return;
|
||||
}
|
||||
|
||||
// 加载用户信息
|
||||
await this.loadUserInfo();
|
||||
|
||||
// 加载统计数据
|
||||
await this.loadStats();
|
||||
|
||||
// 加载用户数据
|
||||
await this.loadUsers();
|
||||
|
||||
// 绑定事件
|
||||
this.bindEvents();
|
||||
|
||||
// 更新界面
|
||||
this.updateUI();
|
||||
|
||||
// 初始化图表
|
||||
this.initCharts();
|
||||
}
|
||||
|
||||
async checkAuth() {
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/auth/me`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
return data.success && data.user.role === 'admin';
|
||||
} catch (error) {
|
||||
console.error('认证检查失败:', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async loadUserInfo() {
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/auth/me`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
if (data.success) {
|
||||
this.currentUser = data.user;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('加载用户信息失败:', error);
|
||||
}
|
||||
}
|
||||
|
||||
async loadStats() {
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/admin/stats`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
if (data.success) {
|
||||
this.stats = data.stats;
|
||||
this.updateStatsUI();
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('加载统计数据失败:', error);
|
||||
this.showNotification('加载统计数据失败', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async loadUsers() {
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/admin/users`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
if (data.success) {
|
||||
this.users = data.users;
|
||||
this.renderUsersTable();
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('加载用户数据失败:', error);
|
||||
this.showNotification('加载用户数据失败', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
updateStatsUI() {
|
||||
// 更新统计卡片
|
||||
const statElements = {
|
||||
'totalUsers': 'totalUsers',
|
||||
'totalStudents': 'totalStudents',
|
||||
'totalTeachers': 'totalTeachers',
|
||||
'totalCourses': 'totalCourses',
|
||||
'totalGrades': 'totalGrades',
|
||||
'avgScore': 'avgScore'
|
||||
};
|
||||
|
||||
Object.entries(statElements).forEach(([key, elementId]) => {
|
||||
const element = document.getElementById(elementId);
|
||||
if (element && this.stats[key] !== undefined) {
|
||||
element.textContent = this.stats[key];
|
||||
}
|
||||
});
|
||||
|
||||
// 更新时间
|
||||
const timeElement = document.getElementById('currentTime');
|
||||
if (timeElement) {
|
||||
timeElement.textContent = new Date().toLocaleString();
|
||||
}
|
||||
}
|
||||
|
||||
renderUsersTable() {
|
||||
const tableBody = document.getElementById('usersTableBody');
|
||||
if (!tableBody) return;
|
||||
|
||||
if (this.users.length === 0) {
|
||||
tableBody.innerHTML = `
|
||||
<tr>
|
||||
<td colspan="7" class="text-center">
|
||||
<div class="no-data">
|
||||
<i class="fas fa-info-circle"></i>
|
||||
<p>暂无用户数据</p>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
`;
|
||||
return;
|
||||
}
|
||||
|
||||
tableBody.innerHTML = this.users.map(user => {
|
||||
const roleClass = this.getRoleClass(user.role);
|
||||
return `
|
||||
<tr>
|
||||
<td><input type="checkbox" class="user-checkbox" data-id="${user.id}"></td>
|
||||
<td>${user.user_id}</td>
|
||||
<td>${user.full_name}</td>
|
||||
<td><span class="role-badge ${roleClass}">${user.role}</span></td>
|
||||
<td>${user.class_name || 'N/A'}</td>
|
||||
<td>${user.email || 'N/A'}</td>
|
||||
<td>
|
||||
<div class="action-buttons">
|
||||
<button class="btn-edit" data-id="${user.id}">
|
||||
<i class="fas fa-edit"></i> 编辑
|
||||
</button>
|
||||
<button class="btn-delete" data-id="${user.id}">
|
||||
<i class="fas fa-trash"></i> 删除
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
getRoleClass(role) {
|
||||
switch (role) {
|
||||
case 'admin': return 'role-admin';
|
||||
case 'teacher': return 'role-teacher';
|
||||
case 'student': return 'role-student';
|
||||
default: return 'role-default';
|
||||
}
|
||||
}
|
||||
|
||||
bindEvents() {
|
||||
// 导航菜单点击
|
||||
document.querySelectorAll('.nav-link').forEach(link => {
|
||||
link.addEventListener('click', (e) => {
|
||||
e.preventDefault();
|
||||
const page = link.dataset.page;
|
||||
this.loadPage(page);
|
||||
});
|
||||
});
|
||||
|
||||
// 搜索按钮
|
||||
document.getElementById('searchBtn')?.addEventListener('click', () => {
|
||||
this.handleSearch();
|
||||
});
|
||||
|
||||
// 重置按钮
|
||||
document.getElementById('resetBtn')?.addEventListener('click', () => {
|
||||
this.resetFilters();
|
||||
});
|
||||
|
||||
// 添加用户按钮
|
||||
document.getElementById('addUserBtn')?.addEventListener('click', () => {
|
||||
this.addUser();
|
||||
});
|
||||
|
||||
// 导出按钮
|
||||
document.getElementById('exportBtn')?.addEventListener('click', () => {
|
||||
this.exportUsers();
|
||||
});
|
||||
|
||||
// 批量删除按钮
|
||||
document.getElementById('batchDeleteBtn')?.addEventListener('click', () => {
|
||||
this.batchDeleteUsers();
|
||||
});
|
||||
|
||||
// 表格操作按钮事件委托
|
||||
document.addEventListener('click', (e) => {
|
||||
if (e.target.closest('.btn-edit')) {
|
||||
const userId = e.target.closest('.btn-edit').dataset.id;
|
||||
this.editUser(userId);
|
||||
}
|
||||
|
||||
if (e.target.closest('.btn-delete')) {
|
||||
const userId = e.target.closest('.btn-delete').dataset.id;
|
||||
this.deleteUser(userId);
|
||||
}
|
||||
});
|
||||
|
||||
// 退出登录
|
||||
document.getElementById('logoutBtn')?.addEventListener('click', () => {
|
||||
this.handleLogout();
|
||||
});
|
||||
|
||||
// 刷新按钮
|
||||
document.getElementById('refreshBtn')?.addEventListener('click', () => {
|
||||
this.refreshData();
|
||||
});
|
||||
}
|
||||
|
||||
async loadPage(page) {
|
||||
// 这里可以实现页面切换逻辑
|
||||
// 暂时使用简单跳转
|
||||
switch (page) {
|
||||
case 'users':
|
||||
window.location.href = '/frontend/html/user_management.html';
|
||||
break;
|
||||
case 'students':
|
||||
window.location.href = '/frontend/html/student_management.html';
|
||||
break;
|
||||
case 'teachers':
|
||||
// 可以跳转到教师管理页面
|
||||
break;
|
||||
case 'grades':
|
||||
window.location.href = '/frontend/html/grade_management.html';
|
||||
break;
|
||||
case 'settings':
|
||||
// 可以跳转到系统设置页面
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
handleSearch() {
|
||||
const userId = document.getElementById('userIdFilter')?.value || '';
|
||||
const name = document.getElementById('nameFilter')?.value || '';
|
||||
const role = document.getElementById('roleFilter')?.value || '';
|
||||
const className = document.getElementById('classFilter')?.value || '';
|
||||
|
||||
// 这里可以实现搜索逻辑
|
||||
this.showNotification('搜索功能待实现', 'info');
|
||||
}
|
||||
|
||||
resetFilters() {
|
||||
document.getElementById('userIdFilter').value = '';
|
||||
document.getElementById('nameFilter').value = '';
|
||||
document.getElementById('roleFilter').value = '';
|
||||
document.getElementById('classFilter').value = '';
|
||||
|
||||
// 重新加载数据
|
||||
this.loadUsers();
|
||||
}
|
||||
|
||||
async addUser() {
|
||||
// 这里可以打开添加用户模态框
|
||||
const userData = {
|
||||
user_id: prompt('请输入用户ID:'),
|
||||
full_name: prompt('请输入姓名:'),
|
||||
role: prompt('请输入角色 (admin/teacher/student):'),
|
||||
email: prompt('请输入邮箱:'),
|
||||
class_name: prompt('请输入班级 (学生/教师可选):')
|
||||
};
|
||||
|
||||
if (!userData.user_id || !userData.full_name || !userData.role) {
|
||||
this.showNotification('用户ID、姓名和角色为必填项', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/admin/users`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
credentials: 'include',
|
||||
body: JSON.stringify(userData)
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
if (data.success) {
|
||||
this.showNotification('用户添加成功', 'success');
|
||||
await this.loadUsers();
|
||||
} else {
|
||||
this.showNotification(data.message || '添加失败', 'error');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('添加用户失败:', error);
|
||||
this.showNotification('添加用户失败', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async exportUsers() {
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/admin/users/export`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const blob = await response.blob();
|
||||
const url = window.URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `用户列表_${new Date().toISOString().split('T')[0]}.xlsx`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
window.URL.revokeObjectURL(url);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('导出失败:', error);
|
||||
this.showNotification('导出失败', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async batchDeleteUsers() {
|
||||
const checkboxes = document.querySelectorAll('.user-checkbox:checked');
|
||||
if (checkboxes.length === 0) {
|
||||
this.showNotification('请选择要删除的用户', 'warning');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!confirm(`确定要删除选中的 ${checkboxes.length} 个用户吗?`)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const userIds = Array.from(checkboxes).map(cb => cb.dataset.id);
|
||||
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/admin/users/batch`, {
|
||||
method: 'DELETE',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
credentials: 'include',
|
||||
body: JSON.stringify({ userIds })
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
if (data.success) {
|
||||
this.showNotification(`成功删除 ${userIds.length} 个用户`, 'success');
|
||||
await this.loadUsers();
|
||||
} else {
|
||||
this.showNotification(data.message || '删除失败', 'error');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('批量删除失败:', error);
|
||||
this.showNotification('批量删除失败', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async editUser(userId) {
|
||||
const user = this.users.find(u => u.id == userId);
|
||||
if (!user) return;
|
||||
|
||||
// 这里可以打开编辑模态框
|
||||
const newName = prompt('请输入新的姓名:', user.full_name);
|
||||
if (newName === null) return;
|
||||
|
||||
const newRole = prompt('请输入新的角色:', user.role);
|
||||
if (newRole === null) return;
|
||||
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/admin/users/${userId}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
credentials: 'include',
|
||||
body: JSON.stringify({
|
||||
full_name: newName,
|
||||
role: newRole,
|
||||
email: user.email,
|
||||
class_name: user.class_name
|
||||
})
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
if (data.success) {
|
||||
this.showNotification('用户更新成功', 'success');
|
||||
await this.loadUsers();
|
||||
} else {
|
||||
this.showNotification(data.message || '更新失败', 'error');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('更新用户失败:', error);
|
||||
this.showNotification('更新用户失败', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async deleteUser(userId) {
|
||||
if (!confirm('确定要删除这个用户吗?')) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/admin/users/${userId}`, {
|
||||
method: 'DELETE',
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
if (data.success) {
|
||||
this.showNotification('用户删除成功', 'success');
|
||||
await this.loadUsers();
|
||||
} else {
|
||||
this.showNotification(data.message || '删除失败', 'error');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('删除用户失败:', error);
|
||||
this.showNotification('删除用户失败', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async handleLogout() {
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/auth/logout`, {
|
||||
method: 'POST',
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
window.location.href = '/html/login.html';
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('退出登录失败:', error);
|
||||
}
|
||||
}
|
||||
|
||||
async refreshData() {
|
||||
await this.loadStats();
|
||||
await this.loadUsers();
|
||||
this.showNotification('数据已刷新', 'success');
|
||||
}
|
||||
|
||||
updateUI() {
|
||||
// 更新用户信息
|
||||
if (this.currentUser) {
|
||||
const userInfoElements = document.querySelectorAll('.user-info');
|
||||
userInfoElements.forEach(el => {
|
||||
el.textContent = `${this.currentUser.full_name} (${this.currentUser.role})`;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async initCharts() {
|
||||
// 加载Chart.js库
|
||||
await this.loadChartLibrary();
|
||||
|
||||
// 初始化用户分布饼图
|
||||
this.initUserDistributionChart();
|
||||
|
||||
// 初始化成绩分布柱状图
|
||||
this.initGradeDistributionChart();
|
||||
}
|
||||
|
||||
showNotification(message, type = 'info') {
|
||||
// 创建通知元素
|
||||
const notification = document.createElement('div');
|
||||
notification.className = `notification notification-${type}`;
|
||||
notification.innerHTML = `
|
||||
<i class="fas fa-${type === 'success' ? 'check-circle' : type === 'error' ? 'exclamation-circle' : type === 'warning' ? 'exclamation-triangle' : 'info-circle'}"></i>
|
||||
<span>${message}</span>
|
||||
<button class="notification-close">×</button>
|
||||
`;
|
||||
|
||||
// 添加到页面
|
||||
document.body.appendChild(notification);
|
||||
|
||||
// 添加关闭事件
|
||||
notification.querySelector('.notification-close').addEventListener('click', () => {
|
||||
notification.remove();
|
||||
});
|
||||
|
||||
// 自动移除
|
||||
setTimeout(() => {
|
||||
if (notification.parentNode) {
|
||||
notification.remove();
|
||||
}
|
||||
}, 5000);
|
||||
}
|
||||
|
||||
async loadChartLibrary() {
|
||||
if (typeof Chart !== 'undefined') return;
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const script = document.createElement('script');
|
||||
script.src = 'https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js';
|
||||
script.onload = resolve;
|
||||
script.onerror = reject;
|
||||
document.head.appendChild(script);
|
||||
});
|
||||
}
|
||||
|
||||
initUserDistributionChart() {
|
||||
const ctx = document.getElementById('userDistributionChart');
|
||||
if (!ctx) return;
|
||||
|
||||
// 模拟数据
|
||||
const data = {
|
||||
labels: ['学生', '教师', '管理员'],
|
||||
datasets: [{
|
||||
data: [this.stats.totalStudents || 100, this.stats.totalTeachers || 20, 1],
|
||||
backgroundColor: [
|
||||
'rgba(54, 162, 235, 0.8)',
|
||||
'rgba(255, 206, 86, 0.8)',
|
||||
'rgba(255, 99, 132, 0.8)'
|
||||
]
|
||||
}]
|
||||
};
|
||||
|
||||
new Chart(ctx, {
|
||||
type: 'pie',
|
||||
data: data,
|
||||
options: {
|
||||
responsive: true,
|
||||
plugins: {
|
||||
legend: {
|
||||
position: 'bottom'
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
initGradeDistributionChart() {
|
||||
const ctx = document.getElementById('gradeDistributionChart');
|
||||
if (!ctx) return;
|
||||
|
||||
// 模拟数据
|
||||
const data = {
|
||||
labels: ['A', 'B', 'C', 'D', 'F'],
|
||||
datasets: [{
|
||||
label: '成绩分布',
|
||||
data: [25, 35, 20, 15, 5],
|
||||
backgroundColor: [
|
||||
'rgba(75, 192, 192, 0.8)',
|
||||
'rgba(54, 162, 235, 0.8)',
|
||||
'rgba(255, 206, 86, 0.8)',
|
||||
'rgba(255, 159, 64, 0.8)',
|
||||
'rgba(255, 99, 132, 0.8)'
|
||||
]
|
||||
}]
|
||||
};
|
||||
|
||||
new Chart(ctx, {
|
||||
type: 'bar',
|
||||
data: data,
|
||||
options: {
|
||||
responsive: true,
|
||||
scales: {
|
||||
y: {
|
||||
beginAtZero: true,
|
||||
ticks: {
|
||||
stepSize: 10
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
269
frontend/js/auth.js
Normal file
269
frontend/js/auth.js
Normal file
@@ -0,0 +1,269 @@
|
||||
class AuthManager {
|
||||
constructor() {
|
||||
// 动态设置API基础URL,支持file:///协议和localhost:3000访问
|
||||
this.apiBase = window.location.protocol === 'file:' ? 'http://localhost:3000/api' : '/api';
|
||||
this.initEventListeners();
|
||||
this.checkAuthStatus();
|
||||
}
|
||||
|
||||
async checkAuthStatus() {
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/auth/me`);
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success && data.user) {
|
||||
// 用户已登录,根据角色重定向到正确的仪表板
|
||||
const userRole = data.user.role;
|
||||
let redirectUrl = '/dashboard';
|
||||
|
||||
if (userRole === 'student') {
|
||||
redirectUrl = '/frontend/html/student_dashboard.html';
|
||||
} else if (userRole === 'teacher') {
|
||||
redirectUrl = '/frontend/html/teacher_dashboard.html';
|
||||
} else if (userRole === 'admin') {
|
||||
redirectUrl = '/frontend/html/admin_dashboard.html';
|
||||
}
|
||||
|
||||
// 如果当前页面是登录或注册页面,则重定向到仪表板
|
||||
const currentPath = window.location.pathname;
|
||||
if (currentPath.includes('login.html') || currentPath.includes('register.html')) {
|
||||
window.location.href = redirectUrl;
|
||||
}
|
||||
// 如果当前页面不是正确的仪表板页面,则重定向
|
||||
else if (!currentPath.includes(redirectUrl) &&
|
||||
currentPath !== '/' &&
|
||||
!currentPath.includes('index.html')) {
|
||||
window.location.href = redirectUrl;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.log('用户未登录');
|
||||
}
|
||||
}
|
||||
|
||||
initEventListeners() {
|
||||
// 登录表单提交
|
||||
const loginForm = document.getElementById('loginForm');
|
||||
if (loginForm) {
|
||||
loginForm.addEventListener('submit', (e) => this.handleLogin(e));
|
||||
}
|
||||
|
||||
// 注册表单提交
|
||||
const registerForm = document.getElementById('registerForm');
|
||||
if (registerForm) {
|
||||
registerForm.addEventListener('submit', (e) => this.handleRegister(e));
|
||||
}
|
||||
|
||||
// 登出按钮
|
||||
const logoutBtn = document.getElementById('logoutBtn');
|
||||
if (logoutBtn) {
|
||||
logoutBtn.addEventListener('click', (e) => this.handleLogout(e));
|
||||
}
|
||||
}
|
||||
|
||||
async handleLogin(e) {
|
||||
e.preventDefault();
|
||||
|
||||
const form = e.target;
|
||||
const formData = new FormData(form);
|
||||
const data = Object.fromEntries(formData.entries());
|
||||
|
||||
const submitBtn = form.querySelector('button[type="submit"]');
|
||||
const originalText = submitBtn.innerHTML;
|
||||
submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 登录中...';
|
||||
submitBtn.disabled = true;
|
||||
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/auth/login`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify(data)
|
||||
});
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
if (result.success) {
|
||||
this.showNotification('登录成功!正在跳转...', 'success');
|
||||
|
||||
// 根据用户角色跳转到不同的仪表板
|
||||
const userRole = result.user?.role;
|
||||
let redirectUrl = '/dashboard';
|
||||
|
||||
if (userRole === 'student') {
|
||||
redirectUrl = '/frontend/html/student_dashboard.html';
|
||||
} else if (userRole === 'teacher') {
|
||||
redirectUrl = '/frontend/html/teacher_dashboard.html';
|
||||
} else if (userRole === 'admin') {
|
||||
redirectUrl = '/frontend/html/admin_dashboard.html';
|
||||
}
|
||||
|
||||
// 延迟跳转以显示通知
|
||||
setTimeout(() => {
|
||||
window.location.href = redirectUrl;
|
||||
}, 1500);
|
||||
} else {
|
||||
this.showNotification(result.message || '登录失败', 'error');
|
||||
submitBtn.innerHTML = originalText;
|
||||
submitBtn.disabled = false;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('登录错误:', error);
|
||||
this.showNotification('网络错误,请重试', 'error');
|
||||
submitBtn.innerHTML = originalText;
|
||||
submitBtn.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
async handleRegister(e) {
|
||||
e.preventDefault();
|
||||
|
||||
const form = e.target;
|
||||
const formData = new FormData(form);
|
||||
const data = Object.fromEntries(formData.entries());
|
||||
|
||||
// 验证密码
|
||||
if (data.password !== data.confirmPassword) {
|
||||
this.showNotification('两次输入的密码不一致', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
const submitBtn = form.querySelector('button[type="submit"]');
|
||||
const originalText = submitBtn.innerHTML;
|
||||
submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 注册中...';
|
||||
submitBtn.disabled = true;
|
||||
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/auth/register`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify(data)
|
||||
});
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
if (result.success) {
|
||||
this.showNotification('注册成功!正在跳转到登录页面...', 'success');
|
||||
|
||||
setTimeout(() => {
|
||||
window.location.href = '/html/login.html';
|
||||
}, 1500);
|
||||
} else {
|
||||
this.showNotification(result.message || '注册失败', 'error');
|
||||
submitBtn.innerHTML = originalText;
|
||||
submitBtn.disabled = false;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('注册错误:', error);
|
||||
this.showNotification('网络错误,请重试', 'error');
|
||||
submitBtn.innerHTML = originalText;
|
||||
submitBtn.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
async handleLogout(e) {
|
||||
e.preventDefault();
|
||||
|
||||
if (!confirm('确定要退出登录吗?')) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/auth/logout`, {
|
||||
method: 'POST'
|
||||
});
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
if (result.success) {
|
||||
this.showNotification('已成功退出登录', 'success');
|
||||
setTimeout(() => {
|
||||
window.location.href = '/';
|
||||
}, 1000);
|
||||
} else {
|
||||
this.showNotification('退出登录失败', 'error');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('退出登录错误:', error);
|
||||
this.showNotification('网络错误,请重试', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
showNotification(message, type = 'info') {
|
||||
// 移除现有的通知
|
||||
const existingNotification = document.querySelector('.notification');
|
||||
if (existingNotification) {
|
||||
existingNotification.remove();
|
||||
}
|
||||
|
||||
// 创建新的通知
|
||||
const notification = document.createElement('div');
|
||||
notification.className = `notification notification-${type}`;
|
||||
notification.innerHTML = `
|
||||
<i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-circle'}"></i>
|
||||
<span>${message}</span>
|
||||
`;
|
||||
|
||||
// 样式
|
||||
notification.style.cssText = `
|
||||
position: fixed;
|
||||
top: 20px;
|
||||
right: 20px;
|
||||
background: ${type === 'success' ? '#10b981' : type === 'error' ? '#ef4444' : '#3b82f6'};
|
||||
color: white;
|
||||
padding: 15px 20px;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
z-index: 1000;
|
||||
animation: slideIn 0.3s ease;
|
||||
`;
|
||||
|
||||
document.body.appendChild(notification);
|
||||
|
||||
// 3秒后自动移除
|
||||
setTimeout(() => {
|
||||
notification.style.animation = 'slideOut 0.3s ease';
|
||||
setTimeout(() => notification.remove(), 300);
|
||||
}, 3000);
|
||||
|
||||
// 添加动画关键帧
|
||||
if (!document.querySelector('#notification-styles')) {
|
||||
const style = document.createElement('style');
|
||||
style.id = 'notification-styles';
|
||||
style.textContent = `
|
||||
@keyframes slideIn {
|
||||
from {
|
||||
transform: translateX(100%);
|
||||
opacity: 0;
|
||||
}
|
||||
to {
|
||||
transform: translateX(0);
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
@keyframes slideOut {
|
||||
from {
|
||||
transform: translateX(0);
|
||||
opacity: 1;
|
||||
}
|
||||
to {
|
||||
transform: translateX(100%);
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
`;
|
||||
document.head.appendChild(style);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 初始化认证管理器
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
window.authManager = new AuthManager();
|
||||
});
|
||||
222
frontend/js/main.js
Normal file
222
frontend/js/main.js
Normal file
@@ -0,0 +1,222 @@
|
||||
// 首页通用JavaScript功能
|
||||
// 主要处理导航栏交互、页面滚动效果等通用功能
|
||||
|
||||
class MainPage {
|
||||
constructor() {
|
||||
this.init();
|
||||
}
|
||||
|
||||
init() {
|
||||
// 初始化所有功能
|
||||
this.initNavbar();
|
||||
this.initScrollEffects();
|
||||
this.initSmoothScroll();
|
||||
this.initBackToTop();
|
||||
this.initMobileMenu();
|
||||
this.initAuthButtons();
|
||||
}
|
||||
|
||||
// 初始化导航栏交互
|
||||
initNavbar() {
|
||||
const navbar = document.querySelector('.navbar');
|
||||
if (!navbar) return;
|
||||
|
||||
// 滚动时改变导航栏样式
|
||||
window.addEventListener('scroll', () => {
|
||||
if (window.scrollY > 50) {
|
||||
navbar.classList.add('navbar-scrolled');
|
||||
} else {
|
||||
navbar.classList.remove('navbar-scrolled');
|
||||
}
|
||||
});
|
||||
|
||||
// 初始化当前页面高亮
|
||||
this.highlightCurrentPage();
|
||||
}
|
||||
|
||||
// 高亮当前页面导航链接
|
||||
highlightCurrentPage() {
|
||||
const currentPath = window.location.pathname;
|
||||
const navLinks = document.querySelectorAll('.nav-link');
|
||||
|
||||
navLinks.forEach(link => {
|
||||
const href = link.getAttribute('href');
|
||||
if (href && currentPath.includes(href.replace('.html', ''))) {
|
||||
link.classList.add('active');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// 初始化滚动效果
|
||||
initScrollEffects() {
|
||||
// 滚动时显示/隐藏元素
|
||||
const observerOptions = {
|
||||
root: null,
|
||||
rootMargin: '0px',
|
||||
threshold: 0.1
|
||||
};
|
||||
|
||||
const observer = new IntersectionObserver((entries) => {
|
||||
entries.forEach(entry => {
|
||||
if (entry.isIntersecting) {
|
||||
entry.target.classList.add('animate-in');
|
||||
}
|
||||
});
|
||||
}, observerOptions);
|
||||
|
||||
// 观察需要动画的元素
|
||||
document.querySelectorAll('.feature-card, .hero-content').forEach(el => {
|
||||
observer.observe(el);
|
||||
});
|
||||
}
|
||||
|
||||
// 初始化平滑滚动
|
||||
initSmoothScroll() {
|
||||
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
|
||||
anchor.addEventListener('click', (e) => {
|
||||
e.preventDefault();
|
||||
const targetId = anchor.getAttribute('href');
|
||||
if (targetId === '#') return;
|
||||
|
||||
const targetElement = document.querySelector(targetId);
|
||||
if (targetElement) {
|
||||
targetElement.scrollIntoView({
|
||||
behavior: 'smooth',
|
||||
block: 'start'
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// 初始化返回顶部按钮
|
||||
initBackToTop() {
|
||||
const backToTopBtn = document.createElement('button');
|
||||
backToTopBtn.id = 'backToTop';
|
||||
backToTopBtn.innerHTML = '<i class="fas fa-chevron-up"></i>';
|
||||
backToTopBtn.title = '返回顶部';
|
||||
document.body.appendChild(backToTopBtn);
|
||||
|
||||
// 滚动时显示/隐藏按钮
|
||||
window.addEventListener('scroll', () => {
|
||||
if (window.scrollY > 300) {
|
||||
backToTopBtn.classList.add('show');
|
||||
} else {
|
||||
backToTopBtn.classList.remove('show');
|
||||
}
|
||||
});
|
||||
|
||||
// 点击返回顶部
|
||||
backToTopBtn.addEventListener('click', () => {
|
||||
window.scrollTo({
|
||||
top: 0,
|
||||
behavior: 'smooth'
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// 初始化移动端菜单
|
||||
initMobileMenu() {
|
||||
const navbarToggler = document.querySelector('.navbar-toggler');
|
||||
const navbarCollapse = document.querySelector('.navbar-collapse');
|
||||
|
||||
if (!navbarToggler || !navbarCollapse) return;
|
||||
|
||||
navbarToggler.addEventListener('click', () => {
|
||||
navbarCollapse.classList.toggle('show');
|
||||
});
|
||||
|
||||
// 点击菜单项后自动关闭移动菜单
|
||||
document.querySelectorAll('.navbar-nav .nav-link').forEach(link => {
|
||||
link.addEventListener('click', () => {
|
||||
if (navbarCollapse.classList.contains('show')) {
|
||||
navbarCollapse.classList.remove('show');
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// 初始化认证按钮状态
|
||||
initAuthButtons() {
|
||||
// 检查用户是否已登录
|
||||
this.checkLoginStatus().then(user => {
|
||||
const loginBtn = document.getElementById('loginBtn');
|
||||
const registerBtn = document.getElementById('registerBtn');
|
||||
const heroLoginBtn = document.getElementById('heroLoginBtn');
|
||||
|
||||
if (user) {
|
||||
// 用户已登录,显示仪表板按钮
|
||||
// 根据用户角色设置正确的仪表板路径
|
||||
let dashboardUrl = '/dashboard';
|
||||
if (user.role === 'student') {
|
||||
dashboardUrl = '/frontend/html/student_dashboard.html';
|
||||
} else if (user.role === 'teacher') {
|
||||
dashboardUrl = '/frontend/html/teacher_dashboard.html';
|
||||
} else if (user.role === 'admin') {
|
||||
dashboardUrl = '/frontend/html/admin_dashboard.html';
|
||||
}
|
||||
|
||||
if (loginBtn) {
|
||||
loginBtn.textContent = '进入仪表板';
|
||||
loginBtn.href = dashboardUrl;
|
||||
}
|
||||
if (heroLoginBtn) {
|
||||
heroLoginBtn.textContent = '进入仪表板';
|
||||
heroLoginBtn.href = dashboardUrl;
|
||||
}
|
||||
if (registerBtn) {
|
||||
registerBtn.style.display = 'none';
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// 检查登录状态
|
||||
async checkLoginStatus() {
|
||||
try {
|
||||
const apiBase = window.location.protocol === 'file:' ? 'http://localhost:3000/api' : '/api';
|
||||
const response = await fetch(`${apiBase}/auth/me`);
|
||||
const data = await response.json();
|
||||
return data.success && data.user;
|
||||
} catch (error) {
|
||||
console.log('用户未登录');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 显示通知
|
||||
showNotification(message, type = 'info') {
|
||||
// 创建通知元素
|
||||
const notification = document.createElement('div');
|
||||
notification.className = `notification notification-${type}`;
|
||||
notification.innerHTML = `
|
||||
<div class="notification-content">
|
||||
<i class="fas ${type === 'success' ? 'fa-check-circle' : type === 'error' ? 'fa-exclamation-circle' : 'fa-info-circle'}"></i>
|
||||
<span>${message}</span>
|
||||
</div>
|
||||
`;
|
||||
|
||||
// 添加到页面
|
||||
document.body.appendChild(notification);
|
||||
|
||||
// 显示通知
|
||||
setTimeout(() => {
|
||||
notification.classList.add('show');
|
||||
}, 10);
|
||||
|
||||
// 自动隐藏
|
||||
setTimeout(() => {
|
||||
notification.classList.remove('show');
|
||||
setTimeout(() => {
|
||||
if (notification.parentNode) {
|
||||
notification.parentNode.removeChild(notification);
|
||||
}
|
||||
}, 300);
|
||||
}, 3000);
|
||||
}
|
||||
}
|
||||
|
||||
// 页面加载完成后初始化
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
new MainPage();
|
||||
});
|
||||
438
frontend/js/student.js
Normal file
438
frontend/js/student.js
Normal file
@@ -0,0 +1,438 @@
|
||||
class StudentManager {
|
||||
constructor() {
|
||||
// 动态设置API基础URL,支持file:///协议和localhost:3000访问
|
||||
this.apiBase = window.location.protocol === 'file:' ? 'http://localhost:3000/api' : '/api';
|
||||
this.initDashboard();
|
||||
this.initGradeDetails();
|
||||
this.loadProfile();
|
||||
}
|
||||
|
||||
async initDashboard() {
|
||||
const gradeList = document.getElementById('gradeList');
|
||||
const statisticsElement = document.getElementById('statistics');
|
||||
|
||||
if (!gradeList) return;
|
||||
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/student/grades`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (response.status === 401) {
|
||||
// 未登录,重定向到登录页
|
||||
this.showNotification('请先登录', 'error');
|
||||
setTimeout(() => {
|
||||
window.location.href = '/html/login.html';
|
||||
}, 1500);
|
||||
return;
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
this.renderGrades(data.grades);
|
||||
this.renderStatistics(data.statistics);
|
||||
this.updateChart(data.grades);
|
||||
} else {
|
||||
this.showNotification(data.message || '获取成绩失败', 'error');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('获取成绩错误:', error);
|
||||
this.showNotification('网络错误,请重试', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
renderGrades(grades) {
|
||||
const gradeList = document.getElementById('gradeList');
|
||||
const gradeTable = document.getElementById('gradeTable');
|
||||
|
||||
if (!gradeTable) return;
|
||||
|
||||
if (grades.length === 0) {
|
||||
gradeList.innerHTML = `
|
||||
<div class="empty-state">
|
||||
<i class="fas fa-clipboard-list fa-3x"></i>
|
||||
<h3>暂无成绩记录</h3>
|
||||
<p>你还没有任何成绩记录</p>
|
||||
</div>
|
||||
`;
|
||||
return;
|
||||
}
|
||||
|
||||
const tbody = gradeTable.querySelector('tbody');
|
||||
tbody.innerHTML = '';
|
||||
|
||||
grades.forEach(grade => {
|
||||
const row = document.createElement('tr');
|
||||
|
||||
// 根据分数设置颜色
|
||||
let scoreClass = '';
|
||||
if (grade.score >= 90) scoreClass = 'grade-excellent';
|
||||
else if (grade.score >= 80) scoreClass = 'grade-good';
|
||||
else if (grade.score >= 60) scoreClass = 'grade-pass';
|
||||
else scoreClass = 'grade-fail';
|
||||
|
||||
row.innerHTML = `
|
||||
<td>${grade.course_code}</td>
|
||||
<td>${grade.course_name}</td>
|
||||
<td>${grade.credit}</td>
|
||||
<td class="${scoreClass}">
|
||||
<span class="grade-badge">${grade.score}</span>
|
||||
</td>
|
||||
<td>${grade.grade_level || '-'}</td>
|
||||
<td>${grade.grade_point || '-'}</td>
|
||||
<td>${grade.teacher_name}</td>
|
||||
<td>${new Date(grade.exam_date).toLocaleDateString()}</td>
|
||||
<td>
|
||||
<a href="/html/student/details.html?id=${grade.id}"
|
||||
class="btn btn-sm btn-secondary">
|
||||
<i class="fas fa-eye"></i> 查看
|
||||
</a>
|
||||
</td>
|
||||
`;
|
||||
|
||||
tbody.appendChild(row);
|
||||
});
|
||||
}
|
||||
|
||||
renderStatistics(statistics) {
|
||||
const element = document.getElementById('statistics');
|
||||
if (!element) return;
|
||||
|
||||
element.innerHTML = `
|
||||
<div class="stats-grid">
|
||||
<div class="stat-card">
|
||||
<div class="stat-icon student">
|
||||
<i class="fas fa-book"></i>
|
||||
</div>
|
||||
<div class="stat-value">${statistics.totalCourses}</div>
|
||||
<div class="stat-label">总课程数</div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="stat-icon course">
|
||||
<i class="fas fa-star"></i>
|
||||
</div>
|
||||
<div class="stat-value">${statistics.totalCredits}</div>
|
||||
<div class="stat-label">总学分</div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="stat-icon grade">
|
||||
<i class="fas fa-chart-line"></i>
|
||||
</div>
|
||||
<div class="stat-value">${statistics.averageScore}</div>
|
||||
<div class="stat-label">平均分</div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="stat-icon teacher">
|
||||
<i class="fas fa-graduation-cap"></i>
|
||||
</div>
|
||||
<div class="stat-value">${statistics.gpa}</div>
|
||||
<div class="stat-label">平均绩点</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
async loadProfile() {
|
||||
const profileElement = document.getElementById('profileInfo');
|
||||
if (!profileElement) return;
|
||||
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/student/profile`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (response.status === 401) {
|
||||
// 未登录,重定向到登录页
|
||||
this.showNotification('请先登录', 'error');
|
||||
setTimeout(() => {
|
||||
window.location.href = '/html/login.html';
|
||||
}, 1500);
|
||||
return;
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
const profile = data.profile;
|
||||
|
||||
// 更新学生仪表板顶部信息
|
||||
const userNameElement = document.getElementById('userName');
|
||||
const studentNameElement = document.getElementById('studentName');
|
||||
const studentClassElement = document.getElementById('studentClass');
|
||||
|
||||
if (userNameElement) {
|
||||
userNameElement.textContent = profile.full_name || profile.username;
|
||||
}
|
||||
if (studentNameElement) {
|
||||
studentNameElement.textContent = profile.full_name || profile.username;
|
||||
}
|
||||
if (studentClassElement) {
|
||||
studentClassElement.textContent = profile.class_name || '未设置';
|
||||
}
|
||||
|
||||
profileElement.innerHTML = `
|
||||
<div class="profile-header">
|
||||
<div class="profile-avatar">
|
||||
<i class="fas fa-user-graduate"></i>
|
||||
</div>
|
||||
<div class="profile-info">
|
||||
<h2>${profile.full_name}</h2>
|
||||
<p class="profile-role">
|
||||
<i class="fas fa-user-tag"></i> 学生
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="profile-details">
|
||||
<div class="detail-item">
|
||||
<i class="fas fa-id-card"></i>
|
||||
<div>
|
||||
<h4>学号</h4>
|
||||
<p>${profile.student_id}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="detail-item">
|
||||
<i class="fas fa-users"></i>
|
||||
<div>
|
||||
<h4>班级</h4>
|
||||
<p>${profile.class_name}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="detail-item">
|
||||
<i class="fas fa-book"></i>
|
||||
<div>
|
||||
<h4>专业</h4>
|
||||
<p>${profile.major || '未设置'}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="detail-item">
|
||||
<i class="fas fa-calendar-alt"></i>
|
||||
<div>
|
||||
<h4>入学年份</h4>
|
||||
<p>${profile.enrollment_year || '未设置'}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
} else {
|
||||
// API返回失败
|
||||
this.showNotification(data.message || '获取个人信息失败', 'error');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('加载个人信息错误:', error);
|
||||
this.showNotification('网络错误,请重试', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async initGradeDetails() {
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
const gradeId = urlParams.get('id');
|
||||
|
||||
if (!gradeId) return;
|
||||
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/student/grades/${gradeId}`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
this.renderGradeDetails(data.grade);
|
||||
} else {
|
||||
this.showNotification('获取成绩详情失败', 'error');
|
||||
setTimeout(() => window.history.back(), 1500);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('获取成绩详情错误:', error);
|
||||
this.showNotification('网络错误,请重试', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
renderGradeDetails(grade) {
|
||||
const container = document.getElementById('gradeDetails');
|
||||
if (!container) return;
|
||||
|
||||
// 计算绩点描述
|
||||
let gradeDescription = '';
|
||||
if (grade.score >= 90) gradeDescription = '优秀';
|
||||
else if (grade.score >= 80) gradeDescription = '良好';
|
||||
else if (grade.score >= 70) gradeDescription = '中等';
|
||||
else if (grade.score >= 60) gradeDescription = '及格';
|
||||
else gradeDescription = '不及格';
|
||||
|
||||
container.innerHTML = `
|
||||
<div class="grade-detail-card">
|
||||
<div class="grade-header">
|
||||
<h2>${grade.course_name} (${grade.course_code})</h2>
|
||||
<div class="grade-score ${grade.score >= 60 ? 'score-pass' : 'score-fail'}">
|
||||
${grade.score} 分
|
||||
<span class="grade-description">${gradeDescription}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grade-details-grid">
|
||||
<div class="detail-section">
|
||||
<h3><i class="fas fa-info-circle"></i> 基本信息</h3>
|
||||
<div class="detail-row">
|
||||
<span>学分:</span>
|
||||
<strong>${grade.credit}</strong>
|
||||
</div>
|
||||
<div class="detail-row">
|
||||
<span>学期:</span>
|
||||
<strong>${grade.semester}</strong>
|
||||
</div>
|
||||
<div class="detail-row">
|
||||
<span>考试日期:</span>
|
||||
<strong>${new Date(grade.exam_date).toLocaleDateString()}</strong>
|
||||
</div>
|
||||
<div class="detail-row">
|
||||
<span>等级:</span>
|
||||
<strong class="grade-level-${grade.grade_level}">${grade.grade_level || '-'}</strong>
|
||||
</div>
|
||||
<div class="detail-row">
|
||||
<span>绩点:</span>
|
||||
<strong>${grade.grade_point || '-'}</strong>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="detail-section">
|
||||
<h3><i class="fas fa-user-graduate"></i> 学生信息</h3>
|
||||
<div class="detail-row">
|
||||
<span>姓名:</span>
|
||||
<strong>${grade.full_name}</strong>
|
||||
</div>
|
||||
<div class="detail-row">
|
||||
<span>学号:</span>
|
||||
<strong>${grade.student_number}</strong>
|
||||
</div>
|
||||
<div class="detail-row">
|
||||
<span>班级:</span>
|
||||
<strong>${grade.class_name}</strong>
|
||||
</div>
|
||||
<div class="detail-row">
|
||||
<span>专业:</span>
|
||||
<strong>${grade.major || '未设置'}</strong>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="detail-section">
|
||||
<h3><i class="fas fa-chalkboard-teacher"></i> 教师信息</h3>
|
||||
<div class="detail-row">
|
||||
<span>任课教师:</span>
|
||||
<strong>${grade.teacher_name}</strong>
|
||||
</div>
|
||||
<div class="detail-row">
|
||||
<span>教师邮箱:</span>
|
||||
<strong>${grade.teacher_email}</strong>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
${grade.remark ? `
|
||||
<div class="remark-section">
|
||||
<h3><i class="fas fa-comment"></i> 备注</h3>
|
||||
<p>${grade.remark}</p>
|
||||
</div>
|
||||
` : ''}
|
||||
|
||||
<div class="grade-actions">
|
||||
<button onclick="window.print()" class="btn btn-secondary">
|
||||
<i class="fas fa-print"></i> 打印成绩单
|
||||
</button>
|
||||
<button onclick="window.history.back()" class="btn btn-primary">
|
||||
<i class="fas fa-arrow-left"></i> 返回
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
updateChart(grades) {
|
||||
const ctx = document.getElementById('gradeChart');
|
||||
if (!ctx) return;
|
||||
|
||||
if (typeof Chart === 'undefined') {
|
||||
// 如果没有Chart.js,延迟加载
|
||||
this.loadChartLibrary().then(() => this.updateChart(grades));
|
||||
return;
|
||||
}
|
||||
|
||||
const courseNames = grades.map(g => g.course_name);
|
||||
const scores = grades.map(g => g.score);
|
||||
|
||||
// 销毁现有图表实例
|
||||
if (window.gradeChart instanceof Chart) {
|
||||
window.gradeChart.destroy();
|
||||
}
|
||||
|
||||
window.gradeChart = new Chart(ctx, {
|
||||
type: 'bar',
|
||||
data: {
|
||||
labels: courseNames,
|
||||
datasets: [{
|
||||
label: '分数',
|
||||
data: scores,
|
||||
backgroundColor: scores.map(score => {
|
||||
if (score >= 90) return 'rgba(75, 192, 192, 0.7)';
|
||||
if (score >= 80) return 'rgba(54, 162, 235, 0.7)';
|
||||
if (score >= 60) return 'rgba(255, 206, 86, 0.7)';
|
||||
return 'rgba(255, 99, 132, 0.7)';
|
||||
}),
|
||||
borderColor: scores.map(score => {
|
||||
if (score >= 90) return 'rgb(75, 192, 192)';
|
||||
if (score >= 80) return 'rgb(54, 162, 235)';
|
||||
if (score >= 60) return 'rgb(255, 206, 86)';
|
||||
return 'rgb(255, 99, 132)';
|
||||
}),
|
||||
borderWidth: 1
|
||||
}]
|
||||
},
|
||||
options: {
|
||||
responsive: true,
|
||||
plugins: {
|
||||
title: {
|
||||
display: true,
|
||||
text: '各科成绩分布'
|
||||
}
|
||||
},
|
||||
scales: {
|
||||
y: {
|
||||
beginAtZero: true,
|
||||
max: 100
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async loadChartLibrary() {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (typeof Chart !== 'undefined') {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
|
||||
const script = document.createElement('script');
|
||||
script.src = 'https://cdn.jsdelivr.net/npm/chart.js';
|
||||
script.onload = resolve;
|
||||
script.onerror = reject;
|
||||
document.head.appendChild(script);
|
||||
});
|
||||
}
|
||||
|
||||
showNotification(message, type = 'info') {
|
||||
// 使用AuthManager的通知系统或自己实现
|
||||
if (window.authManager && window.authManager.showNotification) {
|
||||
window.authManager.showNotification(message, type);
|
||||
} else {
|
||||
alert(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 初始化学生管理器
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
if (window.location.pathname.includes('/student/')) {
|
||||
window.studentManager = new StudentManager();
|
||||
}
|
||||
});
|
||||
409
frontend/js/teacher.js
Normal file
409
frontend/js/teacher.js
Normal file
@@ -0,0 +1,409 @@
|
||||
class TeacherDashboard {
|
||||
constructor() {
|
||||
// 动态设置API基础URL,支持file:///协议和localhost:3000访问
|
||||
this.apiBase = window.location.protocol === 'file:' ? 'http://localhost:3000/api' : '/api';
|
||||
this.currentUser = null;
|
||||
this.courses = [];
|
||||
this.grades = [];
|
||||
this.init();
|
||||
}
|
||||
|
||||
async init() {
|
||||
// 检查登录状态
|
||||
if (!await this.checkAuth()) {
|
||||
window.location.href = '/frontend/html/login.html';
|
||||
return;
|
||||
}
|
||||
|
||||
// 加载用户信息
|
||||
await this.loadUserInfo();
|
||||
|
||||
// 加载课程数据
|
||||
await this.loadCourses();
|
||||
|
||||
// 加载成绩数据
|
||||
await this.loadGrades();
|
||||
|
||||
// 绑定事件
|
||||
this.bindEvents();
|
||||
|
||||
// 更新界面
|
||||
this.updateUI();
|
||||
}
|
||||
|
||||
async checkAuth() {
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/auth/check`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
return data.success && data.user.role === 'teacher';
|
||||
} catch (error) {
|
||||
console.error('认证检查失败:', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async loadUserInfo() {
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/auth/me`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
if (data.success) {
|
||||
this.currentUser = data.user;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('加载用户信息失败:', error);
|
||||
}
|
||||
}
|
||||
|
||||
async loadCourses() {
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/teacher/courses`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
if (data.success) {
|
||||
this.courses = data.courses;
|
||||
this.populateCourseSelectors();
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('加载课程失败:', error);
|
||||
this.showNotification('加载课程失败', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async loadGrades(filters = {}) {
|
||||
try {
|
||||
const queryParams = new URLSearchParams(filters).toString();
|
||||
const url = `${this.apiBase}/teacher/grades${queryParams ? '?' + queryParams : ''}`;
|
||||
|
||||
const response = await fetch(url, {
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
if (data.success) {
|
||||
this.grades = data.grades;
|
||||
this.renderGradesTable();
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('加载成绩失败:', error);
|
||||
this.showNotification('加载成绩失败', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
populateCourseSelectors() {
|
||||
// 填充课程选择器
|
||||
const courseSelectors = document.querySelectorAll('.course-selector');
|
||||
courseSelectors.forEach(select => {
|
||||
select.innerHTML = '<option value="">请选择课程</option>';
|
||||
this.courses.forEach(course => {
|
||||
const option = document.createElement('option');
|
||||
option.value = course.id;
|
||||
option.textContent = `${course.course_code} - ${course.course_name}`;
|
||||
select.appendChild(option);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
renderGradesTable() {
|
||||
const tableBody = document.getElementById('gradesTableBody');
|
||||
if (!tableBody) return;
|
||||
|
||||
if (this.grades.length === 0) {
|
||||
tableBody.innerHTML = `
|
||||
<tr>
|
||||
<td colspan="9" class="text-center">
|
||||
<div class="no-data">
|
||||
<i class="fas fa-info-circle"></i>
|
||||
<p>暂无成绩数据</p>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
`;
|
||||
return;
|
||||
}
|
||||
|
||||
tableBody.innerHTML = this.grades.map(grade => {
|
||||
const gradeClass = this.getGradeClass(grade.score);
|
||||
return `
|
||||
<tr>
|
||||
<td><input type="checkbox" class="grade-checkbox" data-id="${grade.id}"></td>
|
||||
<td>${grade.student_id}</td>
|
||||
<td>${grade.full_name}</td>
|
||||
<td>${grade.class_name}</td>
|
||||
<td>${grade.course_code}</td>
|
||||
<td>${grade.course_name}</td>
|
||||
<td class="grade-cell ${gradeClass}">
|
||||
<span class="grade-score">${grade.score}</span>
|
||||
<span class="grade-level">${grade.grade_level}</span>
|
||||
</td>
|
||||
<td>${grade.exam_date ? new Date(grade.exam_date).toLocaleDateString() : '未设置'}</td>
|
||||
<td>
|
||||
<div class="action-buttons">
|
||||
<button class="btn-edit" data-id="${grade.id}">
|
||||
<i class="fas fa-edit"></i> 编辑
|
||||
</button>
|
||||
<button class="btn-delete" data-id="${grade.id}">
|
||||
<i class="fas fa-trash"></i> 删除
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
`;
|
||||
}).join('');
|
||||
|
||||
// 更新统计信息
|
||||
this.updateStats();
|
||||
}
|
||||
|
||||
getGradeClass(score) {
|
||||
if (score >= 90) return 'grade-excellent';
|
||||
if (score >= 80) return 'grade-good';
|
||||
if (score >= 70) return 'grade-medium';
|
||||
if (score >= 60) return 'grade-pass';
|
||||
return 'grade-fail';
|
||||
}
|
||||
|
||||
updateStats() {
|
||||
if (this.grades.length === 0) return;
|
||||
|
||||
const totalStudents = new Set(this.grades.map(g => g.student_id)).size;
|
||||
const avgScore = this.grades.reduce((sum, g) => sum + g.score, 0) / this.grades.length;
|
||||
const passRate = (this.grades.filter(g => g.score >= 60).length / this.grades.length * 100).toFixed(1);
|
||||
|
||||
document.getElementById('totalStudents').textContent = totalStudents;
|
||||
document.getElementById('avgScore').textContent = avgScore.toFixed(1);
|
||||
document.getElementById('passRate').textContent = `${passRate}%`;
|
||||
}
|
||||
|
||||
bindEvents() {
|
||||
// 搜索按钮
|
||||
document.getElementById('searchBtn')?.addEventListener('click', () => {
|
||||
this.handleSearch();
|
||||
});
|
||||
|
||||
// 重置按钮
|
||||
document.getElementById('resetBtn')?.addEventListener('click', () => {
|
||||
this.resetFilters();
|
||||
});
|
||||
|
||||
// 导出按钮
|
||||
document.getElementById('exportBtn')?.addEventListener('click', () => {
|
||||
this.exportGrades();
|
||||
});
|
||||
|
||||
// 批量删除按钮
|
||||
document.getElementById('batchDeleteBtn')?.addEventListener('click', () => {
|
||||
this.batchDeleteGrades();
|
||||
});
|
||||
|
||||
// 表格操作按钮事件委托
|
||||
document.addEventListener('click', (e) => {
|
||||
if (e.target.closest('.btn-edit')) {
|
||||
const gradeId = e.target.closest('.btn-edit').dataset.id;
|
||||
this.editGrade(gradeId);
|
||||
}
|
||||
|
||||
if (e.target.closest('.btn-delete')) {
|
||||
const gradeId = e.target.closest('.btn-delete').dataset.id;
|
||||
this.deleteGrade(gradeId);
|
||||
}
|
||||
});
|
||||
|
||||
// 退出登录
|
||||
document.getElementById('logoutBtn')?.addEventListener('click', () => {
|
||||
this.handleLogout();
|
||||
});
|
||||
}
|
||||
|
||||
handleSearch() {
|
||||
const className = document.getElementById('classFilter')?.value || '';
|
||||
const courseId = document.getElementById('courseFilter')?.value || '';
|
||||
|
||||
this.loadGrades({ class_name: className, course_id: courseId });
|
||||
}
|
||||
|
||||
resetFilters() {
|
||||
document.getElementById('classFilter').value = '';
|
||||
document.getElementById('courseFilter').value = '';
|
||||
this.loadGrades();
|
||||
}
|
||||
|
||||
async exportGrades() {
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/teacher/grades/export`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const blob = await response.blob();
|
||||
const url = window.URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `成绩报表_${new Date().toISOString().split('T')[0]}.xlsx`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
window.URL.revokeObjectURL(url);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('导出失败:', error);
|
||||
this.showNotification('导出失败', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async batchDeleteGrades() {
|
||||
const checkboxes = document.querySelectorAll('.grade-checkbox:checked');
|
||||
if (checkboxes.length === 0) {
|
||||
this.showNotification('请选择要删除的成绩', 'warning');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!confirm(`确定要删除选中的 ${checkboxes.length} 条成绩记录吗?`)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const gradeIds = Array.from(checkboxes).map(cb => cb.dataset.id);
|
||||
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/teacher/grades/batch`, {
|
||||
method: 'DELETE',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
credentials: 'include',
|
||||
body: JSON.stringify({ gradeIds })
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
if (data.success) {
|
||||
this.showNotification(`成功删除 ${gradeIds.length} 条成绩记录`, 'success');
|
||||
await this.loadGrades();
|
||||
} else {
|
||||
this.showNotification(data.message || '删除失败', 'error');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('批量删除失败:', error);
|
||||
this.showNotification('批量删除失败', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async editGrade(gradeId) {
|
||||
const grade = this.grades.find(g => g.id == gradeId);
|
||||
if (!grade) return;
|
||||
|
||||
// 这里可以打开编辑模态框
|
||||
// 暂时使用简单提示框
|
||||
const newScore = prompt('请输入新的分数:', grade.score);
|
||||
if (newScore === null) return;
|
||||
|
||||
const numericScore = parseFloat(newScore);
|
||||
if (isNaN(numericScore) || numericScore < 0 || numericScore > 100) {
|
||||
this.showNotification('请输入0-100之间的有效分数', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/teacher/grades/${gradeId}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
credentials: 'include',
|
||||
body: JSON.stringify({
|
||||
score: numericScore,
|
||||
examDate: grade.exam_date,
|
||||
remark: grade.remark
|
||||
})
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
if (data.success) {
|
||||
this.showNotification('成绩更新成功', 'success');
|
||||
await this.loadGrades();
|
||||
} else {
|
||||
this.showNotification(data.message || '更新失败', 'error');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('更新成绩失败:', error);
|
||||
this.showNotification('更新成绩失败', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async deleteGrade(gradeId) {
|
||||
if (!confirm('确定要删除这条成绩记录吗?')) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/teacher/grades/${gradeId}`, {
|
||||
method: 'DELETE',
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
if (data.success) {
|
||||
this.showNotification('成绩删除成功', 'success');
|
||||
await this.loadGrades();
|
||||
} else {
|
||||
this.showNotification(data.message || '删除失败', 'error');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('删除成绩失败:', error);
|
||||
this.showNotification('删除成绩失败', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async handleLogout() {
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/auth/logout`, {
|
||||
method: 'POST',
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
window.location.href = '/frontend/html/login.html';
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('退出登录失败:', error);
|
||||
}
|
||||
}
|
||||
|
||||
updateUI() {
|
||||
// 更新用户信息
|
||||
if (this.currentUser) {
|
||||
const userInfoElements = document.querySelectorAll('.user-info');
|
||||
userInfoElements.forEach(el => {
|
||||
el.textContent = `${this.currentUser.full_name} (${this.currentUser.role})`;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
showNotification(message, type = 'info') {
|
||||
// 使用AuthManager的通知系统或简单alert
|
||||
if (typeof AuthManager !== 'undefined' && AuthManager.showNotification) {
|
||||
AuthManager.showNotification(message, type);
|
||||
} else {
|
||||
alert(`${type}: ${message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 页面加载完成后初始化
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
if (window.location.pathname.includes('/teacher/')) {
|
||||
new TeacherDashboard();
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user