// 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 = '