// API基础URL const API_BASE_URL = 'http://localhost:8001'; // 全局状态 let currentUser = null; let accessToken = localStorage.getItem('accessToken'); let lastApiCalls = {}; // 记录上次API调用时间,防止重复请求 // DOM元素 const navMenu = document.getElementById('navMenu'); const userInfo = document.getElementById('userInfo'); const loginBtn = document.getElementById('loginBtn'); const registerBtn = document.getElementById('registerBtn'); const logoutBtn = document.getElementById('logoutBtn'); const loginSection = document.getElementById('loginSection'); const registerSection = document.getElementById('registerSection'); const mainSection = document.getElementById('mainSection'); const loginForm = document.getElementById('loginForm'); const registerForm = document.getElementById('registerForm'); const editProfileForm = document.getElementById('editProfileForm'); const createDocForm = document.getElementById('createDocForm'); const editDocForm = document.getElementById('editDocForm'); const currentUserName = document.getElementById('currentUserName'); const editProfileBtn = document.getElementById('editProfileBtn'); const viewLogsBtn = document.getElementById('viewLogsBtn'); const createDocBtn = document.getElementById('createDocBtn'); const documentsList = document.getElementById('documentsList'); const logsList = document.getElementById('logsList'); const message = document.getElementById('message'); // 模态框相关元素 const editProfileModal = document.getElementById('editProfileModal'); const createDocModal = document.getElementById('createDocModal'); const editDocModal = document.getElementById('editDocModal'); const logsModal = document.getElementById('logsModal'); // 用户管理相关元素 const userManagementSection = document.getElementById('userManagementSection'); const usersList = document.getElementById('usersList'); const refreshUsersBtn = document.getElementById('refreshUsersBtn'); // API请求函数 async function apiRequest(url, options = {}) { const config = { headers: { 'Content-Type': 'application/json', ...options.headers }, ...options }; if (accessToken) { config.headers['Authorization'] = `Bearer ${accessToken}`; } try { const response = await fetch(`${API_BASE_URL}${url}`, config); if (response.status === 401) { // Token过期,清除本地存储并重新登录 accessToken = null; localStorage.removeItem('accessToken'); currentUser = null; showLoginSection(); showMessage('登录已过期,请重新登录', 'error'); return null; } if (!response.ok) { const errorData = await response.json().catch(() => ({})); throw new Error(errorData.detail || `HTTP error! status: ${response.status}`); } const result = await response.json(); return result; } catch (error) { console.error('API请求错误:', error); showMessage(`请求失败: ${error.message}`, 'error'); return null; } } // 显示消息提示 function showMessage(text, type = 'info') { message.textContent = text; message.className = `message ${type}`; message.style.display = 'block'; setTimeout(() => { message.style.display = 'none'; }, 3000); } // 用户认证相关函数 async function login(username, password) { const data = await apiRequest('/auth/login', { method: 'POST', body: JSON.stringify({ username, password }) }); if (data && data.access_token) { accessToken = data.access_token; localStorage.setItem('accessToken', accessToken); await loadCurrentUser(); showMainSection(); showMessage('登录成功', 'success'); return true; } return false; } async function register(userData) { // 将isAdmin添加到userData中 const registrationData = { ...userData, is_admin: document.getElementById('registerIsAdmin') ? document.getElementById('registerIsAdmin').checked : false }; const data = await apiRequest('/auth/register', { method: 'POST', body: JSON.stringify(registrationData) }); if (data) { showMessage('注册成功,请登录', 'success'); // 重置勾选框 if(document.getElementById('registerIsAdmin')) { document.getElementById('registerIsAdmin').checked = false; } showLoginSection(); return true; } return false; } async function logout() { await apiRequest('/auth/logout', { method: 'POST' }); accessToken = null; localStorage.removeItem('accessToken'); currentUser = null; showLoginSection(); showMessage('已退出登录', 'info'); } async function loadCurrentUser() { const data = await apiRequest('/users/me'); if (data) { currentUser = data; userInfo.textContent = `欢迎, ${data.username}`; currentUserName.textContent = data.username; return true; } return false; } async function updateUserProfile(updateData) { const data = await apiRequest('/users/me', { method: 'PUT', body: JSON.stringify(updateData) }); if (data) { await loadCurrentUser(); showMessage('个人信息更新成功', 'success'); return true; } return false; } // 文档管理相关函数 async function loadDocuments() { const data = await apiRequest('/documents'); if (data) { displayDocuments(data); return true; } return false; } async function createDocument(docData) { const data = await apiRequest('/documents', { method: 'POST', body: JSON.stringify(docData) }); if (data) { await loadDocuments(); showMessage('文档创建成功', 'success'); return true; } return false; } async function updateDocument(docId, docData) { const data = await apiRequest(`/documents/${docId}`, { method: 'PUT', body: JSON.stringify(docData) }); if (data) { await loadDocuments(); showMessage('文档更新成功', 'success'); return true; } return false; } async function deleteDocument(docId) { const data = await apiRequest(`/documents/${docId}`, { method: 'DELETE' }); if (data) { await loadDocuments(); showMessage('文档删除成功', 'success'); return true; } return false; } // 操作日志相关函数 async function loadLogs() { const data = await apiRequest('/logs/my'); if (data) { displayLogs(data); return true; } return false; } // 用户管理相关函数 async function loadUsers() { const data = await apiRequest('/users'); if (data) { displayUsers(data); return true; } return false; } async function deleteUser(userId) { if (confirm('确定要删除这个用户吗?此操作不可恢复。')) { const data = await apiRequest(`/users/${userId}`, { method: 'DELETE' }); if (data) { await loadUsers(); showMessage('用户删除成功', 'success'); return true; } } return false; } // 界面显示控制函数 function showLoginSection() { loginSection.style.display = 'block'; registerSection.style.display = 'none'; mainSection.style.display = 'none'; loginBtn.style.display = 'inline-block'; registerBtn.style.display = 'inline-block'; logoutBtn.style.display = 'none'; userInfo.style.display = 'none'; } function showRegisterSection() { loginSection.style.display = 'none'; registerSection.style.display = 'block'; mainSection.style.display = 'none'; } function showMainSection() { loginSection.style.display = 'none'; registerSection.style.display = 'none'; mainSection.style.display = 'block'; loginBtn.style.display = 'none'; registerBtn.style.display = 'none'; logoutBtn.style.display = 'inline-block'; userInfo.style.display = 'inline-block'; // 检查是否为管理员,如果是则显示用户管理界面 if (currentUser && currentUser.is_admin) { userManagementSection.style.display = 'block'; loadUsers(); } else { userManagementSection.style.display = 'none'; } loadDocuments(); } // 显示/隐藏模态框函数 function showModal(modal) { modal.style.display = 'flex'; } function hideModal(modal) { modal.style.display = 'none'; } // 文档显示函数 function displayDocuments(documents) { if (documents.length === 0) { documentsList.innerHTML = `
点击"创建新文档"按钮开始创建您的第一个文档