ERP/frontend/js/app.js

103 lines
3.3 KiB
JavaScript
Raw Normal View History

(() => {
// 应用保存的主题
const savedTheme = localStorage.getItem('theme') || 'light';
document.documentElement.setAttribute('data-theme', savedTheme);
let currentUser = null;
// 更新用户显示
function updateUserDisplay(user) {
const userNameDisplay = document.getElementById('user-name-display');
const userCard = document.getElementById('user-card');
const username = (user && user.username) ? user.username : '未登录';
if (userNameDisplay) userNameDisplay.textContent = username;
if (userCard) userCard.textContent = username;
// 加载用户头像(如果有设置)
const avatarImg = document.getElementById('user-avatar-img');
if (avatarImg && user && user.avatar) {
avatarImg.src = user.avatar;
} else if (avatarImg) {
avatarImg.src = './assets/user-avatar.svg';
}
}
Router.onBeforeEach(async (path) => {
document.getElementById('overlay').classList.remove('hidden');
try {
currentUser = await API.me().catch(() => null);
const publicRoutes = ['/login'];
if ((!currentUser || !currentUser.username) && !publicRoutes.includes(path)) {
location.hash = '#/login';
}
} catch(e) {}
});
Router.onAfterEach(async (path) => {
document.getElementById('overlay').classList.add('hidden');
updateUserDisplay(currentUser);
// 初始化通知系统(仅对超级管理员)
if (currentUser && currentUser.role === 'superadmin' && window.NotificationSystem) {
window.NotificationSystem.init();
}
});
Router.init();
API.me().then(user => {
currentUser = user;
updateUserDisplay(user);
// 初始化通知系统(仅对超级管理员)
if (user && user.role === 'superadmin' && window.NotificationSystem) {
window.NotificationSystem.init();
}
}).catch(()=>{});
// 用户头像按钮点击事件 - 显示/隐藏下拉菜单
const userAvatarBtn = document.getElementById('user-avatar-btn');
const userDropdown = document.getElementById('user-dropdown');
userAvatarBtn?.addEventListener('click', (e) => {
e.stopPropagation();
const isVisible = userDropdown.style.display !== 'none';
userDropdown.style.display = isVisible ? 'none' : 'block';
});
// 点击页面其他地方关闭下拉菜单
document.addEventListener('click', (e) => {
if (userDropdown && !userDropdown.contains(e.target) && e.target !== userAvatarBtn) {
userDropdown.style.display = 'none';
}
});
// 退出登录
const logoutBtn = document.getElementById('user-dropdown-logout');
logoutBtn?.addEventListener('click', () => {
// 清理通知系统
if (window.NotificationSystem) {
window.NotificationSystem.cleanup();
}
API.logout()
.then(() => {
currentUser = null;
updateUserDisplay(null);
userDropdown.style.display = 'none';
location.hash = '#/login';
})
.catch(() => {});
});
// 菜单切换
const toggleBtn = document.getElementById('menu-toggle');
const sidebar = document.querySelector('.sidebar');
toggleBtn?.addEventListener('click', () => {
sidebar.classList.toggle('open');
});
// 暴露更新用户显示的函数,供设置页面使用
window.updateUserDisplay = updateUserDisplay;
})();