Files
2026-09-11 07:15:51 +08:00

172 lines
9.6 KiB
JavaScript

// GameParlor 前端公共脚本
(function () {
const API_BASE = '';
// ---------- 存储 ----------
const TOKEN_KEY = 'gp_token';
const USER_KEY = 'gp_user';
window.GP = {
getToken() { return localStorage.getItem(TOKEN_KEY); },
setToken(t) { localStorage.setItem(TOKEN_KEY, t); },
clearAuth() { localStorage.removeItem(TOKEN_KEY); localStorage.removeItem(USER_KEY); },
getUser() {
try { return JSON.parse(localStorage.getItem(USER_KEY) || 'null'); }
catch { return null; }
},
setUser(u) { localStorage.setItem(USER_KEY, JSON.stringify(u)); },
isAdmin() { const u = this.getUser(); return u && u.role === 'ADMIN'; },
isMember() { const u = this.getUser(); return u && (u.role === 'MEMBER' || u.role === 'ADMIN'); },
redirectLogin() { window.location.href = '/index.html'; },
};
// ---------- API ----------
async function api(path, options = {}) {
const headers = Object.assign({ 'Content-Type': 'application/json' }, options.headers || {});
const token = GP.getToken();
if (token) headers['Authorization'] = 'Bearer ' + token;
const res = await fetch(API_BASE + path, Object.assign({ headers }, options));
let body;
try { body = await res.json(); } catch { body = { code: 500, message: '网络错误' }; }
if (body.code === 401) {
GP.clearAuth();
GP.redirectLogin();
throw new Error(body.message || '未登录');
}
if (body.code !== 200) {
toast(body.message || '操作失败', 'error');
throw new Error(body.message);
}
return body.data;
}
window.api = api;
// ---------- Toast ----------
let toastTimer = null;
function toast(message, type = 'success') {
const existing = document.querySelector('.toast');
if (existing) existing.remove();
const el = document.createElement('div');
el.className = 'toast toast-' + type;
el.textContent = message;
document.body.appendChild(el);
clearTimeout(toastTimer);
toastTimer = setTimeout(() => el.remove(), 2200);
}
window.toast = toast;
// ---------- 登出 ----------
window.logout = async function () {
try { await api('/api/auth/logout', { method: 'POST' }); } catch {}
GP.clearAuth();
GP.redirectLogin();
};
// ---------- 工具 ----------
window.fmtMoney = function (n) {
if (n == null) return '0.00';
return Number(n).toFixed(2);
};
window.fmtDateTime = function (s) {
if (!s) return '-';
return s.replace('T', ' ').slice(0, 16);
};
window.fmtDate = function (s) {
if (!s) return '-';
return String(s).slice(0, 10);
};
window.fmtDuration = function (seconds) {
if (seconds == null) return '00:00';
const m = Math.floor(seconds / 60);
const s = seconds % 60;
return String(m).padStart(2, '0') + ':' + String(s).padStart(2, '0');
};
// ---------- 布局骨架 ----------
// 本脚本在 body 末尾以经典脚本方式加载,执行时 Alpine(defer) 尚未启动。
// 在此同步完成 header/main 的 DOM 搭建,可避免 Alpine 启动后再移动节点
// 触发 MutationObserver 而导致 x-init / initLayout 二次执行(顶部菜单重复的根因)。
if (!document.body.classList.contains('gp-auth')) {
const header = document.createElement('header');
header.className = 'gp-header';
header.innerHTML =
'<div class="gp-header-inner">' +
'<div class="gp-brand"><span class="gp-logo">G</span><span>GameParlor</span></div>' +
'<nav class="gp-nav gp-nav-desktop" data-gp-nav="desktop"></nav>' +
'<div class="gp-userbar" data-gp-userbar></div>' +
'</div>' +
'<nav class="gp-nav gp-nav-mobile" data-gp-nav="mobile"></nav>';
const main = document.createElement('main');
main.className = 'gp-page page-fade';
Array.from(document.body.children).forEach(c => main.appendChild(c));
document.body.appendChild(header);
document.body.appendChild(main);
}
// ---------- 顶部导航数据填充(Alpine 启动后调用,仅填充,不再移动 DOM) ----------
window.initLayout = async function (active) {
if (window.__gpLayoutMe) return window.__gpLayoutMe; // 幂等,防止重复注入
const me = await api('/api/user/me').catch(() => null);
if (!me) { GP.clearAuth(); GP.redirectLogin(); throw new Error('未登录'); }
GP.setUser(me);
window.__gpLayoutMe = me;
const isAdmin = me.role === 'ADMIN';
const isMember = me.role === 'MEMBER' || isAdmin;
const navItems = isAdmin ? [
{ key: 'dashboard', label: '概览', href: '/admin/dashboard.html' },
{ key: 'devices', label: '设备', href: '/admin/devices.html' },
{ key: 'games', label: '游戏', href: '/admin/games.html' },
{ key: 'timeslots', label: '时长', href: '/admin/timeslots.html' },
{ key: 'snacks', label: '零食', href: '/admin/snacks.html' },
{ key: 'combos', label: '套餐', href: '/admin/combos.html' },
{ key: 'users', label: '用户', href: '/admin/users.html' },
{ key: 'recharge', label: '充值审批', href: '/admin/recharge.html' },
] : [
{ key: 'dashboard', label: '首页', href: '/player/dashboard.html' },
{ key: 'browse', label: '玩游戏', href: '/player/browse.html' },
{ key: 'combos', label: '套餐', href: '/player/combos.html' },
...(isMember ? [{ key: 'custom', label: '拼套餐', href: '/player/custom-combo.html' }] : []),
{ key: 'snacks', label: '零食', href: '/player/snacks.html' },
{ key: 'recharge', label: '充值', href: '/player/recharge.html' },
...(isMember ? [{ key: 'points', label: '积分兑换', href: '/player/points.html' }] : []),
{ key: 'history', label: '记录', href: '/player/history.html' },
];
const navHtml = navItems.map(n =>
`<a href="${n.href}"${active === n.key ? ' class="is-active"' : ''}>${n.label}</a>`).join('');
document.querySelectorAll('[data-gp-nav]').forEach(el => { el.innerHTML = navHtml; });
const userbar = document.querySelector('[data-gp-userbar]');
if (userbar) {
userbar.innerHTML =
'<span class="gp-user-meta">' +
'<span>余额 ¥' + fmtMoney(me.balance) + '</span>' +
(isMember ? '<span class="badge badge-accent">会员</span>' : '') +
'<span title="累计消费额(积分)">★ ' + (me.points || 0) + '</span>' +
'</span>' +
'<span class="gp-username"></span>' +
'<button type="button" onclick="logout()" class="btn btn-ghost gp-logout">退出</button>';
userbar.querySelector('.gp-username').textContent = me.username;
}
return me;
};
// ---------- 内联 SVG 图标 ----------
const iconHome = '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="inline"><path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/></svg>';
const iconDevice = '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="inline"><rect x="2" y="6" width="20" height="12" rx="2"/><path d="M6 12h.01M10 12h.01"/></svg>';
const iconGame = '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="inline"><line x1="6" y1="11" x2="10" y2="11"/><line x1="8" y1="9" x2="8" y2="13"/><line x1="15" y1="12" x2="15.01" y2="12"/><line x1="18" y1="10" x2="18.01" y2="10"/><rect x="2" y="6" width="20" height="12" rx="6"/></svg>';
const iconClock = '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="inline"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>';
const iconSnack = '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="inline"><path d="M5 3h14l-2 18H7z"/><line x1="9" y1="8" x2="9" y2="13"/><line x1="15" y1="8" x2="15" y2="13"/></svg>';
const iconCombo = '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="inline"><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/></svg>';
const iconUser = '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="inline"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>';
const iconWallet = '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="inline"><path d="M21 12V7H5a2 2 0 0 1 0-4h14v4"/><path d="M3 5v14a2 2 0 0 0 2 2h16v-5"/><path d="M18 12a2 2 0 0 0 0 4h4v-4z"/></svg>';
const iconStar = '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="inline"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/></svg>';
const iconList = '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="inline"><line x1="8" y1="6" x2="21" y2="6"/><line x1="8" y1="12" x2="21" y2="12"/><line x1="8" y1="18" x2="21" y2="18"/><line x1="3" y1="6" x2="3.01" y2="6"/><line x1="3" y1="12" x2="3.01" y2="12"/><line x1="3" y1="18" x2="3.01" y2="18"/></svg>';
})();