// ============================================================
// 🛡️ 管理后台
// ============================================================
function renderAdminReports() {
const container = document.getElementById('adminContent');
container.innerHTML = '
加载中...
';
API.getReports().then(reports => {
if (!reports || reports.length === 0) {
container.innerHTML = `${getIcon('success')} 暂无举报
`;
return;
}
let html = '';
const statusMap = {
pending: `${getIcon('pending')} 待处理`,
approved: `${getIcon('success')} 已删除`,
rejected: `${getIcon('error')} 已驳回`
};
reports.forEach(r => {
const postTitle = r.post_title || '无标题';
html += `
${escapeHTML(r.reporter_name || '匿名')} 举报了帖子
原因:${escapeHTML(r.reason)}
帖子:${escapeHTML(postTitle)} — ${escapeHTML((r.post_content || '').substring(0, 30))}${(r.post_content || '').length > 30 ? '...' : ''}
状态:${statusMap[r.status] || escapeHTML(r.status)}
${r.handler_name ? `
处理人:${escapeHTML(r.handler_name)}${r.handler_note ? ' (' + escapeHTML(r.handler_note) + ')' : ''}
` : ''}
${r.status === 'pending' ? `
` : ''}
`;
});
container.innerHTML = sanitizeHTML(html);
container.querySelectorAll('[data-action]').forEach(btn => {
btn.addEventListener('click', async function() {
const id = this.dataset.reportid;
const action = this.dataset.action;
const status = action === 'approve' ? 'approved' : 'rejected';
const note = action === 'approve' ? '已删除违规帖子' : '举报不成立';
if (action === 'approve') {
const ok = await showConfirm('确定要删除该帖子并标记举报为已处理吗?', {
title: '删除帖子', confirmText: '删除', danger: true,
});
if (!ok) return;
}
API.updateReport(id, status, note).then(() => {
renderAdminReports();
}).catch(err => showToast('操作失败:' + err.message, 'error'));
});
});
}).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 += `
${escapeHTML(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 = sanitizeHTML(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', async function() {
const userId = this.dataset.userid;
const role = this.dataset.role;
const roleName = role === 'admin' ? '管理员' : '普通用户';
const ok = await showConfirm(`确定要将该用户设为「${roleName}」吗?`, {
title: '修改用户角色',
confirmText: '确定',
danger: role === 'admin',
});
if (!ok) return;
API.updateUserRole(userId, role).then(() => {
renderAdminUsers(currentUsersPage, usersSearchKeyword);
}).catch(err => showToast('操作失败:' + err.message, 'error'));
});
});
// 搜索按钮
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')} |
${escapeHTML(l.username || '系统')} |
${escapeHTML(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 = sanitizeHTML(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 = sanitizeHTML(html);
ul.querySelectorAll('[data-linkid]').forEach(btn => {
btn.addEventListener('click', async function() {
const ok = await showConfirm('确定删除该链接吗?', {
title: '删除友链', confirmText: '删除', danger: true,
});
if (!ok) return;
API.deleteLink(this.dataset.linkid).then(() => {
loadLinks();
}).catch(err => showToast('删除失败:' + err.message, 'error'));
});
});
}).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) { showToast('请填写完整信息', 'warning'); return; }
API.addLink(title, url).then(() => {
document.getElementById('newLinkTitle').value = '';
document.getElementById('newLinkUrl').value = '';
loadLinks();
}).catch(err => showToast('添加失败:' + err.message, 'error'));
});
}
// ============================================================
// ⚙️ 论坛设置(只改名称)
// ============================================================
function renderAdminSettings() {
const container = document.getElementById('adminContent');
container.innerHTML = `
${getIcon('settings')} 论坛名称
`;
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) { showToast('请输入论坛名称', 'warning'); return; }
try {
await API.updateSettings(name);
document.getElementById('settingsResult').innerHTML = `${getIcon('success')} 保存成功!`;
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').innerHTML = `${getIcon('error')} 保存失败`;
document.getElementById('settingsResult').style.color = '#ef4444';
}
});
}
// ============================================================
// 📧 邮件设置(SMTP)
// ============================================================
function renderAdminSmtp() {
const container = document.getElementById('adminContent');
container.innerHTML = `
${getIcon('message')} 邮件设置
配置后可用于注册邮箱验证与密码找回。密码只写不读,保存后不会回显。
`;
const $ = id => document.getElementById(id);
// 载入现有配置
API.getSmtpConfig().then(cfg => {
$('smtpEnabled').checked = cfg.enabled;
$('smtpHost').value = cfg.host || '';
$('smtpPort').value = cfg.port || 587;
$('smtpSecure').value = String(cfg.secure);
$('smtpUser').value = cfg.user || '';
$('smtpFromName').value = cfg.from_name || '';
$('smtpFromEmail').value = cfg.from_email || '';
// 密码永不回显,只用占位文字提示是否已设置
$('smtpPassword').placeholder = cfg.password_set
? '已保存密码,留空则不修改'
: '尚未设置密码';
const status = $('smtpStatus');
if (cfg.configured) {
status.innerHTML = `${getIcon('success')} 配置完整,可以发信`;
status.style.background = 'rgba(34,197,94,0.12)';
status.style.color = '#16a34a';
} else {
status.innerHTML = `${getIcon('warning')} 尚未配置完成,邮件功能不可用`;
status.style.background = 'rgba(245,158,11,0.12)';
status.style.color = '#d97706';
}
}).catch(err => {
showToast('加载配置失败:' + err.message, 'error');
});
// 读取邮箱验证开关(该值在公开设置接口中)
API.getSettings().then(s => {
$('emailVerifyRequired').checked = s.email_verify_required === true;
}).catch(() => {});
$('smtpSaveBtn').addEventListener('click', async () => {
const payload = {
enabled: $('smtpEnabled').checked,
host: $('smtpHost').value.trim(),
port: Number($('smtpPort').value || 587),
secure: $('smtpSecure').value === 'true',
user: $('smtpUser').value.trim(),
from_name: $('smtpFromName').value.trim(),
from_email: $('smtpFromEmail').value.trim(),
};
// 只有填了才提交,避免把已保存的密码覆盖成空
const pw = $('smtpPassword').value;
if (pw) payload.password = pw;
try {
await API.saveSmtpConfig(payload);
$('smtpPassword').value = '';
showToast('配置已保存', 'success');
renderAdminSmtp();
} catch (err) {
showToast(err.message, 'error');
}
});
$('smtpTestBtn').addEventListener('click', async function() {
const btn = this;
btn.disabled = true;
btn.textContent = '发送中…';
try {
const r = await API.sendTestMail();
showToast('测试邮件已发送至 ' + r.to, 'success');
} catch (err) {
showToast(err.message, 'error');
} finally {
btn.disabled = false;
btn.textContent = '发送测试邮件';
}
});
$('smtpClearPwBtn').addEventListener('click', async () => {
const ok = await showConfirm('确定要清除已保存的 SMTP 密码吗?', {
title: '清除密码', confirmText: '清除', danger: true,
});
if (!ok) return;
try {
await API.clearSmtpPassword();
showToast('密码已清除', 'success');
renderAdminSmtp();
} catch (err) {
showToast(err.message, 'error');
}
});
$('emailVerifyRequired').addEventListener('change', async function() {
const desired = this.checked;
try {
await API.setEmailVerifyRequired(desired);
showToast(desired ? '已开启注册邮箱验证' : '已关闭注册邮箱验证', 'success');
} catch (err) {
// 失败时把开关状态回滚,避免界面与服务端不一致
this.checked = !desired;
showToast(err.message, 'error');
}
});
}
// ============================================================
// 🎨 自定义 CSS(独立标签页)- 已改用 Toast 提示
// ============================================================
function renderAdminCustomCSS() {
const container = document.getElementById('adminContent');
container.innerHTML = `
${getIcon('paint')} 自定义 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') {
showToast('文件名必须是 style.css', 'error');
selectedFile = null;
fileInput.value = '';
return;
}
if (!file.type.includes('text/css') && !file.name.endsWith('.css')) {
showToast('请上传 CSS 文件', 'error');
selectedFile = null;
fileInput.value = '';
return;
}
selectedFile = file;
showToast('已选择: ' + file.name + ' (' + (file.size / 1024).toFixed(1) + ' KB)', 'success');
}
document.getElementById('customCssSaveBtn').addEventListener('click', function() {
if (!selectedFile) {
showToast('请先选择 style.css 文件', 'warning');
return;
}
showCustomCssWarningModal(async function() {
try {
await API.uploadCustomCSS(selectedFile);
showToast('CSS 上传成功!刷新页面查看效果', 'success');
selectedFile = null;
fileInput.value = '';
dropText.textContent = '点击或拖拽上传 style.css';
loadCustomCSS();
} catch (err) {
showToast('上传失败:' + err.message, 'error');
}
});
});
document.getElementById('customCssDeleteBtn').addEventListener('click', async function() {
const ok = await showConfirm('确定要删除自定义 CSS 吗?将恢复默认样式。', {
title: '删除自定义 CSS',
confirmText: '删除',
danger: true,
});
if (!ok) return;
try {
await API.deleteCustomCSS();
showToast('已删除自定义 CSS', 'success');
const link = document.getElementById('customCssLink');
if (link) link.remove();
} catch (err) {
showToast('删除失败:' + err.message, 'error');
}
});
}
// ============================================================
// 📄 自定义页面管理
// ============================================================
let editingPageId = null;
function renderAdminCustomPages() {
const container = document.getElementById('adminContent');
container.innerHTML = `
${getIcon('page')} 自定义页面
`;
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 += `
${escapeHTML(p.name)} |
${escapeHTML(p.title)} |
?custom=${escapeHTML(p.name)} |
${p.enabled ? `${getIcon('success')} 启用` : `${getIcon('error')} 禁用`} |
|
`;
});
html += '
';
container.innerHTML = sanitizeHTML(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', async function() {
const ok = await showConfirm('确定要删除这个页面吗?', {
title: '删除页面', confirmText: '删除', danger: true,
});
if (!ok) return;
API.deleteCustomPage(this.dataset.id).then(() => {
loadCustomPageList();
loadCustomPagesNav();
}).catch(err => showToast('删除失败:' + err.message, 'error'));
});
});
}).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 ? getIcon('edit') + ' 编辑页面' : getIcon('add') + ' 添加页面'}
${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) { showToast('请输入页面名称', 'warning'); return; }
if (!title) { showToast('请输入导航栏显示名称', 'warning'); return; }
if (!content) { showToast('请输入页面内容', 'warning'); return; }
if (!/^[a-zA-Z0-9\-_]+$/.test(name)) {
showToast('页面名称只允许字母、数字、短横线和下划线', 'warning');
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) {
showToast('保存失败:' + err.message, 'error');
}
});
}
// ============================================================
// 自定义 CSS 警告模态框
// ============================================================
function showCustomCssWarningModal(onConfirm) {
const modal = document.createElement('div');
modal.className = 'modal active';
modal.style.display = 'flex';
modal.innerHTML = `
${getIcon('warning')} 警告
若上传的 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,
smtp: renderAdminSmtp,
custom: renderAdminCustomPages
};
if (tabMap[tab]) tabMap[tab]();
});
// 页面加载时尝试加载自定义 CSS
document.addEventListener('DOMContentLoaded', function() {
setTimeout(loadCustomCSS, 500);
});