File size: 31,458 Bytes
d6f9917
 
 
 
 
 
 
619e95a
 
0419e54
619e95a
8e5150a
 
619e95a
 
 
 
d6f9917
 
 
 
619e95a
 
d6f9917
 
619e95a
d6f9917
619e95a
 
 
e781bb0
d6f9917
 
 
619e95a
d6f9917
 
619e95a
 
 
8e5150a
 
 
cdbe323
8e5150a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
619e95a
 
 
 
d6f9917
 
e20afc1
619e95a
d6f9917
 
12cd248
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e8c0c1
 
 
 
 
 
d6f9917
 
 
 
619e95a
 
 
 
 
d6f9917
358280b
619e95a
 
251e3ec
 
619e95a
 
 
 
 
 
 
358280b
619e95a
251e3ec
619e95a
 
 
 
358280b
619e95a
 
358280b
619e95a
 
 
 
 
e20afc1
619e95a
 
 
 
358280b
619e95a
251e3ec
619e95a
 
 
 
d6f9917
 
 
 
 
9e8c0c1
d6f9917
0419e54
 
d6f9917
619e95a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d6f9917
 
619e95a
 
 
 
e20afc1
 
d6f9917
619e95a
d6f9917
619e95a
 
 
 
 
0419e54
d6f9917
 
 
 
8e5150a
 
 
 
9e8c0c1
0419e54
d6f9917
 
b699cce
0419e54
619e95a
d6f9917
 
 
0419e54
619e95a
 
 
 
 
 
0419e54
 
 
 
619e95a
0419e54
619e95a
 
 
 
0419e54
619e95a
 
 
 
 
 
 
90321a3
 
 
 
 
b699cce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
619e95a
 
 
 
 
 
 
8299f38
619e95a
8299f38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
619e95a
 
 
 
8299f38
619e95a
 
 
 
 
8299f38
619e95a
8299f38
619e95a
0419e54
 
d6f9917
 
 
619e95a
d6f9917
619e95a
 
d6f9917
 
619e95a
 
d6f9917
 
 
619e95a
251e3ec
8e5150a
 
251e3ec
d6f9917
619e95a
 
 
251e3ec
619e95a
 
 
251e3ec
619e95a
d6f9917
619e95a
 
 
 
 
d6f9917
619e95a
 
 
 
d6f9917
 
 
 
 
619e95a
d6f9917
 
619e95a
d6f9917
619e95a
 
 
 
 
 
 
d6f9917
 
 
619e95a
 
 
 
 
d6f9917
 
 
 
 
 
 
 
619e95a
 
 
 
d6f9917
 
 
 
619e95a
d6f9917
 
619e95a
d6f9917
 
 
 
 
619e95a
 
d6f9917
619e95a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d6f9917
 
619e95a
 
d6f9917
 
 
 
 
 
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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>CerebrateX 作战指挥室</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        .modal { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 100; opacity: 0; transition: opacity 0.2s; }
        .modal.active { display: flex; opacity: 1; align-items: center; justify-content: center; }
        th.sortable { cursor: pointer; transition: background-color 0.2s; }
        th.sortable:hover { background-color: #e2e8f0; }
        /* 隐藏原生下拉箭头,保持表头整洁 */
        select.clean-select { -webkit-appearance: none; -moz-appearance: none; appearance: none; }
        /* Toast 动画样式 */
        .toast-enter { transform: translateY(-20px); opacity: 0; }
        .toast-enter-active { transform: translateY(0); opacity: 1; transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); }
        .toast-exit { transform: translateY(-20px); opacity: 0; transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); }
    </style>
</head>
<body class="bg-slate-50 text-slate-800 p-8">

    <div id="toastContainer" class="fixed top-5 right-5 z-[9999] flex flex-col gap-3 pointer-events-none"></div>

    <div class="max-w-7xl mx-auto">
        <div class="flex justify-between items-center mb-8">
            <h1 class="text-3xl font-bold text-slate-900 tracking-tight">CerebrateX <span class="text-blue-600">作战指挥室</span></h1>
            <div class="flex gap-4">
                <input type="password" id="adminToken" placeholder="输入 Admin Token" class="px-4 py-2 border rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 transition">
                <button onclick="loadUsers()" class="bg-blue-600 text-white px-6 py-2 rounded-lg hover:bg-blue-700 shadow-md font-semibold transition active:scale-95">进入指挥室</button>
                <button onclick="exportCSV()" class="bg-emerald-600 text-white px-6 py-2 rounded-lg hover:bg-emerald-700 shadow-md font-semibold transition active:scale-95">一键导出 CSV</button>
                <button onclick="copyEmails()" class="bg-amber-600 text-white px-6 py-2 rounded-lg hover:bg-amber-700 shadow-md font-semibold transition active:scale-95 ml-2">📋 复制全部邮箱</button>
            </div>
        </div>

        <div class="bg-white rounded-xl shadow-sm border border-slate-200 overflow-x-auto">
            <table class="w-full text-left border-collapse">
                <thead>
                    <tr class="bg-slate-50 border-b border-slate-200">
                        <th class="p-4 font-semibold text-sm text-slate-600">邮箱 / ID</th>
                        <th class="p-4 font-semibold text-sm text-slate-600 sortable select-none" onclick="handleSort('status')">状态 <span id="sort-status" class="text-slate-400"></span></th>
                        <th class="p-4 font-semibold text-sm text-slate-600">
                            套餐 (
                            <select id="langFilter" onchange="loadUsers()" class="clean-select bg-transparent font-bold text-blue-600 outline-none cursor-pointer border-none p-0">
                                <option value="">全部市场</option>
                                <option value="zh">🇨🇳 简中 (zh)</option>
                                <option value="zh-TW">繁中 (zh-TW)</option>
                                <option value="en">🇺🇸 英语 (en)</option>
                                <option value="ja">🇯🇵 日语 (ja)</option>
                                <option value="ko">🇰🇷 韩语 (ko)</option>
                                <option value="fr">🇫🇷 法语 (fr)</option>
                                <option value="de">🇩🇪 德语 (de)</option>
                                <option value="es">🇪🇸 西语 (es)</option>
                                <option value="ru">🇷🇺 俄语 (ru)</option>
                                <option value="it">🇮🇹 意语 (it)</option>
                                <option value="pt">🇵🇹 葡语 (pt)</option>
                                <option value="hi">🇮🇳 印地语 (hi)</option>
                                <option value="ar">🇸🇦 阿语 (ar)</option>
                                <option value="bn">🇧🇩 孟加拉 (bn)</option>
                                <option value="pa">🇵🇰 旁遮普 (pa)</option>
                                <option value="jv">🇮🇩 爪哇语 (jv)</option>
                                <option value="te">🇮🇳 泰卢固 (te)</option>
                                <option value="vi">🇻🇳 越南语 (vi)</option>
                                <option value="mr">🇮🇳 马拉地 (mr)</option>
                                <option value="ta">🇮🇳 泰米尔 (ta)</option>
                                <option value="tr">🇹🇷 土耳其 (tr)</option>
                                <option value="th">🇹🇭 泰语 (th)</option>
                                <option value="pl">🇵🇱 波兰语 (pl)</option>
                                <option value="uk">🇺🇦 乌克兰 (uk)</option>
                                <option value="nl">🇳🇱 荷兰语 (nl)</option>
                                <option value="sv">🇸🇪 瑞典语 (sv)</option>
                                <option value="cs">🇨🇿 捷克语 (cs)</option>
                                <option value="el">🇬🇷 希腊语 (el)</option>
                                <option value="he">🇮🇱 以色列 (he)</option>
                                <option value="fa">🇮🇷 波斯语 (fa)</option>
                            </select>
                            )
                        </th>
                        <th class="p-4 font-semibold text-sm text-slate-600 sortable select-none" onclick="handleSort('points_balance')">周期/永久积分 <span id="sort-points_balance" class="text-slate-400"></span></th>
                        <th class="p-4 font-semibold text-sm text-slate-600 sortable select-none" onclick="handleSort('monthly_attachment_mb_used')">附件已用 / 记忆长度 <span id="sort-monthly_attachment_mb_used" class="text-slate-400"></span></th>
                        <th class="p-4 font-semibold text-sm text-slate-600 sortable select-none" onclick="handleSort('create_time')">注册时间 <span id="sort-create_time" class="text-slate-600">↓</span></th>
                        <th class="p-4 font-semibold text-sm text-slate-600 text-right">操作</th>
                    </tr>
                </thead>
                <tbody id="userTableBody" class="divide-y divide-slate-100">
                    <tr><td colspan="7" class="p-12 text-center text-slate-400 text-sm">请在右上角输入 Token 并进入指挥室</td></tr>
                </tbody>
            </table>
          <div class="mt-8 bg-white rounded-xl shadow-sm border border-slate-200">
              <button onclick="this.nextElementSibling.classList.toggle('hidden')" class="w-full p-4 text-left font-bold text-slate-700 hover:bg-slate-50 rounded-xl transition flex items-center gap-2">
                  📋 退信管理 <span id="bouncedTotal" class="text-sm text-slate-400 font-normal ml-2"></span>
                  <span class="ml-auto text-slate-400 text-xs">点击展开/收起</span>
              </button>
              <div class="hidden p-6 border-t border-slate-100">
                  <div class="flex gap-3 mb-4">
                      <input type="text" id="bouncedSearch" placeholder="搜索邮箱..." oninput="filterBouncedTable()" class="px-4 py-2 border border-slate-300 rounded-lg text-sm">
                      <button onclick="exportBouncedCsv()" class="px-4 py-2 bg-emerald-50 text-emerald-700 rounded-lg text-sm font-semibold hover:bg-emerald-100 transition">📥 导出 CSV</button>
                  </div>
                  <div class="overflow-x-auto max-h-96 overflow-y-auto">
                      <table class="w-full text-left border-collapse">
                          <thead class="bg-slate-50 sticky top-0">
                              <tr>
                                  <th class="p-3 font-semibold text-sm text-slate-600">邮箱</th>
                                  <th class="p-3 font-semibold text-sm text-slate-600">退信时间</th>
                                  <th class="p-3 font-semibold text-sm text-slate-600 text-right">操作</th>
                              </tr>
                          </thead>
                          <tbody id="bouncedTableBody" class="divide-y divide-slate-100"></tbody>
                      </table>
                  </div>
              </div>
          </div>
          <div class="flex justify-center gap-3 mt-4">
              <button onclick="currentPage=1;loadUsers()" class="px-4 py-2 bg-slate-100 rounded-lg text-sm hover:bg-slate-200">首页</button>
              <button onclick="if(currentPage>1){currentPage--;loadUsers()}" class="px-4 py-2 bg-slate-100 rounded-lg text-sm hover:bg-slate-200">上一页</button>
              <span class="px-4 py-2 text-sm text-slate-500">第 <span id="pageNum">1</span> 页</span>
              <button onclick="currentPage++;loadUsers()" class="px-4 py-2 bg-slate-100 rounded-lg text-sm hover:bg-slate-200">下一页</button>
          </div>
        </div>
    </div>

    <div id="adjustModal" class="modal">
        <div class="bg-white p-6 rounded-2xl shadow-2xl w-[400px] transform scale-95 transition-transform duration-200" id="adjustModalInner">
            <div class="flex justify-between items-center mb-5">
                <h2 class="text-xl font-bold text-slate-800">调整用户资产</h2>
                <button onclick="closeModal()" class="text-slate-400 hover:text-slate-600 text-xl font-bold">&times;</button>
            </div>
            <input type="hidden" id="targetUserId">
            
            <label class="block mb-2 text-sm font-semibold text-slate-700">请选择调整项</label>
            <select id="targetField" class="w-full p-3 border border-slate-300 rounded-lg mb-4 bg-slate-50 focus:ring-2 focus:ring-blue-500 focus:outline-none transition">
                <option value="points_balance">周期积分 A库 (月底会被覆盖重置)</option>
                <option value="permanent_points">永久积分 B库 (商业空投/裂变奖励/不过期)</option>
                <option value="tier">套餐级别 (free/functional/strategic)</option>
                <option value="max_context_length">记忆长度 (整数)</option>
                <option value="monthly_attachment_mb_used">附件已用量 (数字)</option>
            </select>

            <label class="block mb-2 text-sm font-semibold text-slate-700">新数值 <span class="text-xs text-slate-400 font-normal">(直接覆盖当前值)</span></label>
            <input type="text" id="newValue" class="w-full p-3 border border-slate-300 rounded-lg mb-4 focus:ring-2 focus:ring-blue-500 focus:outline-none transition" placeholder="填入新的绝对值">

            <label class="block mb-2 text-sm font-semibold text-slate-700">操作原因 <span class="text-xs text-red-500 font-normal">(必填,计入财务审计表)</span></label>
            <input type="text" id="adjustReason" class="w-full p-3 border border-slate-300 rounded-lg mb-6 focus:ring-2 focus:ring-blue-500 focus:outline-none transition" placeholder="例如:商业充值、市场空投、客诉补偿">

            <div class="flex justify-end gap-3">
                <button onclick="closeModal()" class="px-5 py-2.5 bg-slate-100 text-slate-700 font-medium rounded-lg hover:bg-slate-200 transition">取消</button>
                <button onclick="submitAdjust()" class="px-5 py-2.5 bg-blue-600 text-white font-medium rounded-lg hover:bg-blue-700 shadow-md transition active:scale-95">确认执行</button>
            </div>
        </div>
    </div>

    <div id="statusModal" class="modal">
        <div class="bg-white p-6 rounded-2xl shadow-2xl w-[400px] transform scale-95 transition-transform duration-200" id="statusModalInner">
            <div class="flex justify-between items-center mb-4">
                <h2 class="text-xl font-bold text-slate-800">确认切换账号状态</h2>
                <button onclick="closeStatusModal()" class="text-slate-400 hover:text-slate-600 text-xl font-bold">&times;</button>
            </div>
            <p id="statusModalText" class="mb-5 text-sm text-slate-600 leading-relaxed"></p>
            
            <input type="hidden" id="statusUserId">
            <input type="hidden" id="statusNewState">

            <label class="block mb-2 text-sm font-semibold text-slate-700">操作原因 <span class="text-xs text-red-500 font-normal">(必填,计入风控审计)</span></label>
            <input type="text" id="statusReason" class="w-full p-3 border border-slate-300 rounded-lg mb-6 focus:ring-2 focus:ring-red-500 focus:outline-none transition" placeholder="例如:恶意违规封禁">

            <div class="flex justify-end gap-3">
                <button onclick="closeStatusModal()" class="px-5 py-2.5 bg-slate-100 text-slate-700 font-medium rounded-lg hover:bg-slate-200 transition">取消</button>
                <button onclick="submitStatusToggle()" id="statusConfirmBtn" class="px-5 py-2.5 bg-red-600 text-white font-medium rounded-lg hover:bg-red-700 shadow-md transition active:scale-95">确认切换</button>
            </div>
        </div>
    </div>

    <script>
        let currentPage = 1;  
        let currentUsers = [];
        let currentSortBy = 'create_time';
        let currentOrder = 'desc';

        // --- 全新 Toast 提示系统 ---
        function showToast(message, type = 'success') {
            const container = document.getElementById('toastContainer');
            const toast = document.createElement('div');
            const bgColor = type === 'success' ? 'bg-emerald-600' : 'bg-red-600';
            const icon = type === 'success' ? '✓' : '✕';
            
            toast.className = `${bgColor} text-white px-5 py-3 rounded-lg shadow-xl font-medium text-sm flex items-center gap-3 toast-enter pointer-events-auto`;
            toast.innerHTML = `<span class="font-bold text-lg leading-none">${icon}</span><span>${message}</span>`;
            
            container.appendChild(toast);
            
            requestAnimationFrame(() => {
                toast.classList.remove('toast-enter');
                toast.classList.add('toast-enter-active');
            });
            
            setTimeout(() => {
                toast.classList.remove('toast-enter-active');
                toast.classList.add('toast-exit');
                setTimeout(() => toast.remove(), 300);
            }, 3000);
        }

        async function apiCall(url, method = 'GET', body = null) {
            const token = document.getElementById('adminToken').value;
            if (!token) {
                showToast('请先输入右上角的 Admin Token', 'error');
                throw new Error('No token');
            }
            const headers = { 'X-Admin-Token': token, 'Content-Type': 'application/json' };
            const options = { method, headers };
            if (body) options.body = JSON.stringify(body);
            
            const res = await fetch(url, options);
            if (!res.ok) {
                const err = await res.text();
                showToast(`请求被拒绝: ${err}`, 'error');
                throw new Error(err);
            }
            return res;
        }

        async function loadUsers() {
            try {
                // 读取市场区划筛选项,并拼接入请求
                const lang = document.getElementById('langFilter').value;
                const langParam = lang ? `&lang=${lang}` : '';
                
                const res = await apiCall(`/api/admin/users?limit=100&sort_by=${currentSortBy}&order=${currentOrder}${langParam}&page=${currentPage}`);
                const data = await res.json();
                currentUsers = data.users;
                renderTable();
                loadBouncedEmails();
                updateSortUI();
                showToast('作战数据加载成功', 'success');
            } catch (e) {}
        }

        function handleSort(column) {
            if (currentSortBy === column) {
                currentOrder = currentOrder === 'asc' ? 'desc' : 'asc';
            } else {
                currentSortBy = column;
                currentOrder = 'desc'; 
            }
            loadUsers();
        }

        function updateSortUI() {
            ['status', 'points_balance', 'monthly_attachment_mb_used', 'create_time'].forEach(col => {
                const el = document.getElementById(`sort-${col}`);
                if (el) {
                    el.textContent = '';
                    el.className = 'text-slate-400';
                }
            });
            const currentEl = document.getElementById(`sort-${currentSortBy}`);
            if (currentEl) {
                currentEl.textContent = currentOrder === 'asc' ? '↑' : '↓';
                currentEl.className = 'text-blue-600 font-bold ml-1';
            }
        }

        function copyEmails() {
            const emails = currentUsers.map(u => u.email).filter(Boolean).join('\n');
            if (!emails) { showToast('没有可复制的邮箱', 'error'); return; }
            navigator.clipboard.writeText(emails).then(() => showToast('已复制全部邮箱到剪贴板', 'success'));
        }

        async function loadBouncedEmails() {
            const token = document.getElementById('adminToken').value;
            if (!token) return;
            try {
                const res = await fetch('/api/admin/bounced_emails', { headers: { 'X-Admin-Token': token } });
                const data = await res.json();
                window.bouncedData = data.emails || [];
                document.getElementById('bouncedTotal').textContent = `(${window.bouncedData.length} 条)`;
                renderBouncedTable(window.bouncedData);
            } catch(e) {}
        }
        function renderBouncedTable(emails) {
            const tbody = document.getElementById('bouncedTableBody');
            tbody.innerHTML = emails.map(e => `
                <tr class="hover:bg-slate-50">
                    <td class="p-3 text-sm font-mono text-slate-700">${e.email}</td>
                    <td class="p-3 text-xs text-slate-500">${e.created_at ? new Date(e.created_at).toLocaleString('zh-CN') : '-'}</td>
                    <td class="p-3 text-right">
                        <button onclick="deleteBounced('${e.email}')" class="text-red-500 hover:text-red-700 text-xs font-semibold">删除</button>
                    </td>
                </tr>
            `).join('');
        }
        function filterBouncedTable() {
            const kw = document.getElementById('bouncedSearch').value.toLowerCase();
            renderBouncedTable((window.bouncedData || []).filter(e => e.email.toLowerCase().includes(kw)));
        }
        async function deleteBounced(email) {
            if (!confirm(`确定从退信库中删除 ${email} 吗?`)) return;
            const token = document.getElementById('adminToken').value;
            await fetch(`/api/admin/bounced_emails?email=${encodeURIComponent(email)}`, { method: 'DELETE', headers: { 'X-Admin-Token': token } });
            loadBouncedEmails();
        }
        function exportBouncedCsv() {
            const csv = '邮箱,退信时间\n' + (window.bouncedData || []).map(e => `${e.email},${e.created_at || ''}`).join('\n');
            const blob = new Blob(['\uFEFF' + csv], { type: 'text/csv;charset=utf-8;' });
            const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = `bounced_emails_${new Date().toISOString().slice(0,10)}.csv`; a.click();
        }
      
        async function exportCSV() {
            const token = document.getElementById('adminToken').value;
            if (!token) {
                showToast('必须输入 Admin Token 以验证权限', 'error');
                return;
            }
            try {
                showToast('正在拉取全量数据并生成 CSV...', 'success');
                
                // 1. 复用已有的读取接口,把 limit 拉大到 50000 获取全量数据(绕开不存在的 export 接口)
                const lang = document.getElementById('langFilter').value;
                const langParam = lang ? `&lang=${lang}` : '';
                const res = await apiCall(`/api/admin/users?limit=50000&sort_by=${currentSortBy}&order=${currentOrder}${langParam}`);
                const data = await res.json();
                const exportUsers = data.users;

                if (!exportUsers || exportUsers.length === 0) {
                    showToast('没有数据可导出', 'error');
                    return;
                }

                // 2. 前端纯手工拼装 CSV 文件(自动规避中文乱码)
                const headers = ['邮箱', '用户ID', '状态', '语言', '套餐级别', '周期积分', '永久积分', '已用附件MB', '记忆长度', '注册时间'];
                let csvContent = "\uFEFF" + headers.join(',') + '\n'; // \uFEFF 强制带 BOM 格式,防止 Excel 打开乱码
                
                exportUsers.forEach(u => {
                    const row = [
                        u.email || '',
                        u.user_id || '',
                        u.status === 'active' ? '正常运行' : '已封停',
                        u.lang || 'zh',
                        u.tier || 'free',
                        u.points_balance || 0,
                        u.permanent_points || 0,
                        u.monthly_attachment_mb_used || 0,
                        u.max_context_length || 20000,
                        u.create_time ? new Date(u.create_time).toLocaleString('zh-CN', {hour12: false}) : '未知'
                    ];
                    // 处理数据中自带的逗号,套上双引号防止列错位
                    const escapedRow = row.map(field => `"${String(field).replace(/"/g, '""')}"`);
                    csvContent += escapedRow.join(',') + '\n';
                });

                // 3. 触发浏览器原生下载,文件直接落盘
                const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.style.display = 'none';
                a.href = url;
                a.download = `cerebratex_users_export_${new Date().getTime()}.csv`;
                document.body.appendChild(a);
                a.click();
                
                window.URL.revokeObjectURL(url);
                a.remove();
                showToast('CSV 导出成功!', 'success');
            } catch (e) {
                showToast(`导出失败: ${e.message}`, 'error');
            }
        }

        function renderTable() {
            const tbody = document.getElementById('userTableBody');
            tbody.innerHTML = currentUsers.map(u => `
                <tr class="hover:bg-blue-50/50 transition duration-150">
                    <td class="p-4">
                        <div class="font-bold text-slate-800">${u.email}</div>
                        <div class="text-xs text-slate-400 font-mono mt-0.5">${u.user_id}</div>
                    </td>
                    <td class="p-4">
                        <span class="px-2.5 py-1 text-xs font-bold rounded-md ${u.status === 'active' ? 'bg-emerald-100 text-emerald-700' : 'bg-red-100 text-red-700'}">
                            ${u.status === 'active' ? '正常运行' : '已封停'}
                        </span>
                    </td>
                    <td class="p-4">
                        <div class="font-bold text-slate-800 capitalize">${u.tier || 'free'}</div>
                        <div class="flex items-center gap-1.5 mt-1">
                            <span class="text-[10px] bg-indigo-50 text-indigo-600 border border-indigo-100 px-1.5 py-0.5 rounded">来源</span>
                            <span class="text-xs font-mono font-bold text-blue-600 uppercase">${u.lang || 'zh'}</span>
                        </div>
                    </td>
                    <td class="p-4">
                        <div class="flex items-center gap-2">
                            <span class="font-mono font-bold text-blue-600 text-lg">${u.points_balance || 0}</span>
                            <span class="text-[10px] bg-blue-100 text-blue-600 px-1.5 py-0.5 rounded">周期 A库</span>
                        </div>
                        <div class="flex items-center gap-2 mt-1">
                            <span class="font-mono font-bold text-emerald-600 text-sm">${u.permanent_points || 0}</span>
                            <span class="text-[10px] bg-emerald-100 text-emerald-600 px-1.5 py-0.5 rounded">永久 B库</span>
                        </div>
                    </td>
                    <td class="p-4 text-sm text-slate-600">
                        <div class="flex justify-between w-32 mb-1"><span>附件:</span> <span class="font-mono font-semibold">${u.monthly_attachment_mb_used || 0} MB</span></div>
                        <div class="flex justify-between w-32"><span>记忆:</span> <span class="font-mono font-semibold">${u.max_context_length || 20000}</span></div>
                    </td>
                    <td class="p-4 text-sm text-slate-500 font-mono">${u.create_time ? new Date(u.create_time).toLocaleString('zh-CN', {hour12: false}) : '未知'}</td>
                    <td class="p-4 text-right">
                        <div class="flex justify-end gap-3">
                            <button onclick="openModal('${u.user_id}')" class="text-blue-600 hover:text-blue-800 font-semibold text-sm transition bg-blue-50 px-3 py-1.5 rounded hover:bg-blue-100">干预资产</button>
                            <button onclick="openStatusModal('${u.user_id}', '${u.status}')" class="text-red-600 hover:text-red-800 font-semibold text-sm transition bg-red-50 px-3 py-1.5 rounded hover:bg-red-100">启停账号</button>
                        </div>
                    </td>
                </tr>
            `).join('');
        }

        // --- 资产干预逻辑 ---
        function openModal(userId) {
            document.getElementById('targetUserId').value = userId;
            document.getElementById('newValue').value = '';
            document.getElementById('adjustReason').value = '';
            const modal = document.getElementById('adjustModal');
            modal.style.display = 'flex';
            requestAnimationFrame(() => {
                modal.classList.add('active');
                document.getElementById('adjustModalInner').classList.remove('scale-95');
                document.getElementById('adjustModalInner').classList.add('scale-100');
            });
        }

        function closeModal() {
            const modal = document.getElementById('adjustModal');
            modal.classList.remove('active');
            document.getElementById('adjustModalInner').classList.remove('scale-100');
            document.getElementById('adjustModalInner').classList.add('scale-95');
            setTimeout(() => modal.style.display = 'none', 200);
        }

        async function submitAdjust() {
            const userId = document.getElementById('targetUserId').value;
            const targetField = document.getElementById('targetField').value;
            const newValue = document.getElementById('newValue').value;
            const reason = document.getElementById('adjustReason').value;

            if (!newValue || !reason) {
                showToast("新数值和操作原因不能为空", "error");
                return;
            }

            try {
                await apiCall(`/api/admin/users/${userId}/adjust`, 'POST', {
                    target_field: targetField,
                    new_value: newValue,
                    reason: reason
                });
                showToast("资产干预成功!资金流水已入账", "success");
                closeModal();
                loadUsers();
            } catch (e) {}
        }

        // --- 账号启停逻辑 ---
        function openStatusModal(userId, currentStatus) {
            const newStatus = (!currentStatus || currentStatus === 'active') ? 'disabled' : 'active';
            document.getElementById('statusUserId').value = userId;
            document.getElementById('statusNewState').value = newStatus;
            document.getElementById('statusReason').value = '';
            
            const textEl = document.getElementById('statusModalText');
            const btnEl = document.getElementById('statusConfirmBtn');
            if(newStatus === 'disabled') {
                textEl.innerHTML = `您即将把该账号设置为 <span class="font-bold text-red-600">已封停</span>。<br>用户将无法登录并使用任何 AI 服务。`;
                btnEl.className = "px-5 py-2.5 bg-red-600 text-white font-medium rounded-lg hover:bg-red-700 shadow-md transition active:scale-95";
            } else {
                textEl.innerHTML = `您即将把该账号恢复为 <span class="font-bold text-emerald-600">正常运行</span>。<br>用户的所有权限将被解封。`;
                btnEl.className = "px-5 py-2.5 bg-emerald-600 text-white font-medium rounded-lg hover:bg-emerald-700 shadow-md transition active:scale-95";
            }

            const modal = document.getElementById('statusModal');
            modal.style.display = 'flex';
            requestAnimationFrame(() => {
                modal.classList.add('active');
                document.getElementById('statusModalInner').classList.remove('scale-95');
                document.getElementById('statusModalInner').classList.add('scale-100');
            });
        }

        function closeStatusModal() {
            const modal = document.getElementById('statusModal');
            modal.classList.remove('active');
            document.getElementById('statusModalInner').classList.remove('scale-100');
            document.getElementById('statusModalInner').classList.add('scale-95');
            setTimeout(() => modal.style.display = 'none', 200);
        }

        async function submitStatusToggle() {
            const userId = document.getElementById('statusUserId').value;
            const newStatus = document.getElementById('statusNewState').value;
            const reason = document.getElementById('statusReason').value;

            if (!reason) {
                showToast("封禁或解封原因不能为空", "error");
                return;
            }

            try {
                await apiCall(`/api/admin/users/${userId}/status?status=${newStatus}&reason=${encodeURIComponent(reason)}`, 'POST');
                showToast("账号状态已成功切换!", "success");
                closeStatusModal();
                loadUsers();
            } catch (e) {}
        }
    </script>
</body>
</html>