905086
2026-11-03 262ce70998fa52dec3120589f51c47e96fb96df4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>99游戏盒子 - 管理后台</title>
<style>
* { margin:0; padding:0; box-sizing:border-box; }
body { font-family:"Microsoft YaHei",sans-serif; background:#14161f; color:#e0e0e0; font-size:14px; }
button { cursor:pointer; font-family:inherit; }
input,select,textarea { font-family:inherit; outline:none; }
.hidden { display:none !important; }
 
/* 登录页 */
#loginPage { display:flex; align-items:center; justify-content:center; height:100vh; }
.login-box { background:#1e2130; border-radius:12px; padding:40px; width:360px; box-shadow:0 10px 40px rgba(0,0,0,.5); }
.login-box h1 { font-size:20px; text-align:center; margin-bottom:8px; }
.login-box .sub { text-align:center; color:#888; font-size:12px; margin-bottom:24px; }
.login-box input { width:100%; padding:10px 12px; border-radius:6px; border:1px solid #333; background:#14161f; color:#fff; margin-bottom:14px; }
.btn { border:none; border-radius:6px; padding:9px 16px; background:#2b7fff; color:#fff; }
.btn:hover { background:#4a92ff; }
.btn-gray { background:#3a3f52; color:#ccc; }
.btn-gray:hover { background:#4a5069; }
.btn-danger { background:#c0392b; }
.btn-danger:hover { background:#d94a3a; }
.btn-sm { padding:5px 10px; font-size:12px; }
.btn-block { width:100%; padding:11px; font-size:15px; }
 
/* 主面板 */
#mainPage { display:none; height:100vh; flex-direction:column; }
.topbar { background:#1a1d2b; padding:0 24px; display:flex; align-items:center; height:56px; gap:20px; border-bottom:1px solid #262a3d; }
.logo { font-size:17px; font-weight:bold; color:#ff5c8a; }
.nav-tabs { display:flex; gap:4px; flex:1; }
.nav-tabs button { background:none; border:none; color:#9aa0b4; padding:8px 18px; border-radius:6px; font-size:14px; }
.nav-tabs button.active { background:#2b7fff; color:#fff; }
#logoutBtn { background:none; border:1px solid #3a3f52; color:#aaa; border-radius:6px; padding:7px 14px; }
 
.content { flex:1; overflow:auto; padding:24px; }
.stats-row { display:flex; gap:16px; margin-bottom:24px; }
.stat-card { background:#1e2130; border-radius:10px; padding:18px 24px; min-width:150px; }
.stat-card .num { font-size:26px; font-weight:bold; color:#4a92ff; }
.stat-card .label { color:#888; font-size:12px; margin-top:4px; }
 
.panel { background:#1e2130; border-radius:10px; padding:20px; }
.panel h2 { font-size:16px; margin-bottom:16px; }
.toolbar { display:flex; gap:10px; margin-bottom:16px; flex-wrap:wrap; align-items:center; }
.toolbar input, .toolbar select { background:#14161f; border:1px solid #333; color:#fff; border-radius:6px; padding:8px 10px; }
 
table { width:100%; border-collapse:collapse; }
th, td { padding:10px 12px; text-align:left; border-bottom:1px solid #262a3d; font-size:13px; }
th { color:#888; font-weight:normal; }
tr:hover td { background:#232739; }
.tag { display:inline-block; padding:2px 8px; border-radius:4px; font-size:12px; }
.tag-blue { background:rgba(43,127,255,.15); color:#4a92ff; }
.tag-green { background:rgba(46,204,113,.15); color:#2ecc71; }
.tag-red { background:rgba(231,76,60,.15); color:#e74c3c; }
.tag-gray { background:rgba(150,150,150,.15); color:#aaa; }
 
/* 弹窗 */
.modal-mask { position:fixed; inset:0; background:rgba(0,0,0,.6); display:flex; align-items:center; justify-content:center; z-index:100; }
.modal { background:#1e2130; border-radius:12px; padding:24px; width:640px; max-height:86vh; overflow:auto; }
.modal h3 { margin-bottom:18px; }
.form-row { margin-bottom:12px; }
.form-row label { display:block; color:#9aa0b4; font-size:12px; margin-bottom:6px; }
.form-row input, .form-row select, .form-row textarea { width:100%; background:#14161f; border:1px solid #333; color:#fff; border-radius:6px; padding:9px 10px; }
.form-row textarea { min-height:90px; resize:vertical; }
.form-cols { display:grid; grid-template-columns:1fr 1fr; gap:0 16px; }
.upload-box { border:1px dashed #3a3f52; border-radius:8px; padding:12px; margin-bottom:8px; }
.upload-box .hint { color:#666; font-size:12px; margin-bottom:8px; }
.file-item { display:flex; justify-content:space-between; background:#14161f; padding:6px 10px; border-radius:6px; margin-top:6px; font-size:12px; }
.file-item img { width:48px; height:32px; object-fit:cover; border-radius:4px; }
.pager { display:flex; gap:8px; align-items:center; margin-top:16px; justify-content:center; }
.pager button { background:#3a3f52; color:#ccc; border:none; border-radius:4px; padding:6px 12px; }
.pager button:disabled { opacity:.4; cursor:default; }
.toast { position:fixed; top:70px; left:50%; transform:translateX(-50%); background:#2ecc71; color:#fff; padding:10px 22px; border-radius:8px; z-index:200; display:none; }
.toast.err { background:#e74c3c; }
.keylist { background:#14161f; border-radius:6px; padding:12px; max-height:220px; overflow:auto; font-family:Consolas,monospace; line-height:1.9; margin-top:10px; }
</style>
</head>
<body>
 
<!-- 登录 -->
<div id="loginPage">
  <div class="login-box">
    <h1>99游戏盒子 · 管理后台</h1>
    <div class="sub">GameBox Admin</div>
    <input id="adminUser" placeholder="管理员账号" value="admin">
    <input id="adminPwd" type="password" placeholder="密码">
    <button class="btn btn-block" onclick="adminLogin()">登 录</button>
  </div>
</div>
 
<!-- 主面板 -->
<div id="mainPage">
  <div class="topbar">
    <div class="logo">99游戏盒子 · 管理后台</div>
    <div class="nav-tabs">
      <button class="active" data-tab="keys" onclick="switchTab('keys')">密钥管理</button>
      <button data-tab="games" onclick="switchTab('games')">游戏管理</button>
      <button data-tab="cats" onclick="switchTab('cats')">类别管理</button>
    </div>
    <button id="logoutBtn" onclick="logout()">退出登录</button>
  </div>
  <div class="content">
    <div class="stats-row" id="statsRow"></div>
 
    <!-- 密钥管理 -->
    <div id="tab-keys" class="panel">
      <h2>会员密钥</h2>
      <div class="toolbar">
        <select id="genType"><option value="day">日卡</option><option value="month">月卡</option><option value="year">年卡</option></select>
        <input id="genCount" type="number" value="10" min="1" max="100" style="width:80px">
        <button class="btn" onclick="generateKeys()">生成密钥</button>
        <span style="flex:1"></span>
        <input id="keyKeyword" placeholder="搜索激活码">
        <select id="keyStatus">
          <option value="">全部状态</option>
          <option value="0">未使用</option>
          <option value="1">已使用</option>
          <option value="2">已过期</option>
        </select>
        <button class="btn" onclick="loadKeys(1)">搜索</button>
      </div>
      <table>
        <thead><tr><th>ID</th><th>激活码</th><th>类型</th><th>状态</th><th>绑定用户</th><th>机器码</th><th>到期时间</th><th>重置次数</th><th>操作</th></tr></thead>
        <tbody id="keyTable"></tbody>
      </table>
      <div class="pager" id="keyPager"></div>
    </div>
 
    <!-- 游戏管理 -->
    <div id="tab-games" class="panel hidden">
      <h2>游戏资源</h2>
      <div class="toolbar">
        <button class="btn" onclick="showGameModal()">+ 上传游戏</button>
      </div>
      <table>
        <thead><tr><th>ID</th><th>封面</th><th>名称</th><th>类别</th><th>平台</th><th>大小</th><th>下载次数</th><th>操作</th></tr></thead>
        <tbody id="gameTable"></tbody>
      </table>
    </div>
 
    <!-- 类别管理 -->
    <div id="tab-cats" class="panel hidden">
      <h2>游戏类别</h2>
      <div class="toolbar">
        <input id="newCatName" placeholder="新类别名称">
        <button class="btn" onclick="addCategory()">添加类别</button>
      </div>
      <table>
        <thead><tr><th>ID</th><th>名称</th><th>游戏数</th><th>操作</th></tr></thead>
        <tbody id="catTable"></tbody>
      </table>
    </div>
  </div>
</div>
 
<!-- 游戏编辑弹窗 -->
<div id="gameModal" class="modal-mask hidden">
  <div class="modal">
    <h3 id="gameModalTitle">上传游戏</h3>
    <input type="hidden" id="g_id">
    <div class="form-cols">
      <div class="form-row"><label>游戏名称 *</label><input id="g_title"></div>
      <div class="form-row"><label>类别</label><select id="g_category"></select></div>
      <div class="form-row"><label>平台</label><select id="g_platform"><option value="pc">PC资源(单机)</option><option value="switch">Switch资源</option></select></div>
      <div class="form-row"><label>标签(逗号分隔,如: 即时战略,经典怀旧)</label><input id="g_tags"></div>
      <div class="form-row"><label>游戏大小(如 232.6 GB)</label><input id="g_size"></div>
      <div class="form-row"><label>安装磁盘占用(如 411.6 GB)</label><input id="g_install_size"></div>
      <div class="form-row"><label>系统要求</label><input id="g_os" placeholder="Windows 10 64bit"></div>
      <div class="form-row"><label>CPU要求</label><input id="g_cpu" placeholder="Intel i5-4460"></div>
      <div class="form-row"><label>显卡要求</label><input id="g_gpu" placeholder="GTX 1060 6GB"></div>
      <div class="form-row"><label>内存要求</label><input id="g_ram" placeholder="16 GB RAM"></div>
    </div>
    <div class="form-row"><label>版本说明(如 V1.685|官方简体中文|支持键盘.鼠标.手柄)</label><input id="g_version_note"></div>
    <div class="form-row"><label>是否首页轮播</label><select id="g_banner"><option value="0">否</option><option value="1">是</option></select></div>
 
    <div class="upload-box">
      <div class="hint">封面上传(jpg/png)</div>
      <input type="file" accept="image/*" onchange="uploadSingle(this,'cover','g_cover')">
      <div id="g_cover_list"></div>
      <input type="hidden" id="g_cover">
    </div>
    <div class="upload-box">
      <div class="hint">视频上传(mp4,可选)</div>
      <input type="file" accept="video/*" onchange="uploadSingle(this,'video','g_video')">
      <input type="hidden" id="g_video">
    </div>
    <div class="upload-box">
      <div class="hint">游戏截图(可多选)</div>
      <input type="file" accept="image/*" multiple onchange="uploadScreenshots(this)">
      <div id="g_shots_list"></div>
    </div>
    <div class="upload-box">
      <div class="hint">游戏安装包(zip/rar/exe/iso 等,可多选)</div>
      <input type="file" multiple onchange="uploadPackages(this)">
      <div id="g_files_list"></div>
    </div>
    <div class="form-row"><label>游戏介绍(说明图片文字)</label><textarea id="g_description"></textarea></div>
    <div style="display:flex;gap:10px;justify-content:flex-end;margin-top:16px">
      <button class="btn btn-gray" onclick="hideGameModal()">取消</button>
      <button class="btn" onclick="saveGame()">保存</button>
    </div>
  </div>
</div>
 
<div id="toast" class="toast"></div>
 
<script>
let token = localStorage.getItem('admin_token') || '';
let editingScreenshots = [], editingFiles = [];
let keyTotal = 0, keyPage = 1;
 
function toast(msg, err) {
  const t = document.getElementById('toast');
  t.textContent = msg; t.className = 'toast show' + (err ? ' err' : '');
  setTimeout(() => t.className = 'toast', 2500);
}
async function api(path, opts = {}) {
  opts.headers = Object.assign({'Content-Type': 'application/json'}, opts.headers || {});
  if (token) opts.headers['Authorization'] = 'Bearer ' + token;
  if (opts.body && typeof opts.body !== 'string' && !(opts.body instanceof FormData)) {
    opts.body = JSON.stringify(opts.body);
  }
  const res = await fetch(path, opts);
  if (res.status === 401) { localStorage.removeItem('admin_token'); location.reload(); throw new Error('未登录'); }
  return res.json();
}
 
function adminLogin() {
  const username = document.getElementById('adminUser').value.trim();
  const password = document.getElementById('adminPwd').value;
  fetch('/admin/api/login', {method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({username, password})})
    .then(r => r.json()).then(res => {
      if (res.code === 0) { token = res.data.token; localStorage.setItem('admin_token', token); enterPanel(); }
      else toast(res.msg, true);
    });
}
function logout() { localStorage.removeItem('admin_token'); location.reload(); }
 
function enterPanel() {
  document.getElementById('loginPage').style.display = 'none';
  document.getElementById('mainPage').style.display = 'flex';
  loadStats(); loadKeys(1); loadGames(); loadCategories();
}
function switchTab(tab) {
  document.querySelectorAll('.nav-tabs button').forEach(b => b.classList.toggle('active', b.dataset.tab === tab));
  ['keys','games','cats'].forEach(t => document.getElementById('tab-' + t).classList.toggle('hidden', t !== tab));
}
 
async function loadStats() {
  const res = await api('/admin/api/stats');
  if (res.code !== 0) return;
  const d = res.data;
  document.getElementById('statsRow').innerHTML = [
    ['注册用户', d.users], ['游戏总数', d.games], ['密钥总数', d.keys],
    ['未使用密钥', d.unused_keys], ['已使用密钥', d.used_keys],
  ].map(([l, n]) => `<div class="stat-card"><div class="num">${n}</div><div class="label">${l}</div></div>`).join('');
}
 
/* ---------- 密钥 ---------- */
async function generateKeys() {
  const card_type = document.getElementById('genType').value;
  const count = parseInt(document.getElementById('genCount').value) || 1;
  const res = await api('/admin/api/keys/generate', {method: 'POST', body: {card_type, count}});
  if (res.code !== 0) return toast(res.msg, true);
  let html = res.data.map(c => `<div>${c} <a href="javascript:void(0)" onclick="copyText('${c}')" style="color:#4a92ff">复制</a></div>`).join('');
  toast(res.msg);
  // 展示生成的密钥
  const w = document.createElement('div');
  w.className = 'modal-mask';
  w.innerHTML = `<div class="modal" style="width:420px"><h3>新生成的密钥</h3><div class="keylist">${html}</div>
    <div style="text-align:right;margin-top:14px"><button class="btn" onclick="this.closest('.modal-mask').remove();loadKeys(1)">知道了</button></div></div>`;
  document.body.appendChild(w);
}
function copyText(t) { navigator.clipboard.writeText(t); toast('已复制'); }
 
async function loadKeys(page) {
  keyPage = page || 1;
  const keyword = document.getElementById('keyKeyword').value.trim();
  const status = document.getElementById('keyStatus').value;
  const res = await api(`/admin/api/keys?page=${keyPage}&keyword=${encodeURIComponent(keyword)}&status=${status}`);
  if (res.code !== 0) return;
  keyTotal = res.data.total;
  const rows = res.data.list.map(k => {
    let st, cls;
    if (k.status === 0) { st = '未使用'; cls = 'tag-blue'; }
    else if (k.expired) { st = '已过期'; cls = 'tag-red'; }
    else { st = '使用中'; cls = 'tag-green'; }
    return `<tr>
      <td>${k.id}</td><td style="font-family:Consolas">${k.code}</td>
      <td><span class="tag tag-gray">${k.card_name}</span></td>
      <td><span class="tag ${cls}">${st}</span></td>
      <td>${k.phone || '-'}</td>
      <td style="max-width:160px;overflow:hidden;text-overflow:ellipsis">${k.machine_code || '-'}</td>
      <td>${k.expired_at_str || '-'}</td>
      <td>${k.reset_count}</td>
      <td>
        ${k.status === 1 ? `<button class="btn btn-sm" onclick="resetKey(${k.id})">重置(可再用)</button> ` : ''}
        <button class="btn btn-sm btn-danger" onclick="deleteKey(${k.id})">删除</button>
      </td></tr>`;
  }).join('');
  document.getElementById('keyTable').innerHTML = rows || '<tr><td colspan="9" style="text-align:center;color:#666">暂无数据</td></tr>';
  const pages = Math.max(1, Math.ceil(keyTotal / 20));
  document.getElementById('keyPager').innerHTML =
    `<button ${keyPage<=1?'disabled':''} onclick="loadKeys(${keyPage-1})">上一页</button>
     <span>第 ${keyPage} / ${pages} 页 · 共 ${keyTotal} 条</span>
     <button ${keyPage>=pages?'disabled':''} onclick="loadKeys(${keyPage+1})">下一页</button>`;
}
async function resetKey(id) {
  const res = await api(`/admin/api/keys/${id}/reset`, {method: 'POST'});
  toast(res.msg, res.code !== 0);
  loadKeys(keyPage);
}
async function deleteKey(id) {
  if (!confirm('确定删除该密钥?')) return;
  const res = await api(`/admin/api/keys/${id}`, {method: 'DELETE'});
  toast(res.msg, res.code !== 0);
  loadKeys(keyPage);
}
 
/* ---------- 游戏 ---------- */
async function loadGames() {
  const res = await api('/admin/api/games');
  if (res.code !== 0) return;
  const rows = res.data.map(g => `<tr>
    <td>${g.id}</td>
    <td><img src="${g.cover}" style="width:72px;height:44px;object-fit:cover;border-radius:4px" onerror="this.style.visibility='hidden'"></td>
    <td>${g.title}</td>
    <td>${g.category_name || '-'}</td>
    <td><span class="tag ${g.platform==='pc'?'tag-blue':'tag-green'}">${g.platform==='pc'?'PC':'Switch'}</span></td>
    <td>${g.size}</td>
    <td>${g.download_count}</td>
    <td>
      <button class="btn btn-sm" onclick='showGameModal(${JSON.stringify(g).replace(/'/g,"&#39;")})'>修改</button>
      <button class="btn btn-sm btn-danger" onclick="deleteGame(${g.id})">删除</button>
    </td></tr>`).join('');
  document.getElementById('gameTable').innerHTML = rows || '<tr><td colspan="8" style="text-align:center;color:#666">暂无数据</td></tr>';
}
function showGameModal(g) {
  editingScreenshots = []; editingFiles = [];
  if (g) {
    document.getElementById('gameModalTitle').innerText = '修改游戏';
    g_id.value = g.id; g_title.value = g.title; g_tags.value = g.tags || '';
    g_size.value = g.size || ''; g_install_size.value = g.install_size || '';
    g_os.value = g.os_req || ''; g_cpu.value = g.cpu_req || ''; g_gpu.value = g.gpu_req || ''; g_ram.value = g.ram_req || '';
    g_version_note.value = g.version_note || ''; g_description.value = g.description || '';
    g_platform.value = g.platform || 'pc'; g_banner.value = g.is_banner ? '1' : '0';
    g_cover.value = g.cover || ''; g_video.value = g.video || '';
    try { editingScreenshots = JSON.parse(g.screenshots || '[]'); } catch(e) {}
    try { editingFiles = JSON.parse(g.files || '[]'); } catch(e) {}
    document.getElementById('g_category').value = g.category_id || '';
  } else {
    document.getElementById('gameModalTitle').innerText = '上传游戏';
    document.querySelectorAll('#gameModal input,#gameModal textarea,#gameModal select').forEach(el => { if(el.type!=='file') el.value=''; });
    g_platform.value = 'pc'; g_banner.value = '0';
  }
  renderShots(); renderFiles(); renderCover();
  document.getElementById('gameModal').classList.remove('hidden');
}
function hideGameModal() { document.getElementById('gameModal').classList.add('hidden'); }
function renderCover() {
  const url = document.getElementById('g_cover').value;
  document.getElementById('g_cover_list').innerHTML = url ? `<div class="file-item"><img src="${url}"><span>${url}</span></div>` : '';
}
async function uploadSingle(input, type, targetId) {
  if (!input.files.length) return;
  const fd = new FormData();
  fd.append('file', input.files[0]); fd.append('type', type);
  const res = await api('/admin/api/upload', {method: 'POST', body: fd});
  if (res.code !== 0) return toast(res.msg, true);
  document.getElementById(targetId).value = res.data.url;
  if (targetId === 'g_cover') renderCover();
  toast('上传成功');
}
async function uploadScreenshots(input) {
  for (const f of input.files) {
    const fd = new FormData();
    fd.append('file', f); fd.append('type', 'image');
    const res = await api('/admin/api/upload', {method: 'POST', body: fd});
    if (res.code === 0) editingScreenshots.push(res.data.url);
  }
  renderShots(); toast('截图上传完成');
}
async function uploadPackages(input) {
  for (const f of input.files) {
    const fd = new FormData();
    fd.append('file', f); fd.append('type', 'file');
    const res = await api('/admin/api/upload', {method: 'POST', body: fd});
    if (res.code === 0) editingFiles.push({name: res.data.name, size: res.data.size, url: res.data.url});
  }
  renderFiles(); toast('安装包上传完成');
}
function renderShots() {
  document.getElementById('g_shots_list').innerHTML = editingScreenshots.map((u, i) =>
    `<div class="file-item"><img src="${u}"><span>${u}</span><button class="btn btn-sm btn-danger" onclick="editingScreenshots.splice(${i},1);renderShots()">移除</button></div>`).join('');
}
function renderFiles() {
  document.getElementById('g_files_list').innerHTML = editingFiles.map((f, i) =>
    `<div class="file-item"><span>${f.name}(${f.size})</span><button class="btn btn-sm btn-danger" onclick="editingFiles.splice(${i},1);renderFiles()">移除</button></div>`).join('');
}
async function saveGame() {
  const body = {
    id: parseInt(g_id.value) || 0,
    title: g_title.value.trim(), category_id: parseInt(g_category.value) || 0,
    platform: g_platform.value, tags: g_tags.value.trim(),
    size: g_size.value.trim(), install_size: g_install_size.value.trim(),
    os_req: g_os.value.trim(), cpu_req: g_cpu.value.trim(), gpu_req: g_gpu.value.trim(), ram_req: g_ram.value.trim(),
    version_note: g_version_note.value.trim(), cover: g_cover.value, video: g_video.value,
    screenshots: JSON.stringify(editingScreenshots), description: g_description.value,
    files: JSON.stringify(editingFiles), is_banner: g_banner.value === '1',
  };
  const res = await api('/admin/api/games', {method: 'POST', body});
  toast(res.msg, res.code !== 0);
  if (res.code === 0) { hideGameModal(); loadGames(); loadStats(); }
}
async function deleteGame(id) {
  if (!confirm('确定删除该游戏?')) return;
  const res = await api(`/admin/api/games/${id}`, {method: 'DELETE'});
  toast(res.msg, res.code !== 0);
  loadGames(); loadStats();
}
 
/* ---------- 类别 ---------- */
async function loadCategories() {
  const res = await api('/admin/api/categories');
  if (res.code !== 0) return;
  document.getElementById('g_category').innerHTML = '<option value="">未分类</option>' +
    res.data.map(c => `<option value="${c.id}">${c.name}</option>`).join('');
  const gres = await api('/admin/api/games');
  const cnt = {};
  (gres.data || []).forEach(g => { cnt[g.category_id] = (cnt[g.category_id] || 0) + 1; });
  document.getElementById('catTable').innerHTML = res.data.map(c =>
    `<tr><td>${c.id}</td><td>${c.name}</td><td>${cnt[c.id] || 0}</td>
     <td><button class="btn btn-sm" onclick="renameCat(${c.id},'${c.name}')">修改名称</button>
     <button class="btn btn-sm btn-danger" onclick="deleteCat(${c.id})">删除</button></td></tr>`).join('');
}
async function addCategory() {
  const name = document.getElementById('newCatName').value.trim();
  if (!name) return toast('请填写类别名称', true);
  const res = await api('/admin/api/categories', {method: 'POST', body: {name}});
  toast(res.msg, res.code !== 0);
  if (res.code === 0) { document.getElementById('newCatName').value = ''; loadCategories(); }
}
async function renameCat(id, oldName) {
  const name = prompt('修改类别名称', oldName);
  if (!name || name === oldName) return;
  const res = await api('/admin/api/categories', {method: 'POST', body: {id, name}});
  toast(res.msg, res.code !== 0);
  loadCategories();
}
async function deleteCat(id) {
  if (!confirm('确定删除该类别?')) return;
  const res = await api(`/admin/api/categories/${id}`, {method: 'DELETE'});
  toast(res.msg, res.code !== 0);
  loadCategories();
}
 
document.getElementById('adminPwd').addEventListener('keydown', e => { if (e.key === 'Enter') adminLogin(); });
if (token) enterPanel();
</script>
</body>
</html>