// ============================================================
// 🛡️ 管理后台
// ============================================================
function renderAdminReports() {
const container = document.getElementById('adminContent');
container.innerHTML = '
加载中...
';
API.getReports().then(reports => {
if (!reports || reports.length === 0) {
container.innerHTML = '✅ 暂无举报
';
return;
}
let html = '';
const statusMap = { pending: '⏳ 待处理', approved: '✅ 已删除', rejected: '❌ 已驳回' };
reports.forEach(r => {
const postTitle = r.post_title || '无标题';
html += `
${r.reporter_name || '匿名'} 举报了帖子
原因:${r.reason}
帖子:${postTitle} — ${(r.post_content || '').substring(0, 30)}${(r.post_content || '').length > 30 ? '...' : ''}
状态:${statusMap[r.status] || r.status}
${r.handler_name ? `
处理人:${r.handler_name}${r.handler_note ? ' (' + r.handler_note + ')' : ''}
` : ''}
${r.status === 'pending' ? `
` : ''}
`;
});
container.innerHTML = html;
container.querySelectorAll('[data-action]').forEach(btn => {
btn.addEventListener('click', function() {
const id = this.dataset.reportid;
const action = this.dataset.action;
const status = action === 'approve' ? 'approved' : 'rejected';
const note = action === 'approve' ? '已删除违规帖子' : '举报不成立';
if (action === 'approve' && !confirm('确定要删除该帖子并标记举报为已处理吗?')) return;
API.updateReport(id, status, note).then(() => {
if (action === 'approve') {
const report = reports.find(r => r.id === id);
if (report && report.post_id) {
API.deletePost(report.post_id).catch(() => {});
}
}
renderAdminReports();
}).catch(err => alert('操作失败:' + err.message));
});
});
}).catch(() => {
container.innerHTML = '加载失败
';
});
}
// ============================================================
// 👥 用户列表(支持分页 + 搜索)
// ============================================================
let currentUsersPage = 1;
let usersTotalPages = 1;
let usersSearchKeyword = '';
function renderAdminUsers(page = 1, search = '') {
const container = document.getElementById('adminContent');
container.innerHTML = '加载中...
';
currentUsersPage = page;
usersSearchKeyword = search;
API.getUsers(page, 20, search).then(result => {
const users = result.data || [];
const pagination = result.pagination || { total: 0, totalPages: 1, page: 1 };
usersTotalPages = pagination.totalPages || 1;
let html = `
| 用户 |
角色 |
注册时间 |
操作 |
`;
if (users.length === 0) {
html += `| 暂无用户 |
`;
} else {
users.forEach(u => {
const isAdmin = u.role === 'admin';
const isCurrentUser = currentUser && currentUser.id === u.id;
html += `
${u.username}
${isCurrentUser ? ' 你' : ''}
|
${isAdmin ? '管理员' : '普通用户'}
|
${u.created_at ? new Date(u.created_at).toLocaleDateString('zh-CN') : '—'} |
${isCurrentUser ?
'不可操作自己' :
(isAdmin ?
`` :
``
)
}
|
`;
});
}
html += '
';
// 分页控件
if (usersTotalPages > 1) {
html += `
`;
let startPage = Math.max(1, page - 4);
let endPage = Math.min(usersTotalPages, page + 4);
if (page <= 4) endPage = Math.min(usersTotalPages, 9);
if (page > usersTotalPages - 4) startPage = Math.max(1, usersTotalPages - 8);
if (startPage > 1) {
html += ``;
if (startPage > 2) html += `…`;
}
for (let i = startPage; i <= endPage; i++) {
const isActive = i === page;
html += `
`;
}
if (endPage < usersTotalPages) {
if (endPage < usersTotalPages - 1) html += `…`;
html += ``;
}
html += `
${pagination.total} 位用户
`;
}
container.innerHTML = html;
// 绑定分页按钮事件
container.querySelectorAll('.users-page-btn:not([disabled])').forEach(btn => {
btn.addEventListener('click', function() {
const newPage = parseInt(this.dataset.page);
if (newPage >= 1 && newPage <= usersTotalPages) {
renderAdminUsers(newPage, usersSearchKeyword);
}
});
});
// 绑定角色切换事件
container.querySelectorAll('[data-role]').forEach(btn => {
btn.addEventListener('click', function() {
const userId = this.dataset.userid;
const role = this.dataset.role;
const roleName = role === 'admin' ? '管理员' : '普通用户';
if (!confirm(`确定要将该用户设为「${roleName}」吗?`)) return;
API.updateUserRole(userId, role).then(() => {
renderAdminUsers(currentUsersPage, usersSearchKeyword);
}).catch(err => alert('操作失败:' + err.message));
});
});
// 搜索按钮
const searchBtn = document.getElementById('userSearchBtn');
if (searchBtn) {
searchBtn.addEventListener('click', function() {
const input = document.getElementById('userSearchInput');
renderAdminUsers(1, input.value.trim());
});
}
// 清空搜索
const clearBtn = document.getElementById('userClearSearchBtn');
if (clearBtn) {
clearBtn.addEventListener('click', function() {
const input = document.getElementById('userSearchInput');
input.value = '';
renderAdminUsers(1, '');
});
}
// 回车搜索
const searchInput = document.getElementById('userSearchInput');
if (searchInput) {
searchInput.addEventListener('keydown', function(e) {
if (e.key === 'Enter') {
renderAdminUsers(1, this.value.trim());
}
});
}
}).catch(() => {
container.innerHTML = '加载失败
';
});
}
// ============================================================
// 📜 操作日志(支持分页)
// ============================================================
function renderAdminLogs(page = 1) {
const container = document.getElementById('adminContent');
container.innerHTML = '加载中...
';
API.getEventLogs(page, 20).then(result => {
const logs = result.data || [];
const pagination = result.pagination || { total: 0, totalPages: 1, page: 1 };
const totalPages = pagination.totalPages || 1;
if (!logs || logs.length === 0) {
container.innerHTML = '暂无日志
';
return;
}
let html = `
| 时间 |
用户 |
操作 |
`;
logs.forEach(l => {
html += `
| ${new Date(l.created_at).toLocaleString('zh-CN')} |
${l.username || '系统'} |
${l.action} |
`;
});
html += '
';
// 分页控件
if (totalPages > 1) {
html += `
`;
let startPage = Math.max(1, page - 4);
let endPage = Math.min(totalPages, page + 4);
if (page <= 4) endPage = Math.min(totalPages, 9);
if (page > totalPages - 4) startPage = Math.max(1, totalPages - 8);
if (startPage > 1) {
html += ``;
if (startPage > 2) html += `…`;
}
for (let i = startPage; i <= endPage; i++) {
const isActive = i === page;
html += `
`;
}
if (endPage < totalPages) {
if (endPage < totalPages - 1) html += `…`;
html += ``;
}
html += `
${pagination.total} 条日志
`;
}
container.innerHTML = html;
// 绑定分页按钮事件
container.querySelectorAll('.logs-page-btn:not([disabled])').forEach(btn => {
btn.addEventListener('click', function() {
const newPage = parseInt(this.dataset.page);
if (newPage >= 1 && newPage <= totalPages) {
renderAdminLogs(newPage);
}
});
});
}).catch(() => {
container.innerHTML = '加载失败
';
});
}
// ============================================================
// 🔗 友情链接管理
// ============================================================
function renderAdminLinks() {
const container = document.getElementById('adminContent');
container.innerHTML = `
`;
function loadLinks() {
API.getLinks().then(links => {
const ul = document.getElementById('linkList');
if (!links || links.length === 0) {
ul.innerHTML = '暂无友情链接
';
return;
}
let html = '';
links.forEach(l => {
html += `
`;
});
ul.innerHTML = html;
ul.querySelectorAll('[data-linkid]').forEach(btn => {
btn.addEventListener('click', function() {
if (!confirm('确定删除该链接吗?')) return;
API.deleteLink(this.dataset.linkid).then(() => {
loadLinks();
}).catch(err => alert('删除失败:' + err.message));
});
});
}).catch(() => {});
}
loadLinks();
document.getElementById('addLinkBtn').addEventListener('click', function() {
const title = document.getElementById('newLinkTitle').value.trim();
const url = document.getElementById('newLinkUrl').value.trim();
if (!title || !url) { alert('请填写完整信息'); return; }
API.addLink(title, url).then(() => {
document.getElementById('newLinkTitle').value = '';
document.getElementById('newLinkUrl').value = '';
loadLinks();
}).catch(err => alert('添加失败:' + err.message));
});
}
// ============================================================
// ⚙️ 论坛设置(只改名称)
// ============================================================
function renderAdminSettings() {
const container = document.getElementById('adminContent');
container.innerHTML = `
⚙️ 论坛名称
`;
API.getSettings().then(data => {
document.getElementById('settingsForumName').value = data.forum_name || 'Forumlify';
}).catch(() => {});
document.getElementById('settingsForumSave').addEventListener('click', async () => {
const name = document.getElementById('settingsForumName').value.trim();
if (!name) { alert('请输入论坛名称'); return; }
try {
await API.updateSettings(name);
document.getElementById('settingsResult').textContent = '✅ 保存成功!';
document.getElementById('settingsResult').style.color = '#22c55e';
document.getElementById('forumName').textContent = name;
document.title = name;
const titleEl = document.getElementById('pageTitle');
if (titleEl) titleEl.textContent = name;
} catch (err) {
document.getElementById('settingsResult').textContent = '❌ 保存失败';
document.getElementById('settingsResult').style.color = '#ef4444';
}
});
}
// ============================================================
// 🎨 自定义 CSS(独立标签页)
// ============================================================
function renderAdminCustomCSS() {
const container = document.getElementById('adminContent');
container.innerHTML = `
🎨 自定义 CSS
上传 style.css 覆盖默认样式,自定义论坛外观。
`;
// 自定义 CSS 上传逻辑
const dropZone = document.getElementById('customCssDropZone');
const fileInput = document.getElementById('customCssInput');
const dropText = document.getElementById('customCssDropText');
const statusEl = document.getElementById('customCssStatus');
let selectedFile = null;
if (dropZone && fileInput) {
dropZone.addEventListener('click', function() {
fileInput.click();
});
fileInput.addEventListener('change', function() {
if (this.files.length > 0) {
handleCssFile(this.files[0]);
}
});
dropZone.addEventListener('dragover', function(e) {
e.preventDefault();
this.style.borderColor = 'var(--primary)';
this.style.background = 'var(--primary-bg)';
dropText.textContent = '松开上传';
});
dropZone.addEventListener('dragleave', function(e) {
e.preventDefault();
this.style.borderColor = 'var(--border)';
this.style.background = 'var(--bg)';
dropText.textContent = '点击或拖拽上传 style.css';
});
dropZone.addEventListener('drop', function(e) {
e.preventDefault();
this.style.borderColor = 'var(--border)';
this.style.background = 'var(--bg)';
dropText.textContent = '点击或拖拽上传 style.css';
if (e.dataTransfer.files.length > 0) {
handleCssFile(e.dataTransfer.files[0]);
}
});
}
function handleCssFile(file) {
if (file.name !== 'style.css') {
statusEl.textContent = '❌ 文件名必须是 style.css';
statusEl.style.color = '#ef4444';
selectedFile = null;
fileInput.value = '';
return;
}
if (!file.type.includes('text/css') && !file.name.endsWith('.css')) {
statusEl.textContent = '❌ 请上传 CSS 文件';
statusEl.style.color = '#ef4444';
selectedFile = null;
fileInput.value = '';
return;
}
selectedFile = file;
statusEl.textContent = '✅ 已选择: ' + file.name + ' (' + (file.size / 1024).toFixed(1) + ' KB)';
statusEl.style.color = '#22c55e';
}
document.getElementById('customCssSaveBtn').addEventListener('click', function() {
if (!selectedFile) {
statusEl.textContent = '⚠️ 请先选择 style.css 文件';
statusEl.style.color = '#f59e0b';
return;
}
showCustomCssWarningModal(async function() {
try {
await API.uploadCustomCSS(selectedFile);
statusEl.textContent = '✅ CSS 上传成功!刷新页面查看效果';
statusEl.style.color = '#22c55e';
selectedFile = null;
fileInput.value = '';
dropText.textContent = '点击或拖拽上传 style.css';
loadCustomCSS();
} catch (err) {
statusEl.textContent = '❌ 上传失败:' + err.message;
statusEl.style.color = '#ef4444';
}
});
});
document.getElementById('customCssDeleteBtn').addEventListener('click', async function() {
if (!confirm('确定要删除自定义 CSS 吗?将恢复默认样式。')) return;
try {
await API.deleteCustomCSS();
statusEl.textContent = '✅ 已删除自定义 CSS';
statusEl.style.color = '#22c55e';
const link = document.getElementById('customCssLink');
if (link) link.remove();
} catch (err) {
statusEl.textContent = '❌ 删除失败:' + err.message;
statusEl.style.color = '#ef4444';
}
});
}
// ============================================================
// 📄 自定义页面管理
// ============================================================
let editingPageId = null;
function renderAdminCustomPages() {
const container = document.getElementById('adminContent');
container.innerHTML = `
📄 自定义页面
`;
loadCustomPageList();
document.getElementById('addCustomPageBtn').addEventListener('click', function() {
editingPageId = null;
openCustomPageEditor();
});
}
function loadCustomPageList() {
const container = document.getElementById('customPageList');
container.innerHTML = '加载中...
';
API.getAdminCustomPages().then(pages => {
if (pages.length === 0) {
container.innerHTML = '暂无自定义页面
';
return;
}
let html = `
| 名称 |
标题 |
URL |
状态 |
操作 |
`;
pages.forEach(p => {
html += `
${p.name} |
${p.title} |
?custom=${p.name} |
${p.enabled ? '✅ 启用' : '❌ 禁用'} |
|
`;
});
html += '
';
container.innerHTML = html;
container.querySelectorAll('[data-action="edit"]').forEach(btn => {
btn.addEventListener('click', function() {
const page = pages.find(p => p.id === this.dataset.id);
if (page) {
editingPageId = page.id;
openCustomPageEditor(page);
}
});
});
container.querySelectorAll('[data-action="delete"]').forEach(btn => {
btn.addEventListener('click', function() {
if (!confirm('确定要删除这个页面吗?')) return;
API.deleteCustomPage(this.dataset.id).then(() => {
loadCustomPageList();
loadCustomPagesNav();
}).catch(err => alert('删除失败:' + err.message));
});
});
}).catch(err => {
container.innerHTML = '加载失败
';
});
}
function openCustomPageEditor(page) {
const isEdit = !!page;
const modal = document.createElement('div');
modal.className = 'modal active';
modal.style.display = 'flex';
modal.innerHTML = `
×
${isEdit ? '✏️ 编辑页面' : '📄 添加页面'}
${isEdit ? '
⚠️ 名称不可修改
' : '
只允许字母、数字、短横线和下划线
'}
支持 HTML、CSS(<style>)、JS(<script>),内容会在独立的沙盒中渲染
`;
document.body.appendChild(modal);
modal.querySelector('.close').addEventListener('click', function() {
modal.remove();
});
modal.addEventListener('click', function(e) {
if (e.target === this) modal.remove();
});
modal.querySelector('#editorSaveBtn').addEventListener('click', async function() {
const name = document.getElementById('editorPageName').value.trim();
const title = document.getElementById('editorPageTitle').value.trim();
const content = document.getElementById('editorContent').value.trim();
const enabled = document.getElementById('editorEnabled').value === 'true';
if (!name) { alert('请输入页面名称'); return; }
if (!title) { alert('请输入导航栏显示名称'); return; }
if (!content) { alert('请输入页面内容'); return; }
if (!/^[a-zA-Z0-9\-_]+$/.test(name)) {
alert('页面名称只允许字母、数字、短横线和下划线');
return;
}
try {
if (isEdit) {
await API.updateCustomPage(page.id, title, content, enabled);
} else {
await API.createCustomPage(name, title, content);
}
modal.remove();
loadCustomPageList();
loadCustomPagesNav();
} catch (err) {
alert('保存失败:' + err.message);
}
});
}
// ============================================================
// 自定义 CSS 警告模态框
// ============================================================
function showCustomCssWarningModal(onConfirm) {
const modal = document.createElement('div');
modal.className = 'modal active';
modal.style.display = 'flex';
modal.innerHTML = `
⚠️ 警告
若上传的 style.css 存在问题,将导致整个论坛界面样式错乱,甚至无法正常使用。
请确保 CSS 文件是完整的、经过测试的版本。如出现问题,可点击「删除自定义 CSS」恢复默认样式。
`;
document.body.appendChild(modal);
modal.querySelector('#cssWarningConfirm').addEventListener('click', function() {
modal.remove();
if (onConfirm) onConfirm();
});
modal.querySelector('#cssWarningCancel').addEventListener('click', function() {
modal.remove();
});
modal.addEventListener('click', function(e) {
if (e.target === this) modal.remove();
});
}
// ============================================================
// 加载自定义 CSS
// ============================================================
function loadCustomCSS() {
const existing = document.getElementById('customCssLink');
if (existing) existing.remove();
const link = document.createElement('link');
link.id = 'customCssLink';
link.rel = 'stylesheet';
link.href = CONFIG.API_BASE_URL + '/custom-css?v=' + Date.now();
link.onerror = function() {
// 如果自定义 CSS 不存在,静默失败
};
document.head.appendChild(link);
}
// ============================================================
// 管理后台Tab切换(侧边栏适配)
// ============================================================
// 使用事件委托监听 .admin-nav 下的点击
document.querySelector('.admin-nav')?.addEventListener('click', function(e) {
const tabLink = e.target.closest('.admin-nav-item');
if (!tabLink) return;
e.preventDefault();
const tab = tabLink.dataset.tab;
if (!tab) return;
// 切换高亮
document.querySelectorAll('.admin-nav-item').forEach(el => el.classList.remove('active'));
tabLink.classList.add('active');
// 渲染对应内容
const tabMap = {
reports: renderAdminReports,
users: renderAdminUsers,
logs: renderAdminLogs,
links: renderAdminLinks,
'custom-css': renderAdminCustomCSS,
settings: renderAdminSettings,
custom: renderAdminCustomPages
};
if (tabMap[tab]) tabMap[tab]();
});
// 页面加载时尝试加载自定义 CSS
document.addEventListener('DOMContentLoaded', function() {
setTimeout(loadCustomCSS, 500);
});