File size: 42,549 Bytes
8cdca00
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
let apiKey = '';
let currentScope = 'none';
let currentToken = '';
let currentSection = 'image';
const accountMap = new Map();
const selectedTokens = new Set();
const selectedLocal = {
  image: new Set(),
  video: new Set()
};
const ui = {};
const byId = (id) => document.getElementById(id);
const loadFailed = new Map();
const deleteFailed = new Map();
let currentBatchAction = null;
let lastBatchAction = null;
let isLocalDeleting = false;
const cacheListState = {
  image: { loaded: false, visible: false, items: [] },
  video: { loaded: false, visible: false, items: [] }
};
const UI_MAP = {
  imgCount: 'img-count',
  imgSize: 'img-size',
  videoCount: 'video-count',
  videoSize: 'video-size',
  onlineCount: 'online-count',
  onlineStatus: 'online-status',
  onlineLastClear: 'online-last-clear',
  accountTableBody: 'account-table-body',
  accountEmpty: 'account-empty',
  selectAll: 'select-all',
  localImageSelectAll: 'local-image-select-all',
  localVideoSelectAll: 'local-video-select-all',
  selectedCount: 'selected-count',
  batchActions: 'batch-actions',
  loadBtn: 'btn-load-stats',
  deleteBtn: 'btn-delete-assets',
  localCacheLists: 'local-cache-lists',
  localImageList: 'local-image-list',
  localVideoList: 'local-video-list',
  localImageBody: 'local-image-body',
  localVideoBody: 'local-video-body',
  onlineAssetsTable: 'online-assets-table',
  batchProgress: 'batch-progress',
  batchProgressText: 'batch-progress-text',
  pauseActionBtn: 'btn-pause-action',
  stopActionBtn: 'btn-stop-action',
  failureDetailsBtn: 'btn-failure-details',
  confirmDialog: 'confirm-dialog',
  confirmMessage: 'confirm-message',
  confirmOk: 'confirm-ok',
  confirmCancel: 'confirm-cancel',
  failureDialog: 'failure-dialog',
  failureList: 'failure-list',
  failureClose: 'failure-close',
  failureRetry: 'failure-retry'
};

function setText(el, text) {
  if (el) el.textContent = text;
}

function resolveOnlineStatus(status) {
  if (status === 'ok') {
    return { text: '连接正常', className: 'text-xs text-green-600 mt-1' };
  }
  if (status === 'no_token') {
    return { text: '无可用 Token', className: 'text-xs text-orange-500 mt-1' };
  }
  if (status === 'not_loaded') {
    return { text: '未加载', className: 'text-xs text-[var(--accents-4)] mt-1' };
  }
  return { text: '无法连接', className: 'text-xs text-red-500 mt-1' };
}

function createIconButton(title, svg, onClick) {
  const btn = document.createElement('button');
  btn.className = 'cache-icon-button';
  btn.title = title;
  btn.innerHTML = svg;
  btn.addEventListener('click', onClick);
  return btn;
}

async function init() {
  apiKey = await ensureAdminKey();
  if (apiKey === null) return;
  cacheUI();
  setupCacheCards();
  setupConfirmDialog();
  setupFailureDialog();
  setupBatchControls();
  await loadStats();
  await showCacheSection('image');
}

function setupCacheCards() {
  if (!ui.cacheCards) return;
  ui.cacheCards.forEach(card => {
    card.addEventListener('click', () => {
      const type = card.getAttribute('data-type');
      if (type) toggleCacheList(type);
    });
  });
}

function cacheUI() {
  Object.entries(UI_MAP).forEach(([key, id]) => {
    ui[key] = byId(id);
  });
  ui.cacheCards = document.querySelectorAll('.cache-card');
}

function ensureUI() {
  if (!ui.batchActions) cacheUI();
}

let confirmResolver = null;

function setupConfirmDialog() {
  const dialog = ui.confirmDialog;
  if (!dialog) return;

  dialog.addEventListener('close', () => {
    if (!confirmResolver) return;
    const ok = dialog.returnValue === 'ok';
    confirmResolver(ok);
    confirmResolver = null;
  });

  dialog.addEventListener('cancel', (event) => {
    event.preventDefault();
    dialog.close('cancel');
  });

  dialog.addEventListener('click', (event) => {
    if (event.target === dialog) {
      dialog.close('cancel');
    }
  });

  if (ui.confirmOk) {
    ui.confirmOk.addEventListener('click', () => dialog.close('ok'));
  }
  if (ui.confirmCancel) {
    ui.confirmCancel.addEventListener('click', () => dialog.close('cancel'));
  }
}

function setupFailureDialog() {
  const dialog = ui.failureDialog;
  if (!dialog) return;
  if (ui.failureClose) {
    ui.failureClose.addEventListener('click', () => dialog.close());
  }
  if (ui.failureRetry) {
    ui.failureRetry.addEventListener('click', () => retryFailed());
  }
  dialog.addEventListener('click', (event) => {
    if (event.target === dialog) {
      dialog.close();
    }
  });
}

function setupBatchControls() {
  if (ui.pauseActionBtn) {
    ui.pauseActionBtn.addEventListener('click', () => togglePause());
  }
  if (ui.stopActionBtn) {
    ui.stopActionBtn.addEventListener('click', () => stopActiveBatch());
  }
  if (ui.failureDetailsBtn) {
    ui.failureDetailsBtn.addEventListener('click', () => showFailureDetails());
  }
}

function confirmAction(message, options = {}) {
  ensureUI();
  const dialog = ui.confirmDialog;
  if (!dialog || typeof dialog.showModal !== 'function') {
    return Promise.resolve(window.confirm(message));
  }
  if (ui.confirmMessage) ui.confirmMessage.textContent = message;
  if (ui.confirmOk) ui.confirmOk.textContent = options.okText || '确定';
  if (ui.confirmCancel) ui.confirmCancel.textContent = options.cancelText || '取消';
  return new Promise(resolve => {
    confirmResolver = resolve;
    dialog.showModal();
  });
}

function formatTime(ms) {
  if (!ms) return '';
  const dt = new Date(ms);
  return dt.toLocaleString('zh-CN', { hour12: false });
}

function calcPercent(processed, total) {
  return total ? Math.floor((processed / total) * 100) : 0;
}

const accountStates = new Map();
let isBatchLoading = false;
let isLoadPaused = false;
let batchQueue = [];
let batchTokens = [];
let batchTotal = 0;
let batchProcessed = 0;
let isBatchDeleting = false;
let isDeletePaused = false;
let deleteTotal = 0;
let deleteProcessed = 0;
let currentBatchTaskId = null;
let batchEventSource = null;

async function loadStats(options = {}) {
  try {
    ensureUI();
    const merge = options.merge === true;
    const silent = options.silent === true;
    const params = new URLSearchParams();
    if (options.tokens && options.tokens.length) {
      params.set('tokens', options.tokens.join(','));
      currentScope = 'selected';
    } else if (options.scope === 'all') {
      params.set('scope', 'all');
      currentScope = 'all';
    } else if (currentToken) {
      params.set('token', currentToken);
      currentScope = 'single';
    } else {
      currentScope = 'none';
    }
    const url = `/v1/admin/cache${params.toString() ? `?${params.toString()}` : ''}`;
    const res = await fetch(url, {
      headers: buildAuthHeaders(apiKey)
    });

    if (res.status === 401) {
      logout();
      return;
    }
    const data = await res.json();
    applyStatsData(data, merge);
    return data;
  } catch (e) {
    if (!silent) showToast('加载统计失败', 'error');
    return null;
  }
}

function applyStatsData(data, merge = false) {
  if (!merge) {
    accountStates.clear();
  }

  setText(ui.imgCount, data.local_image.count);
  setText(ui.imgSize, `${data.local_image.size_mb} MB`);
  setText(ui.videoCount, data.local_video.count);
  setText(ui.videoSize, `${data.local_video.size_mb} MB`);
  setText(ui.onlineCount, data.online.count);

  const online = data.online || {};
  const status = resolveOnlineStatus(online.status);
  setOnlineStatus(status.text, status.className);

  // Update master accounts list
  updateAccountSelect(data.online_accounts || []);

  // Update dynamic states
  const details = Array.isArray(data.online_details) ? data.online_details : [];
  details.forEach(detail => {
    accountStates.set(detail.token, {
      count: detail.count,
      status: detail.status,
      last_asset_clear_at: detail.last_asset_clear_at
    });
  });
  if (online?.token) {
    accountStates.set(online.token, {
      count: online.count,
      status: online.status,
      last_asset_clear_at: online.last_asset_clear_at
    });
  }

  if (data.online_scope === 'all') {
    currentScope = 'all';
    currentToken = '';
  } else if (data.online_scope === 'selected') {
    currentScope = 'selected';
  } else if (online.token) {
    currentScope = 'single';
    currentToken = online.token;
  } else {
    currentScope = 'none';
  }

  const timeText = formatTime(online.last_asset_clear_at);
  setText(ui.onlineLastClear, timeText ? `上次清空:${timeText}` : '');

  renderAccountTable(data);
}

function updateAccountSelect(accounts) {
  accountMap.clear();
  accounts.forEach(account => {
    accountMap.set(account.token, account);
  });
}

function renderAccountTable(data) {
  const tbody = ui.accountTableBody;
  const empty = ui.accountEmpty;
  if (!tbody || !empty) return;

  const details = Array.isArray(data.online_details) ? data.online_details : [];
  const accounts = Array.isArray(data.online_accounts) ? data.online_accounts : [];
  const detailsMap = new Map(details.map(item => [item.token, item]));
  let rows = [];

  if (accounts.length > 0) {
    rows = accounts.map(item => {
      const detail = detailsMap.get(item.token);
      const state = accountStates.get(item.token);
      let count = '-';
      let status = 'not_loaded';
      let last_asset_clear_at = item.last_asset_clear_at;

      if (detail) {
        count = detail.count;
        status = detail.status;
        last_asset_clear_at = detail.last_asset_clear_at ?? last_asset_clear_at;
      } else if (item.token === data.online?.token) {
        count = data.online.count;
        status = data.online.status;
        last_asset_clear_at = data.online.last_asset_clear_at ?? last_asset_clear_at;
      } else if (state) {
        count = state.count;
        status = state.status;
        last_asset_clear_at = state.last_asset_clear_at ?? last_asset_clear_at;
      }

      return {
        token: item.token,
        token_masked: item.token_masked,
        pool: item.pool,
        count,
        status,
        last_asset_clear_at
      };
    });
  } else if (details.length > 0) {
    rows = details.map(item => ({
      token: item.token,
      token_masked: item.token_masked,
      pool: (accountMap.get(item.token) || {}).pool || '-',
      count: item.count,
      status: item.status,
      last_asset_clear_at: item.last_asset_clear_at
    }));
  }

  if (rows.length === 0) {
    tbody.replaceChildren();
    empty.classList.remove('hidden');
    return;
  }

  empty.classList.add('hidden');
  const selected = selectedTokens;
  const fragment = document.createDocumentFragment();
  rows.forEach(row => {
    const tr = document.createElement('tr');
    const isSelected = selected.has(row.token);
    if (isSelected) tr.classList.add('row-selected');

    const tdCheck = document.createElement('td');
    tdCheck.className = 'text-center';
    const checkbox = document.createElement('input');
    checkbox.type = 'checkbox';
    checkbox.className = 'checkbox';
    checkbox.checked = isSelected;
    checkbox.setAttribute('data-token', row.token);
    checkbox.addEventListener('change', () => toggleSelect(row.token, checkbox));
    tdCheck.appendChild(checkbox);

    const tdToken = document.createElement('td');
    tdToken.className = 'text-left';
    const tokenWrap = document.createElement('div');
    tokenWrap.className = 'flex items-center gap-2';
    const tokenText = document.createElement('span');
    tokenText.className = 'font-mono text-xs text-gray-500';
    tokenText.title = row.token;
    tokenText.textContent = row.token_masked || row.token;
    tokenWrap.appendChild(tokenText);
    tdToken.appendChild(tokenWrap);

    const tdPool = document.createElement('td');
    tdPool.className = 'text-center';
    const poolBadge = document.createElement('span');
    poolBadge.className = 'badge badge-gray';
    poolBadge.textContent = row.pool || '-';
    tdPool.appendChild(poolBadge);

    const tdCount = document.createElement('td');
    tdCount.className = 'text-center';
    const countBadge = document.createElement('span');
    countBadge.className = 'badge badge-gray';
    countBadge.textContent = row.count === '-' ? '未加载' : row.count;
    tdCount.appendChild(countBadge);

    const tdLast = document.createElement('td');
    tdLast.className = 'text-left text-xs text-gray-500';
    tdLast.textContent = formatTime(row.last_asset_clear_at) || '-';

    const tdActions = document.createElement('td');
    tdActions.className = 'text-center';
    const actionsWrap = document.createElement('div');
    actionsWrap.className = 'flex items-center justify-center gap-2';
    actionsWrap.appendChild(createIconButton(
      '清空',
      `<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path></svg>`,
      () => clearOnlineCache(row.token)
    ));
    tdActions.appendChild(actionsWrap);

    tr.appendChild(tdCheck);
    tr.appendChild(tdToken);
    tr.appendChild(tdPool);
    tr.appendChild(tdCount);
    tr.appendChild(tdLast);
    tr.appendChild(tdActions);
    fragment.appendChild(tr);
  });
  tbody.replaceChildren(fragment);
  syncSelectAllState();
  updateSelectedCount();
  updateBatchActionsVisibility();
}

async function clearCache(type) {
  const ok = await confirmAction(`确定要清空本地${type === 'image' ? '图片' : '视频'}缓存吗?`, { okText: '清空' });
  if (!ok) return;

  try {
    const res = await fetch('/v1/admin/cache/clear', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        ...buildAuthHeaders(apiKey)
      },
      body: JSON.stringify({ type })
    });

    const data = await res.json();
    if (data.status === 'success') {
      showToast(`清理成功,释放 ${data.result.size_mb} MB`, 'success');
      const state = cacheListState[type];
      if (state) {
        state.items = [];
        state.loaded = true;
      }
      if (selectedLocal[type]) selectedLocal[type].clear();
      if (state && state.visible) {
        renderLocalCacheList(type, []);
      } else {
        syncLocalSelectAllState(type);
        updateSelectedCount();
      }
      loadStats();
    } else {
      showToast('清理失败', 'error');
    }
  } catch (e) {
    showToast('请求失败', 'error');
  }
}

function toggleSelect(token, checkbox) {
  if (checkbox && checkbox.checked) {
    selectedTokens.add(token);
  } else {
    selectedTokens.delete(token);
  }
  if (checkbox) {
    const row = checkbox.closest('tr');
    if (row) row.classList.toggle('row-selected', checkbox.checked);
  }
  syncSelectAllState();
  updateSelectedCount();
}

function toggleSelectAll(checkbox) {
  const shouldSelect = checkbox.checked;
  selectedTokens.clear();
  if (shouldSelect) {
    accountMap.forEach((_, token) => selectedTokens.add(token));
  }
  syncRowCheckboxes();
  updateSelectedCount();
}

function toggleLocalSelect(type, name, checkbox) {
  const set = selectedLocal[type];
  if (!set) return;
  if (checkbox && checkbox.checked) {
    set.add(name);
  } else {
    set.delete(name);
  }
  if (checkbox) {
    const row = checkbox.closest('tr');
    if (row) row.classList.toggle('row-selected', checkbox.checked);
  }
  syncLocalSelectAllState(type);
  updateSelectedCount();
}

function toggleLocalSelectAll(type, checkbox) {
  const set = selectedLocal[type];
  if (!set) return;
  const shouldSelect = checkbox && checkbox.checked;
  set.clear();
  if (shouldSelect) {
    const items = cacheListState[type]?.items || [];
    items.forEach(item => {
      if (item && item.name) set.add(item.name);
    });
  }
  syncLocalRowCheckboxes(type);
  updateSelectedCount();
}

function syncLocalRowCheckboxes(type) {
  const body = type === 'image' ? ui.localImageBody : ui.localVideoBody;
  if (!body) return;
  const set = selectedLocal[type];
  const checkboxes = body.querySelectorAll('input[type="checkbox"].checkbox');
  checkboxes.forEach(cb => {
    const name = cb.getAttribute('data-name');
    if (!name) return;
    cb.checked = set.has(name);
    const row = cb.closest('tr');
    if (row) row.classList.toggle('row-selected', cb.checked);
  });
  syncLocalSelectAllState(type);
}

function syncLocalSelectAllState(type) {
  const selectAll = type === 'image' ? ui.localImageSelectAll : ui.localVideoSelectAll;
  if (!selectAll) return;
  const total = cacheListState[type]?.items?.length || 0;
  const selected = selectedLocal[type]?.size || 0;
  selectAll.checked = total > 0 && selected === total;
  selectAll.indeterminate = selected > 0 && selected < total;
}

function syncRowCheckboxes() {
  const tbody = ui.accountTableBody;
  if (!tbody) return;
  const checkboxes = tbody.querySelectorAll('input[type="checkbox"].checkbox');
  checkboxes.forEach(cb => {
    const token = cb.getAttribute('data-token');
    if (!token) return;
    cb.checked = selectedTokens.has(token);
    const row = cb.closest('tr');
    if (row) row.classList.toggle('row-selected', cb.checked);
  });
}

function syncSelectAllState() {
  const selectAll = ui.selectAll;
  if (!selectAll) return;
  const total = accountMap.size;
  const selected = selectedTokens.size;
  selectAll.checked = total > 0 && selected === total;
  selectAll.indeterminate = selected > 0 && selected < total;
}

function updateSelectedCount() {
  const el = ui.selectedCount;
  const selected = getActiveSelectedSet().size;
  if (el) el.textContent = String(selected);
  setActionButtonsState();
  updateBatchActionsVisibility();
}

function updateBatchActionsVisibility() {
  const bar = ui.batchActions;
  if (!bar) return;
  bar.classList.remove('hidden');
}

function updateLoadButton() {
  const btn = ui.loadBtn;
  if (!btn) return;
  if (currentSection === 'online') {
    btn.textContent = '加载';
    btn.title = '';
  } else {
    btn.textContent = '刷新';
    btn.title = '';
  }
}

function updateDeleteButton() {
  const btn = ui.deleteBtn;
  if (!btn) return;
  if (currentSection === 'online') {
    btn.textContent = '清理';
    btn.title = '';
  } else {
    btn.textContent = '删除';
    btn.title = '';
  }
}


function setActionButtonsState() {
  const loadBtn = ui.loadBtn;
  const deleteBtn = ui.deleteBtn;
  const disabled = isBatchLoading || isBatchDeleting || isLocalDeleting;
  const noSelection = getActiveSelectedSet().size === 0;
  if (loadBtn) {
    if (currentSection === 'online') {
      loadBtn.disabled = disabled || noSelection;
    } else {
      loadBtn.disabled = disabled;
    }
  }
  if (deleteBtn) {
    if (currentSection === 'online') {
      deleteBtn.disabled = disabled || noSelection;
    } else {
      deleteBtn.disabled = disabled || noSelection;
    }
  }
}

function updateBatchProgress() {
  const container = ui.batchProgress;
  if (!container || !ui.batchProgressText) return;
  if (currentSection !== 'online') {
    container.classList.add('hidden');
    if (ui.pauseActionBtn) ui.pauseActionBtn.classList.add('hidden');
    if (ui.stopActionBtn) ui.stopActionBtn.classList.add('hidden');
    return;
  }
  if (!isBatchLoading && !isBatchDeleting) {
    container.classList.add('hidden');
    if (ui.pauseActionBtn) ui.pauseActionBtn.classList.add('hidden');
    if (ui.stopActionBtn) ui.stopActionBtn.classList.add('hidden');
    return;
  }

  const isLoading = isBatchLoading;
  const processed = isLoading ? batchProcessed : deleteProcessed;
  const total = isLoading ? batchTotal : deleteTotal;
  const percent = calcPercent(processed, total);
  ui.batchProgressText.textContent = `${percent}%`;
  container.classList.remove('hidden');

  if (ui.pauseActionBtn) {
    ui.pauseActionBtn.classList.add('hidden');
  }
  if (ui.stopActionBtn) {
    ui.stopActionBtn.classList.remove('hidden');
  }
}

function refreshBatchUI() {
  setActionButtonsState();
  updateBatchActionsVisibility();
  updateBatchProgress();
}

function setOnlineStatus(text, className) {
  const statusEl = ui.onlineStatus;
  if (!statusEl) return;
  statusEl.textContent = text;
  statusEl.className = className;
}

function getActiveSelectedSet() {
  if (currentSection === 'online') return selectedTokens;
  return selectedLocal[currentSection] || new Set();
}

function updateToolbarForSection() {
  updateLoadButton();
  updateDeleteButton();
  updateSelectedCount();
  updateBatchProgress();
}

function updateOnlineCountFromTokens(tokens) {
  let total = 0;
  tokens.forEach(token => {
    const state = accountStates.get(token);
    if (state && typeof state.count === 'number') {
      total += state.count;
    }
  });
  setText(ui.onlineCount, String(total));
}

function formatSize(bytes) {
  if (bytes === 0 || bytes === null || bytes === undefined) return '-';
  const kb = 1024;
  const mb = kb * 1024;
  if (bytes >= mb) return `${(bytes / mb).toFixed(2)} MB`;
  if (bytes >= kb) return `${(bytes / kb).toFixed(1)} KB`;
  return `${bytes} B`;
}

async function showCacheSection(type) {
  ensureUI();
  currentSection = type;
  if (ui.cacheCards) {
    ui.cacheCards.forEach(card => {
      const cardType = card.getAttribute('data-type');
      card.classList.toggle('selected', cardType === type);
    });
  }
  if (type === 'image') {
    cacheListState.image.visible = true;
    cacheListState.video.visible = false;
    if (cacheListState.image.loaded) renderLocalCacheList('image', cacheListState.image.items);
    else await loadLocalCacheList('image');
    if (ui.localCacheLists) ui.localCacheLists.classList.remove('hidden');
    if (ui.localImageList) ui.localImageList.classList.remove('hidden');
    if (ui.localVideoList) ui.localVideoList.classList.add('hidden');
    if (ui.onlineAssetsTable) ui.onlineAssetsTable.classList.add('hidden');
    updateToolbarForSection();
    return;
  }
  if (type === 'video') {
    cacheListState.video.visible = true;
    cacheListState.image.visible = false;
    if (cacheListState.video.loaded) renderLocalCacheList('video', cacheListState.video.items);
    else await loadLocalCacheList('video');
    if (ui.localCacheLists) ui.localCacheLists.classList.remove('hidden');
    if (ui.localVideoList) ui.localVideoList.classList.remove('hidden');
    if (ui.localImageList) ui.localImageList.classList.add('hidden');
    if (ui.onlineAssetsTable) ui.onlineAssetsTable.classList.add('hidden');
    updateToolbarForSection();
    return;
  }
  if (type === 'online') {
    cacheListState.image.visible = false;
    cacheListState.video.visible = false;
    if (ui.localCacheLists) ui.localCacheLists.classList.add('hidden');
    if (ui.localImageList) ui.localImageList.classList.add('hidden');
    if (ui.localVideoList) ui.localVideoList.classList.add('hidden');
    if (ui.onlineAssetsTable) ui.onlineAssetsTable.classList.remove('hidden');
    updateToolbarForSection();
  }
}

async function toggleCacheList(type) {
  await showCacheSection(type);
}

async function loadLocalCacheList(type) {
  const body = type === 'image' ? ui.localImageBody : ui.localVideoBody;
  if (!body) return;
  body.innerHTML = `<tr><td colspan="5">加载中...</td></tr>`;
  try {
    const params = new URLSearchParams({ type, page: '1', page_size: '1000' });
    const res = await fetch(`/v1/admin/cache/list?${params.toString()}`, {
      headers: buildAuthHeaders(apiKey)
    });
    if (!res.ok) {
      body.innerHTML = `<tr><td colspan="5">加载失败</td></tr>`;
      return;
    }
    const data = await res.json();
    const items = Array.isArray(data.items) ? data.items : [];
    cacheListState[type].items = items;
    cacheListState[type].loaded = true;
    const keep = new Set(items.map(item => item.name));
    const selected = selectedLocal[type];
    Array.from(selected).forEach(name => {
      if (!keep.has(name)) selected.delete(name);
    });
    renderLocalCacheList(type, items);
  } catch (e) {
    body.innerHTML = `<tr><td colspan="5">加载失败</td></tr>`;
  }
}

function renderLocalCacheList(type, items) {
  const body = type === 'image' ? ui.localImageBody : ui.localVideoBody;
  if (!body) return;
  if (!items || items.length === 0) {
    body.innerHTML = `<tr><td colspan="5" class="table-empty">暂无文件</td></tr>`;
    syncLocalSelectAllState(type);
    return;
  }
  const selected = selectedLocal[type];
  const fragment = document.createDocumentFragment();
  items.forEach(item => {
    const tr = document.createElement('tr');
    const isSelected = selected.has(item.name);
    if (isSelected) tr.classList.add('row-selected');

    const tdCheck = document.createElement('td');
    tdCheck.className = 'text-center';
    const checkbox = document.createElement('input');
    checkbox.type = 'checkbox';
    checkbox.className = 'checkbox';
    checkbox.checked = isSelected;
    checkbox.setAttribute('data-name', item.name);
    checkbox.onchange = () => toggleLocalSelect(type, item.name, checkbox);
    tdCheck.appendChild(checkbox);

    const tdName = document.createElement('td');
    tdName.className = 'text-left';
    const nameWrap = document.createElement('div');
    nameWrap.className = 'flex items-center gap-2';
    if (item.preview_url) {
      const img = document.createElement('img');
      img.src = item.preview_url;
      img.alt = '';
      img.className = 'cache-preview';
      nameWrap.appendChild(img);
    }
    const nameText = document.createElement('span');
    nameText.className = 'font-mono text-xs text-gray-500';
    nameText.textContent = item.name;
    nameWrap.appendChild(nameText);
    tdName.appendChild(nameWrap);

    const tdSize = document.createElement('td');
    tdSize.className = 'text-left';
    tdSize.textContent = formatSize(item.size_bytes);

    const tdTime = document.createElement('td');
    tdTime.className = 'text-left text-xs text-gray-500';
    tdTime.textContent = formatTime(item.mtime_ms);

    const tdActions = document.createElement('td');
    tdActions.className = 'text-center';
    tdActions.innerHTML = `
      <div class="cache-list-actions">
        <button class="cache-icon-button" onclick="viewLocalFile('${type}', '${item.name}')" title="查看">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M1 12s4-7 11-7 11 7 11 7-4 7-11 7S1 12 1 12z"></path>
            <circle cx="12" cy="12" r="3"></circle>
          </svg>
        </button>
        <button class="cache-icon-button" onclick="deleteLocalFile('${type}', '${item.name}')" title="删除">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <polyline points="3 6 5 6 21 6"></polyline>
            <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
          </svg>
        </button>
      </div>
    `;

    tr.appendChild(tdCheck);
    tr.appendChild(tdName);
    tr.appendChild(tdSize);
    tr.appendChild(tdTime);
    tr.appendChild(tdActions);
    fragment.appendChild(tr);
  });
  body.replaceChildren(fragment);
  syncLocalSelectAllState(type);
  updateSelectedCount();
}

function viewLocalFile(type, name) {
  const safeName = encodeURIComponent(name);
  const url = type === 'image' ? `/v1/files/image/${safeName}` : `/v1/files/video/${safeName}`;
  window.open(url, '_blank');
}

async function deleteLocalFile(type, name) {
  const ok = await confirmAction(`确定要删除该文件吗?`, { okText: '删除' });
  if (!ok) return;
  const okDelete = await requestDeleteLocalFile(type, name);
  if (!okDelete) return;
  showToast('删除成功', 'success');
  const state = cacheListState[type];
  if (state && Array.isArray(state.items)) {
    state.items = state.items.filter(item => item.name !== name);
    state.loaded = true;
    selectedLocal[type]?.delete(name);
    if (state.visible) renderLocalCacheList(type, state.items);
  }
  await loadStats();
}

async function requestDeleteLocalFile(type, name) {
  try {
    const res = await fetch('/v1/admin/cache/item/delete', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        ...buildAuthHeaders(apiKey)
      },
      body: JSON.stringify({ type, name })
    });
    return res.ok;
  } catch (e) {
    return false;
  }
}

async function deleteSelectedLocal(type) {
  const selected = selectedLocal[type];
  const names = selected ? Array.from(selected) : [];
  if (names.length === 0) {
    showToast('未选择文件', 'info');
    return;
  }
  const ok = await confirmAction(`确定要删除选中的 ${names.length} 个文件吗?`, { okText: '删除' });
  if (!ok) return;
  isLocalDeleting = true;
  setActionButtonsState();
  let success = 0;
  let failed = 0;
  const batchSize = 10;
  for (let i = 0; i < names.length; i += batchSize) {
    const chunk = names.slice(i, i + batchSize);
    const results = await Promise.all(chunk.map(name => requestDeleteLocalFile(type, name)));
    results.forEach((ok, idx) => {
      if (ok) {
        success += 1;
      } else {
        failed += 1;
      }
    });
  }
  const state = cacheListState[type];
  if (state && Array.isArray(state.items)) {
    const toRemove = new Set(names);
    state.items = state.items.filter(item => !toRemove.has(item.name));
    state.loaded = true;
  }
  selectedLocal[type].clear();
  if (state && state.visible) renderLocalCacheList(type, state.items);
  await loadStats();
  isLocalDeleting = false;
  setActionButtonsState();
  if (failed === 0) {
    showToast(`已删除 ${success} 个文件`, 'success');
  } else {
    showToast(`删除完成:成功 ${success},失败 ${failed}`, 'info');
  }
}

function handleLoadClick() {
  ensureUI();
  if (isBatchLoading || isBatchDeleting) {
    showToast('当前有任务进行中', 'info');
    return;
  }
  if (currentSection === 'online') {
    loadSelectedAccounts();
  } else {
    loadLocalCacheList(currentSection);
  }
}

function handleDeleteClick() {
  ensureUI();
  if (isBatchLoading || isBatchDeleting) {
    showToast('当前有任务进行中', 'info');
    return;
  }
  if (currentSection === 'online') {
    clearSelectedAccounts();
  } else {
    deleteSelectedLocal(currentSection);
  }
}

function stopBatchLoad(options = {}) {
  if (!isBatchLoading) return;
  isBatchLoading = false;
  isLoadPaused = false;
  currentBatchAction = null;
  batchQueue = [];
  BatchSSE.close(batchEventSource);
  batchEventSource = null;
  currentBatchTaskId = null;
  setOnlineStatus('已终止', 'text-xs text-[var(--accents-4)] mt-1');
  updateLoadButton();
  refreshBatchUI();
  if (!options.silent) showToast('已终止剩余加载请求', 'info');
}

function stopBatchDelete(options = {}) {
  if (!isBatchDeleting) return;
  isBatchDeleting = false;
  isDeletePaused = false;
  currentBatchAction = null;
  batchQueue = [];
  BatchSSE.close(batchEventSource);
  batchEventSource = null;
  currentBatchTaskId = null;
  updateDeleteButton();
  refreshBatchUI();
  if (!options.silent) showToast('已终止剩余清理请求', 'info');
}

function togglePause() {
  if (isBatchLoading || isBatchDeleting) {
    showToast('当前批量任务不支持暂停', 'info');
  }
}

function stopActiveBatch() {
  if (isBatchLoading) {
    BatchSSE.cancel(currentBatchTaskId, apiKey);
    stopBatchLoad();
  } else if (isBatchDeleting) {
    BatchSSE.cancel(currentBatchTaskId, apiKey);
    stopBatchDelete();
  }
}

function getMaskedToken(token) {
  const meta = accountMap.get(token);
  if (meta && meta.token_masked) return meta.token_masked;
  if (!token) return '';
  return token.length > 12 ? `${token.slice(0, 6)}...${token.slice(-4)}` : token;
}

function showFailureDetails() {
  ensureUI();
  const dialog = ui.failureDialog;
  if (!dialog || !ui.failureList) return;
  let action = currentBatchAction || lastBatchAction;
  if (!action) {
    action = deleteFailed.size > 0 ? 'delete' : 'load';
  }
  const failures = action === 'delete' ? deleteFailed : loadFailed;
  ui.failureList.innerHTML = '';
  failures.forEach((reason, token) => {
    const item = document.createElement('div');
    item.className = 'failure-item';
    const tokenEl = document.createElement('div');
    tokenEl.className = 'failure-token';
    tokenEl.textContent = getMaskedToken(token);
    const reasonEl = document.createElement('div');
    reasonEl.textContent = reason;
    item.appendChild(tokenEl);
    item.appendChild(reasonEl);
    ui.failureList.appendChild(item);
  });
  dialog.showModal();
}

function retryFailed() {
  const action = currentBatchAction || lastBatchAction || (deleteFailed.size > 0 ? 'delete' : 'load');
  const failures = action === 'delete' ? deleteFailed : loadFailed;
  const tokens = Array.from(failures.keys());
  if (tokens.length === 0) return;
  if (isBatchLoading || isBatchDeleting) {
    showToast('请等待当前任务结束', 'info');
    return;
  }
  if (ui.failureDialog) ui.failureDialog.close();
  if (action === 'delete') {
    startBatchDelete(tokens);
  } else {
    startBatchLoad(tokens);
  }
}

async function startBatchLoad(tokens) {
  if (isBatchLoading) {
    showToast('正在加载中,请稍候', 'info');
    return;
  }
  if (isBatchDeleting) {
    showToast('正在清理中,请稍候', 'info');
    return;
  }
  if (!tokens || tokens.length === 0) return;
  isBatchLoading = true;
  isLoadPaused = false;
  currentBatchAction = 'load';
  lastBatchAction = 'load';
  loadFailed.clear();
  batchTokens = tokens.slice();
  batchQueue = tokens.slice();
  batchTotal = batchQueue.length;
  batchProcessed = 0;

  batchTokens.forEach(token => accountStates.delete(token));
  updateOnlineCountFromTokens(batchTokens);
  setOnlineStatus('加载中', 'text-xs text-blue-600 mt-1');
  updateLoadButton();
  if (accountMap.size > 0) {
    renderAccountTable({ online_accounts: Array.from(accountMap.values()), online_details: [], online: {} });
  }
  refreshBatchUI();

  try {
    const res = await fetch('/v1/admin/cache/online/load/async', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        ...buildAuthHeaders(apiKey)
      },
      body: JSON.stringify({ tokens })
    });
    const data = await res.json();
    if (!res.ok || data.status !== 'success') {
      throw new Error(data.detail || '请求失败');
    }

    currentBatchTaskId = data.task_id;
    BatchSSE.close(batchEventSource);
    batchEventSource = BatchSSE.open(currentBatchTaskId, apiKey, {
      onMessage: (msg) => {
        if (msg.type === 'snapshot' || msg.type === 'progress') {
          if (typeof msg.total === 'number') batchTotal = msg.total;
          if (typeof msg.processed === 'number') batchProcessed = msg.processed;
          updateBatchProgress();
        } else if (msg.type === 'done') {
          if (typeof msg.total === 'number') batchTotal = msg.total;
          batchProcessed = batchTotal;
          updateBatchProgress();
          const result = msg.result;
          if (result) {
            applyStatsData(result, true);
            const details = Array.isArray(result.online_details) ? result.online_details : [];
            loadFailed.clear();
            details.forEach(detail => {
              if (detail.status !== 'ok') loadFailed.set(detail.token, detail.status);
            });
          }
          finishBatchLoad();
          if (msg.warning) {
            showToast(`加载完成\n⚠️ ${msg.warning}`, 'warning');
          }
          currentBatchTaskId = null;
          BatchSSE.close(batchEventSource);
          batchEventSource = null;
        } else if (msg.type === 'cancelled') {
          stopBatchLoad({ silent: true });
          showToast('已终止加载', 'info');
          currentBatchTaskId = null;
          BatchSSE.close(batchEventSource);
          batchEventSource = null;
        } else if (msg.type === 'error') {
          stopBatchLoad({ silent: true });
          showToast('加载失败: ' + (msg.error || '未知错误'), 'error');
          currentBatchTaskId = null;
          BatchSSE.close(batchEventSource);
          batchEventSource = null;
        }
      },
      onError: () => {
        stopBatchLoad({ silent: true });
        showToast('连接中断', 'error');
        currentBatchTaskId = null;
        BatchSSE.close(batchEventSource);
        batchEventSource = null;
      }
    });
  } catch (e) {
    stopBatchLoad({ silent: true });
    showToast(e.message || '请求失败', 'error');
  }
}

function finishBatchLoad() {
  isBatchLoading = false;
  isLoadPaused = false;
  currentBatchAction = null;
  updateOnlineCountFromTokens(batchTokens);
  const hasError = batchTokens.some(token => {
    const state = accountStates.get(token);
    return !state || (state.status && state.status !== 'ok');
  });
  if (batchTokens.length === 0) {
    setOnlineStatus('未加载', 'text-xs text-[var(--accents-4)] mt-1');
  } else if (hasError) {
    setOnlineStatus('部分异常', 'text-xs text-orange-500 mt-1');
  } else {
    setOnlineStatus('连接正常', 'text-xs text-green-600 mt-1');
  }
  updateLoadButton();
  refreshBatchUI();
}

async function loadSelectedAccounts() {
  if (selectedTokens.size === 0) {
    showToast('请选择要加载的账号', 'error');
    return;
  }
  startBatchLoad(Array.from(selectedTokens));
}

async function loadAllAccounts() {
  const tokens = Array.from(accountMap.keys());
  if (tokens.length === 0) {
    showToast('暂无可用账号', 'error');
    return;
  }
  startBatchLoad(tokens);
}

async function clearSelectedAccounts() {
  if (selectedTokens.size === 0) {
    showToast('请选择要清空的账号', 'error');
    return;
  }
  if (isBatchDeleting) {
    showToast('正在清理中,请稍候', 'info');
    return;
  }
  if (isBatchLoading) {
    showToast('正在加载中,请稍候', 'info');
    return;
  }
  const ok = await confirmAction(`确定要清空选中的 ${selectedTokens.size} 个账号在线资产吗?`, { okText: '清空' });
  if (!ok) return;
  startBatchDelete(Array.from(selectedTokens));
}

async function startBatchDelete(tokens) {
  if (!tokens || tokens.length === 0) return;
  isBatchDeleting = true;
  isDeletePaused = false;
  currentBatchAction = 'delete';
  lastBatchAction = 'delete';
  deleteFailed.clear();
  deleteTotal = tokens.length;
  deleteProcessed = 0;
  batchQueue = tokens.slice();
  showToast('正在批量清理在线资产,请稍候...', 'info');
  updateDeleteButton();
  refreshBatchUI();
  try {
    const res = await fetch('/v1/admin/cache/online/clear/async', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        ...buildAuthHeaders(apiKey)
      },
      body: JSON.stringify({ tokens })
    });
    const data = await res.json();
    if (!res.ok || data.status !== 'success') {
      throw new Error(data.detail || '请求失败');
    }

    currentBatchTaskId = data.task_id;
    BatchSSE.close(batchEventSource);
    batchEventSource = BatchSSE.open(currentBatchTaskId, apiKey, {
      onMessage: (msg) => {
        if (msg.type === 'snapshot' || msg.type === 'progress') {
          if (typeof msg.total === 'number') deleteTotal = msg.total;
          if (typeof msg.processed === 'number') deleteProcessed = msg.processed;
          updateBatchProgress();
        } else if (msg.type === 'done') {
          if (typeof msg.total === 'number') deleteTotal = msg.total;
          deleteProcessed = deleteTotal;
          updateBatchProgress();
          const result = msg.result;
          deleteFailed.clear();
          if (result && result.results) {
            Object.entries(result.results).forEach(([token, res]) => {
              if (res.status !== 'success') {
                deleteFailed.set(token, res.error || '清理失败');
              }
            });
          }
          finishBatchDelete();
          if (msg.warning) {
            showToast(`清理完成\n⚠️ ${msg.warning}`, 'warning');
          }
          currentBatchTaskId = null;
          BatchSSE.close(batchEventSource);
          batchEventSource = null;
        } else if (msg.type === 'cancelled') {
          stopBatchDelete({ silent: true });
          showToast('已终止清理', 'info');
          currentBatchTaskId = null;
          BatchSSE.close(batchEventSource);
          batchEventSource = null;
        } else if (msg.type === 'error') {
          stopBatchDelete({ silent: true });
          showToast('清理失败: ' + (msg.error || '未知错误'), 'error');
          currentBatchTaskId = null;
          BatchSSE.close(batchEventSource);
          batchEventSource = null;
        }
      },
      onError: () => {
        stopBatchDelete({ silent: true });
        showToast('连接中断', 'error');
        currentBatchTaskId = null;
        BatchSSE.close(batchEventSource);
        batchEventSource = null;
      }
    });
  } catch (e) {
    stopBatchDelete({ silent: true });
    showToast(e.message || '请求失败', 'error');
  }
}

function finishBatchDelete() {
  isBatchDeleting = false;
  isDeletePaused = false;
  currentBatchAction = null;
  updateDeleteButton();
  refreshBatchUI();
  showToast('批量清理完成', 'success');
  loadStats();
}

async function clearOnlineCache(targetToken = '', skipConfirm = false) {
  const tokenToClear = targetToken || (currentScope === 'all' ? '' : currentToken);
  if (!tokenToClear) {
    showToast('请选择要清空的账号', 'error');
    return;
  }
  const meta = accountMap.get(tokenToClear);
  const label = meta ? meta.token_masked : tokenToClear;
  if (!skipConfirm) {
    const ok = await confirmAction(`确定要清空账号 ${label} 的在线资产吗?`, { okText: '清空' });
    if (!ok) return;
  }

  showToast('正在清理在线资产,请稍候...', 'info');

  try {
    const res = await fetch('/v1/admin/cache/online/clear', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        ...buildAuthHeaders(apiKey)
      },
      body: JSON.stringify({ token: tokenToClear })
    });

    const data = await res.json();
    if (data.status === 'success') {
      showToast(`清理完成 (成功: ${data.result.success}, 失败: ${data.result.failed})`, 'success');
    } else {
      showToast('清理失败', 'error');
    }
  } catch (e) {
    showToast('请求超时或失败', 'error');
  }
}

window.onload = init;