南开大学自动抢课脚本

使用Codex编写,由Gemini审查,纯AI,无人工

内容放在最后,因为没有找到上传文件的方法,故而直接给出整个脚本内容

样式

特点:

很多,自由探索吧

注意:

国际小学期时创建的,不知道能不能在学期内学科使用,如果不可以让AI改一改就可以

脚本内容

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
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
// ==UserScript==
// @name 南开 EAMS 选课队列助手
// @namespace codex.local
// @version 2.0.0
// @description 支持优先级、并发课程、备选轮转和配置管理的定时选课助手。
// @match https://eamis.nankai.edu.cn/eams/stdElectCourse!defaultPage.action*
// @grant unsafeWindow
// @run-at document-idle
// ==/UserScript==

(function () {
"use strict";

const page = typeof unsafeWindow === "undefined" ? window : unsafeWindow;
const $ = page.jQuery;
const LEGACY_STORAGE_KEY = "codex.nankai.elect.queue.v1";
const STORAGE_PREFIX = "codex.nankai.elect.queue.v2.";
const RECOVERY_PREFIX = "codex.nankai.elect.recovery.v2.";
const DEFAULTS = {
targetTime: "13:00:00",
concurrency: 3,
retryIntervalMs: 500,
maxAttempts: 13,
};

const state = {
armed: false,
running: false,
paused: false,
pauseWaiters: [],
timer: null,
panel: null,
viewportHandler: null,
queue: [],
settings: { ...DEFAULTS },
logs: [],
successes: [],
failureStats: {},
activeGroup: "",
queueSearch: "",
failedGroups: new Set(),
progress: {},
serverClock: {
offsetMs: null,
rttMs: null,
checkedAt: 0,
},
requestStats: {
count: 0,
totalMs: 0,
minMs: null,
maxMs: 0,
lastMs: 0,
consecutiveNetworkErrors: 0,
},
profileId: "",
profileError: "",
};

function discoverProfile() {
const urlProfile = new URLSearchParams(location.search).get("electionProfile.id");
const configProfile = page.electCourseTable?.config?.profileId;
const normalizedUrl = urlProfile ? String(urlProfile) : "";
const normalizedConfig = configProfile ? String(configProfile) : "";
if (
normalizedUrl &&
normalizedConfig &&
normalizedUrl !== normalizedConfig
) {
return {
id: "",
error: `轮次参数冲突:URL=${normalizedUrl},页面配置=${normalizedConfig}`,
};
}
const id = normalizedUrl || normalizedConfig;
return id
? { id, error: "" }
: { id: "", error: "无法从 URL 或页面配置识别选课 profileId" };
}

function storageKey() {
return `${STORAGE_PREFIX}${state.profileId}`;
}

function recoveryKey() {
return `${RECOVERY_PREFIX}${state.profileId}`;
}

function uid() {
return `${Date.now()}-${Math.random().toString(16).slice(2)}`;
}

function lessons() {
return page.electCourseTable?.lessons?.().get?.() || [];
}

function findLesson(query) {
const value = String(query || "").trim().toLowerCase();
if (!value) return null;
return lessons().find((lesson) =>
[lesson.no, lesson.code, lesson.id].some(
(field) => String(field).trim().toLowerCase() === value
)
);
}

function load() {
try {
const key = storageKey();
if (!localStorage.getItem(key) && localStorage.getItem(LEGACY_STORAGE_KEY)) {
localStorage.setItem(key, localStorage.getItem(LEGACY_STORAGE_KEY));
localStorage.removeItem(LEGACY_STORAGE_KEY);
}
const saved = JSON.parse(localStorage.getItem(key));
if (saved?.queue) state.queue = saved.queue;
if (saved?.settings) state.settings = { ...DEFAULTS, ...saved.settings };
if (Array.isArray(saved?.successes)) state.successes = saved.successes;
if (saved?.settings?.maxOpenRetries != null && saved.settings.maxAttempts == null) {
state.settings.maxAttempts = Number(saved.settings.maxOpenRetries) + 1;
}
} catch (error) {
console.warn("[选课助手] 配置读取失败", error);
}

state.queue.forEach((entry) => {
const lesson = page.electCourseTable?.lessons({ id: entry.lessonId }).first();
entry.teacher = entry.teacher || lesson?.teachers || "";
entry.note = entry.note || "";
});
}

function save() {
localStorage.setItem(
storageKey(),
JSON.stringify({
queue: state.queue,
settings: state.settings,
successes: state.successes,
})
);
}

function escapeHtml(value) {
return String(value ?? "")
.replaceAll("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll('"', """)
.replaceAll("'", "'");
}

function cleanHtml(html) {
const box = document.createElement("div");
box.innerHTML = String(html || "");
box.querySelectorAll("script,style,noscript").forEach((node) => node.remove());
return (box.innerText || box.textContent || "").replace(/\s+/g, " ").trim();
}

function classify(text) {
if (/操作\s*成功|选课\s*成功|成功选上/.test(text)) return "success";
if (/当前选课不开放|尚未开始|未到选课时间/.test(text)) return "not-open";
if (/已满|人数.*满|没有余量|名额.*0|超过.*上限/.test(text)) return "full";
if (/已经选过|已选该课|重复选课/.test(text)) return "already";
if (/冲突/.test(text)) return "conflict";
if (/失败|错误|不能|不允许/.test(text)) return "error";
return "unknown";
}

const FAILURE_LABELS = {
"not-open": "未开放",
full: "名额已满",
conflict: "课程冲突",
network: "网络错误",
error: "业务错误",
unknown: "未知结果",
stopped: "任务停止",
};

function log(message, type = "info") {
const stamp = new Date().toLocaleTimeString("zh-CN", { hour12: false });
state.logs.unshift({ stamp, message, type });
state.logs = state.logs.slice(0, 40);
const box = document.querySelector("#codex-elect-log");
if (box) {
box.innerHTML = state.logs
.map(
(item) =>
`<div style="color:${item.type === "ok" ? "#8cff9b" : item.type === "bad" ? "#ff8a8a" : "#d7e8ff"}">[${item.stamp}] ${item.message}</div>`
)
.join("");
}
}

function renderSuccesses() {
const box = document.querySelector("#codex-elect-success-list");
if (!box) return;
if (!state.successes.length) {
box.innerHTML = '<div style="color:#8293a5">暂无成功记录</div>';
return;
}
box.innerHTML = state.successes
.map(
(item) => `
<div style="padding:3px 0;border-bottom:1px dotted #345">
<span style="color:#8cff9b">[${escapeHtml(item.time)}]</span>
${escapeHtml(item.no)} ${escapeHtml(item.teacher)} · ${escapeHtml(item.name)}
<span style="color:#9fb3c8">组 ${escapeHtml(item.group)}</span>
</div>`
)
.join("");
}

function recordSuccess(entry, result) {
state.successes = state.successes.filter(
(item) => Number(item.lessonId) !== Number(entry.lessonId)
);
state.successes.unshift({
lessonId: entry.lessonId,
no: entry.no,
code: entry.code,
name: entry.name,
teacher: entry.teacher,
note: entry.note,
group: entry.group,
priority: entry.priority,
result: result.text || result.kind,
time: new Date().toLocaleString("zh-CN", { hour12: false }),
});
state.successes = state.successes.slice(0, 100);
save();
renderSuccesses();
}

function renderFailureStats() {
const box = document.querySelector("#codex-elect-failure-list");
if (!box) return;
const rows = Object.entries(state.failureStats).filter(([, item]) => item.count > 0);
if (!rows.length) {
box.innerHTML = '<span style="color:#8293a5">暂无失败统计</span>';
return;
}
box.innerHTML = rows
.sort((left, right) => right[1].count - left[1].count)
.map(
([kind, item]) =>
`<span title="${escapeHtml(item.lastText || "")}" style="display:inline-block;margin-right:10px;color:#ffb0a8">${escapeHtml(FAILURE_LABELS[kind] || kind)}:${item.count}</span>`
)
.join("");
}

function recordFailure(result) {
if (result.kind === "success" || result.kind === "already") return;
const current = state.failureStats[result.kind] || { count: 0, lastText: "" };
current.count += 1;
current.lastText = result.text || result.kind;
state.failureStats[result.kind] = current;
renderFailureStats();
}

function waitWhilePaused() {
if (!state.paused || !state.armed) return Promise.resolve();
return new Promise((resolve) => state.pauseWaiters.push(resolve));
}

function releasePauseWaiters() {
const waiters = state.pauseWaiters.splice(0);
waiters.forEach((resolve) => resolve());
}

function setStatus(message, color = "#d7e8ff") {
const node = document.querySelector("#codex-elect-status");
if (node) {
node.textContent = message;
node.style.color = color;
}
}

function updateEntry(uidValue, patch) {
const entry = state.queue.find((item) => item.uid === uidValue);
if (!entry) return;
Object.assign(entry, patch);
save();
renderQueue();
}

function moveEntry(uidValue, direction) {
const index = state.queue.findIndex((item) => item.uid === uidValue);
const next = index + direction;
if (index < 0 || next < 0 || next >= state.queue.length) return;
[state.queue[index], state.queue[next]] = [state.queue[next], state.queue[index]];
save();
renderQueue();
}

function renderQueue() {
const box = document.querySelector("#codex-elect-queue");
const tabs = document.querySelector("#codex-elect-group-tabs");
if (!box) return;
if (!state.queue.length) {
if (tabs) tabs.innerHTML = "";
box.innerHTML = '<div style="color:#ffcc80">队列为空</div>';
return;
}

const groups = [...new Set(state.queue.map((entry) => entry.group))];
if (!groups.includes(state.activeGroup)) state.activeGroup = groups[0];
if (tabs) {
tabs.innerHTML = groups
.map(
(group) =>
`<button data-group-tab="${escapeHtml(group)}" style="${group === state.activeGroup ? "background:#1976d2;color:white" : ""}">${escapeHtml(group)}</button>`
)
.join("");
tabs.querySelectorAll("[data-group-tab]").forEach((button) =>
button.addEventListener("click", () => {
state.activeGroup = button.dataset.groupTab;
renderQueue();
})
);
}

const visibleEntries = state.queue
.map((entry, index) => ({ entry, index }))
.filter(({ entry }) => entry.group === state.activeGroup)
.filter(({ entry }) => {
const search = state.queueSearch.trim().toLowerCase();
if (!search) return true;
return [
entry.no,
entry.code,
entry.name,
entry.teacher,
entry.note,
entry.priority,
].some((value) => String(value || "").toLowerCase().includes(search));
})
.sort((left, right) => left.entry.priority - right.entry.priority || left.index - right.index);

box.innerHTML = visibleEntries.length
? visibleEntries
.map(
({ entry }, index) => `
<div data-drag-uid="${entry.uid}" style="border:1px solid #456;padding:6px;margin-top:5px;border-radius:5px;user-select:text">
<div style="display:flex;gap:6px;align-items:flex-start">
<span draggable="true" data-drag-handle="${entry.uid}" title="拖动排序" style="cursor:grab;user-select:none;padding:0 4px;border:1px solid #567;border-radius:3px"></span>
<div><b>${index + 1}. ${entry.no}</b> ${entry.teacher || "教师未知"} · ${entry.name}</div>
</div>
<div style="display:flex;gap:5px;align-items:center;margin-top:4px">
<label>优先级 <input data-priority="${entry.uid}" type="number" min="1" value="${entry.priority}" style="width:42px"></label>
<label>备选组 <input data-group="${entry.uid}" value="${entry.group}" style="width:45px"></label>
<button data-up="${entry.uid}"></button>
<button data-down="${entry.uid}"></button>
<button data-remove="${entry.uid}">删除</button>
</div>
<input data-note="${entry.uid}" value="${entry.note || ""}" placeholder="备注(如:首选老师/不冲突时选)" style="box-sizing:border-box;width:100%;margin-top:5px">
</div>`
)
.join("")
: '<div style="color:#8293a5;padding:6px">当前组没有匹配课程</div>';

box.querySelectorAll("[data-priority]").forEach((input) =>
input.addEventListener("change", () =>
updateEntry(input.dataset.priority, { priority: Math.max(1, Number(input.value) || 1) })
)
);
box.querySelectorAll("[data-group]").forEach((input) =>
input.addEventListener("change", () =>
updateEntry(input.dataset.group, { group: input.value.trim() || "A" })
)
);
box.querySelectorAll("[data-note]").forEach((input) =>
input.addEventListener("change", () =>
updateEntry(input.dataset.note, { note: input.value.trim() })
)
);
box.querySelectorAll("[data-up]").forEach((button) =>
button.addEventListener("click", () => moveEntry(button.dataset.up, -1))
);
box.querySelectorAll("[data-down]").forEach((button) =>
button.addEventListener("click", () => moveEntry(button.dataset.down, 1))
);
box.querySelectorAll("[data-remove]").forEach((button) =>
button.addEventListener("click", () => {
state.queue = state.queue.filter((item) => item.uid !== button.dataset.remove);
save();
renderQueue();
})
);

let draggedUid = null;
box.querySelectorAll("[data-drag-handle]").forEach((handle) => {
const card = handle.closest("[data-drag-uid]");
handle.addEventListener("dragstart", (event) => {
draggedUid = handle.dataset.dragHandle;
card.style.opacity = "0.45";
event.dataTransfer.effectAllowed = "move";
event.dataTransfer.setData("text/plain", draggedUid);
});
handle.addEventListener("dragend", () => {
draggedUid = null;
card.style.opacity = "";
box.querySelectorAll("[data-drag-uid]").forEach((item) => {
item.style.borderTopColor = "#456";
item.style.borderBottomColor = "#456";
});
});
});
box.querySelectorAll("[data-drag-uid]").forEach((card) => {
card.addEventListener("dragover", (event) => {
if (!draggedUid) return;
event.preventDefault();
if (!draggedUid || draggedUid === card.dataset.dragUid) return;
const after = event.clientY > card.getBoundingClientRect().top + card.offsetHeight / 2;
card.style.borderTopColor = after ? "#456" : "#42a5f5";
card.style.borderBottomColor = after ? "#42a5f5" : "#456";
});
card.addEventListener("dragleave", () => {
card.style.borderTopColor = "#456";
card.style.borderBottomColor = "#456";
});
card.addEventListener("drop", (event) => {
event.preventDefault();
const sourceUid = draggedUid || event.dataTransfer.getData("text/plain");
const sourceIndex = state.queue.findIndex((item) => item.uid === sourceUid);
let targetIndex = state.queue.findIndex((item) => item.uid === card.dataset.dragUid);
if (sourceIndex < 0 || targetIndex < 0 || sourceIndex === targetIndex) return;
const after = event.clientY > card.getBoundingClientRect().top + card.offsetHeight / 2;
const [moved] = state.queue.splice(sourceIndex, 1);
if (sourceIndex < targetIndex) targetIndex -= 1;
state.queue.splice(targetIndex + (after ? 1 : 0), 0, moved);
save();
renderQueue();
});
});
}

function renderProgress() {
const box = document.querySelector("#codex-elect-progress");
if (!box) return;
const groups = [...new Set(state.queue.map((entry) => entry.group))];
if (!groups.length) {
box.textContent = "暂无执行进度";
return;
}
const totalDone = Object.values(state.progress).reduce(
(sum, item) => sum + (item.attempt || 0),
0
);
const taskCount = new Set(
state.queue.map((entry) => `${entry.group}\u0000${entry.priority}`)
).size;
const totalMax = taskCount * state.settings.maxAttempts;
box.innerHTML = [
`<div>总进度:${totalDone}/${totalMax}</div>`,
...groups.map((group) => {
const item = state.progress[group] || { attempt: 0, status: "等待" };
const priorityCount = new Set(
state.queue
.filter((entry) => entry.group === group)
.map((entry) => entry.priority)
).size;
return `<span style="display:inline-block;margin-right:10px">组 ${escapeHtml(group)}:${item.attempt}/${priorityCount * state.settings.maxAttempts} ${escapeHtml(item.status)}</span>`;
}),
].join("");
}

function renderRequestStats() {
const box = document.querySelector("#codex-elect-request-stats");
if (!box) return;
const stats = state.requestStats;
const average = stats.count ? stats.totalMs / stats.count : 0;
box.textContent = stats.count
? `请求 ${stats.count} 次|最近 ${stats.lastMs.toFixed(0)}ms|平均 ${average.toFixed(0)}ms|最小 ${(stats.minMs || 0).toFixed(0)}ms|最大 ${stats.maxMs.toFixed(0)}ms`
: "暂无请求延迟数据";
}

function renderServerClock() {
const box = document.querySelector("#codex-elect-server-clock");
if (!box) return;
const clock = state.serverClock;
if (clock.offsetMs == null) {
box.textContent = "服务器时间:校准中";
return;
}
const direction = clock.offsetMs >= 0 ? "快" : "慢";
box.textContent = `服务器时间比本机${direction} ${Math.abs(clock.offsetMs).toFixed(0)}ms(校准 RTT ${clock.rttMs.toFixed(0)}ms)`;
}

async function calibrateServerClock() {
try {
const startedAt = Date.now();
const response = await fetch(`${location.pathname}${location.search}`, {
method: "HEAD",
cache: "no-store",
credentials: "same-origin",
});
const endedAt = Date.now();
const dateHeader = response.headers.get("date");
if (!dateHeader) throw new Error("响应没有 Date 头");
const serverMs = Date.parse(dateHeader);
if (!Number.isFinite(serverMs)) throw new Error("Date 头无效");
state.serverClock = {
offsetMs: serverMs - (startedAt + endedAt) / 2,
rttMs: endedAt - startedAt,
checkedAt: endedAt,
};
} catch (error) {
state.serverClock = { offsetMs: null, rttMs: null, checkedAt: Date.now() };
console.warn("[选课助手] 服务器时间校准失败", error);
}
renderServerClock();
}

function addCourse() {
const query = document.querySelector("#codex-elect-course").value;
const lesson = findLesson(query);
if (!lesson) {
setStatus("找不到课程:请输入精确课程序号、课程代码或 lessonId", "#ff8a8a");
return;
}
if (state.queue.some((item) => item.lessonId === lesson.id)) {
setStatus("该教学班已在队列中", "#ffcc80");
return;
}

state.queue.push({
uid: uid(),
lessonId: lesson.id,
no: lesson.no,
code: lesson.code,
name: lesson.name || page.electCourseTable.courseI18NMap[`ci${lesson.courseId}`] || "",
teacher: lesson.teachers || "",
note: document.querySelector("#codex-elect-note").value.trim(),
priority: Math.max(1, Number(document.querySelector("#codex-elect-priority").value) || 1),
group: document.querySelector("#codex-elect-group").value.trim() || "A",
});
save();
renderQueue();
setStatus(`已添加 ${lesson.no} ${lesson.code}`, "#8cff9b");
}

function weekStateOverlaps(left, right) {
const length = Math.min(String(left || "").length, String(right || "").length);
for (let index = 0; index < length; index += 1) {
if (left[index] === "1" && right[index] === "1") return true;
}
return false;
}

function lessonsConflict(left, right) {
return (left.arrangeInfo || []).some((a) =>
(right.arrangeInfo || []).some(
(b) =>
a.weekDay === b.weekDay &&
a.startUnit <= b.endUnit &&
b.startUnit <= a.endUnit &&
weekStateOverlaps(a.weekState, b.weekState)
)
);
}

function validateQueue() {
const problems = [];
if (!state.queue.length) problems.push("队列为空");

for (const entry of state.queue) {
const lesson = page.electCourseTable?.lessons({ id: entry.lessonId }).first();
if (!lesson) problems.push(`${entry.no} 不在当前页面课程数据中`);
if (lesson?.elected || lesson?.defaultElected) problems.push(`${entry.no} 已处于选中状态`);
const conflicts = lesson ? page.electCourseTable.checkConflict(lesson) : null;
if (conflicts?.length) problems.push(`${entry.no} 与已选课程时间冲突`);
}

for (let leftIndex = 0; leftIndex < state.queue.length; leftIndex += 1) {
for (let rightIndex = leftIndex + 1; rightIndex < state.queue.length; rightIndex += 1) {
const leftEntry = state.queue[leftIndex];
const rightEntry = state.queue[rightIndex];
if (
leftEntry.priority !== rightEntry.priority ||
leftEntry.group === rightEntry.group
) {
continue;
}
const leftLesson = page.electCourseTable?.lessons({ id: leftEntry.lessonId }).first();
const rightLesson = page.electCourseTable?.lessons({ id: rightEntry.lessonId }).first();
if (leftLesson && rightLesson && lessonsConflict(leftLesson, rightLesson)) {
problems.push(
`并发冲突:${leftEntry.no}(组 ${leftEntry.group})与 ${rightEntry.no}(组 ${rightEntry.group})时间重叠`
);
}
}
}
return problems;
}

function looksLoggedOut(text, responseURL = "") {
return (
/login|sso|auth/i.test(responseURL) ||
/统一身份认证|用户登录|登录已失效|请重新登录/.test(text) ||
/<form[^>]+(?:login|password)/i.test(text)
);
}

function scheduleRecovery(reason) {
if (sessionStorage.getItem(recoveryKey())) return;
sessionStorage.setItem(
recoveryKey(),
JSON.stringify({ time: Date.now(), resume: state.armed || state.running, reason })
);
state.paused = true;
setStatus(`${reason},2 秒后自动刷新`, "#ff8a8a");
log(`${reason},准备自动刷新`, "bad");
setTimeout(() => page.location.reload(), 2000);
}

function installConnectionWatch() {
page.addEventListener("offline", () => {
sessionStorage.setItem(
recoveryKey(),
JSON.stringify({
time: Date.now(),
resume: state.armed || state.running,
reason: "浏览器离线",
})
);
state.paused = true;
updatePauseButton();
setStatus("网络已断开,联网后自动刷新", "#ff8a8a");
log("浏览器检测到离线,任务已暂停", "bad");
});
page.addEventListener("online", () => {
if (sessionStorage.getItem(recoveryKey())) page.location.reload();
});
}

function resumeRecoveryIfNeeded() {
try {
const recovery = JSON.parse(sessionStorage.getItem(recoveryKey()));
sessionStorage.removeItem(recoveryKey());
if (!recovery || Date.now() - recovery.time > 120000 || !recovery.resume) return;
state.armed = true;
state.paused = false;
updatePauseButton();
setStatus(`已从“${recovery.reason}”刷新恢复,继续执行`, "#8cff9b");
log(`自动刷新后恢复任务:${recovery.reason}`, "ok");
setTimeout(executeQueue, 300);
} catch {
sessionStorage.removeItem(recoveryKey());
}
}

async function verifyElected(entry) {
try {
const response = await fetch(`${location.pathname}${location.search}`, {
cache: "no-store",
credentials: "same-origin",
});
const html = await response.text();
if (looksLoggedOut(html, response.url)) {
scheduleRecovery("登录状态失效");
return false;
}
const pattern = new RegExp(
`electedIds\\[["']l${Number(entry.lessonId)}["']\\]\\s*=\\s*true`
);
const verified = pattern.test(html);
if (verified) {
page.electCourseTable
?.lessons({ id: Number(entry.lessonId) })
.update({ elected: true, defaultElected: true });
page.electCourseTable?.init();
log(`${entry.no} 已从服务器核验为“已选”`, "ok");
} else {
log(`${entry.no} 成功响应后服务器核验未发现已选状态`, "bad");
}
return verified;
} catch (error) {
log(`${entry.no} 核验失败:${error.message}`, "bad");
return false;
}
}

function submitLesson(entry) {
return new Promise((resolve) => {
const currentProfile = discoverProfile();
if (
currentProfile.error ||
!currentProfile.id ||
currentProfile.id !== state.profileId
) {
resolve({
kind: "error",
text:
currentProfile.error ||
`选课轮次已变化:原 ${state.profileId},当前 ${currentProfile.id || "未知"}`,
});
return;
}
const startedAt = performance.now();
$.ajax({
type: "POST",
url: `/eams/stdElectCourse!batchOperator.action?profileId=${encodeURIComponent(state.profileId)}`,
data: {
optype: true,
operator0: `${entry.lessonId}:true:0`,
lesson0: entry.lessonId,
[`expLessonGroup_${entry.lessonId}`]: "undefined",
},
timeout: 10000,
})
.done((html, _status, xhr) => {
const elapsedMs = performance.now() - startedAt;
const stats = state.requestStats;
stats.count += 1;
stats.totalMs += elapsedMs;
stats.lastMs = elapsedMs;
stats.minMs = stats.minMs == null ? elapsedMs : Math.min(stats.minMs, elapsedMs);
stats.maxMs = Math.max(stats.maxMs, elapsedMs);
stats.consecutiveNetworkErrors = 0;
renderRequestStats();
const text = cleanHtml(html);
if (looksLoggedOut(String(html), xhr.responseURL)) {
scheduleRecovery("登录状态失效");
resolve({ kind: "network", text: "登录状态失效", elapsedMs });
return;
}
resolve({ kind: classify(text), text, elapsedMs });
})
.fail((xhr, status) => {
const elapsedMs = performance.now() - startedAt;
const stats = state.requestStats;
stats.count += 1;
stats.totalMs += elapsedMs;
stats.lastMs = elapsedMs;
stats.minMs = stats.minMs == null ? elapsedMs : Math.min(stats.minMs, elapsedMs);
stats.maxMs = Math.max(stats.maxMs, elapsedMs);
stats.consecutiveNetworkErrors += 1;
renderRequestStats();
if (stats.consecutiveNetworkErrors >= 3) {
scheduleRecovery("连续 3 次无法连接服务器");
}
resolve({
kind: "network",
text: `HTTP ${xhr.status || 0} ${status}`,
elapsedMs,
});
});
});
}

async function runFallbackGroup(entries) {
const group = entries[0].group;
const baseAttempt = state.progress[group]?.attempt || 0;
state.progress[group] = { attempt: baseAttempt, status: "执行中" };
renderProgress();
for (let attempt = 0; attempt < state.settings.maxAttempts && state.armed; attempt += 1) {
await waitWhilePaused();
if (!state.armed) return false;
const entry = entries[attempt % entries.length];
state.progress[group] = {
attempt: baseAttempt + attempt + 1,
status: `优先级 ${entry.priority} / ${entry.no} 请求中`,
};
renderProgress();
log(
`组 ${entry.group} 第 ${attempt + 1}/${state.settings.maxAttempts} 次:${entry.no} ${entry.teacher}${entry.note ? `(${entry.note})` : ""}`
);
const result = await submitLesson(entry);
recordFailure(result);
log(`${entry.no}:${result.text || result.kind}`, result.kind === "success" ? "ok" : "info");
if (result.kind === "success" || result.kind === "already") {
state.progress[group].status = "核验中";
renderProgress();
if (await verifyElected(entry)) {
state.failedGroups.delete(group);
recordSuccess(entry, result);
state.progress[group].status = "成功";
renderProgress();
log(`备选组 ${entry.group} 已完成,停止该组后续课程`, "ok");
return true;
}
}
if (attempt + 1 < state.settings.maxAttempts) {
const next = entries[(attempt + 1) % entries.length];
log(`${entry.no} 未成功,${state.settings.retryIntervalMs}ms 后切换 ${next.no}`);
await new Promise((resolve) => setTimeout(resolve, state.settings.retryIntervalMs));
await waitWhilePaused();
}
}
state.progress[group] = {
attempt: baseAttempt + state.settings.maxAttempts,
status: state.armed ? "失败" : "停止",
};
if (state.armed) state.failedGroups.add(group);
renderProgress();
log(`备选组 ${entries[0].group} 已用完 ${state.settings.maxAttempts} 次尝试`, "bad");
return false;
}

async function runLimited(tasks, limit) {
let cursor = 0;
const workers = Array.from({ length: Math.min(limit, tasks.length) }, async () => {
while (cursor < tasks.length && state.armed) {
await waitWhilePaused();
if (!state.armed) break;
const task = tasks[cursor++];
await task();
}
});
await Promise.all(workers);
}

async function executeQueue(sourceQueue = state.queue) {
if (state.running || !state.armed) return;
state.running = true;
updateRetryFailedButton();
clearInterval(state.timer);
setStatus("正在执行选课队列", "#ffdf80");
const completedGroups = new Set();

const priorities = [...new Set(sourceQueue.map((entry) => entry.priority))].sort((a, b) => a - b);
for (const priority of priorities) {
await waitWhilePaused();
if (!state.armed) break;
const skipped = sourceQueue.filter(
(entry) => entry.priority === priority && completedGroups.has(entry.group)
);
for (const entry of skipped) {
log(`跳过 ${entry.no}:关联组 ${entry.group} 已在更高优先级成功`, "ok");
}
const tier = sourceQueue.filter(
(entry) => entry.priority === priority && !completedGroups.has(entry.group)
);
const groups = new Map();
for (const entry of tier) {
if (!groups.has(entry.group)) groups.set(entry.group, []);
groups.get(entry.group).push(entry);
}
log(`开始优先级 ${priority},${groups.size} 个课程组`);
await runLimited(
[...groups.entries()].map(([group, entries]) => async () => {
if (await runFallbackGroup(entries)) completedGroups.add(group);
}),
state.settings.concurrency
);
}

state.running = false;
state.armed = false;
state.paused = false;
updatePauseButton();
updateRetryFailedButton();
setStatus("队列执行结束,请核对已选课程", "#8cff9b");
log("全部优先级执行结束,请在“已选课程”中核对结果", "ok");
}

function targetTimestamp() {
const [hour, minute, second] = state.settings.targetTime.split(":").map(Number);
const target = new Date();
target.setHours(hour, minute, second, 0);
return target.getTime();
}

function normalizeTime(value) {
const match = String(value || "")
.trim()
.match(/^(\d{1,2}):(\d{1,2})(?::(\d{1,2}))?$/);
if (!match) return null;
const hour = Number(match[1]);
const minute = Number(match[2]);
const second = Number(match[3] || 0);
if (hour > 23 || minute > 59 || second > 59) return null;
return [hour, minute, second].map((item) => String(item).padStart(2, "0")).join(":");
}

function buildQueuePreview(sourceQueue = state.queue, title = "执行前队列预览") {
const priorities = [...new Set(sourceQueue.map((entry) => entry.priority))].sort(
(left, right) => left - right
);
const lines = [
title,
"",
`时间:${state.settings.targetTime}`,
`并发:${state.settings.concurrency}`,
`每组尝试:${state.settings.maxAttempts} 次`,
`轮转间隔:${state.settings.retryIntervalMs} ms`,
"",
];
for (const priority of priorities) {
lines.push(`优先级 ${priority}`);
const groups = new Map();
sourceQueue
.filter((entry) => entry.priority === priority)
.forEach((entry) => {
if (!groups.has(entry.group)) groups.set(entry.group, []);
groups.get(entry.group).push(entry);
});
for (const [group, entries] of groups) {
lines.push(` 组 ${group}:`);
entries.forEach((entry, index) => {
lines.push(
` ${index + 1}. ${entry.no} ${entry.teacher} · ${entry.name}${entry.note ? `(${entry.note})` : ""}`
);
});
}
}
lines.push("", "确认按以上队列启动吗?");
return lines.join("\n");
}

function arm() {
const real = document.querySelector("#codex-elect-real").checked;
if (!real) {
setStatus("请先勾选允许真实提交", "#ff8a8a");
return;
}
const currentProfile = discoverProfile();
if (
currentProfile.error ||
!currentProfile.id ||
currentProfile.id !== state.profileId
) {
setStatus(
currentProfile.error ||
`选课轮次已变化:原 ${state.profileId},当前 ${currentProfile.id || "未知"}`,
"#ff8a8a"
);
return;
}
const problems = validateQueue();
if (problems.length) {
log(`检查提醒:${problems.join(";")}`, "bad");
if (!page.confirm(`发现以下提醒:\n${problems.join("\n")}\n\n仍要启动吗?`)) return;
}

const normalizedTime = normalizeTime(
document.querySelector("#codex-elect-time-text").value
);
if (!normalizedTime) {
setStatus("时间格式无效,请输入 HH:MM 或 HH:MM:SS", "#ff8a8a");
return;
}
state.settings.targetTime = normalizedTime;
document.querySelector("#codex-elect-time-text").value = normalizedTime;
state.settings.concurrency = Math.max(
1,
Math.floor(Number(document.querySelector("#codex-elect-concurrency").value) || 1)
);
state.settings.maxAttempts = Math.min(
100,
Math.max(1, Number(document.querySelector("#codex-elect-attempts").value) || 1)
);
state.settings.retryIntervalMs = Math.min(
10000,
Math.max(50, Number(document.querySelector("#codex-elect-interval").value) || 500)
);
if (!page.confirm(buildQueuePreview())) {
setStatus("已取消启动", "#ffcc80");
return;
}
state.failureStats = {};
state.failedGroups = new Set();
renderFailureStats();
save();
state.armed = true;
state.paused = false;
state.progress = {};
state.requestStats = {
count: 0,
totalMs: 0,
minMs: null,
maxMs: 0,
lastMs: 0,
consecutiveNetworkErrors: 0,
};
renderProgress();
renderRequestStats();
updatePauseButton();
updateRetryFailedButton();
const target = targetTimestamp();
if (Date.now() >= target) {
executeQueue();
return;
}

clearInterval(state.timer);
state.timer = setInterval(() => {
const remaining = target - Date.now();
if (state.paused) {
setStatus("已暂停倒计时,恢复后继续", "#ffcc80");
} else if (remaining <= 0) {
executeQueue();
} else {
setStatus(`已武装,距离 ${state.settings.targetTime} 还有 ${(remaining / 1000).toFixed(1)} 秒`);
}
}, 100);
}

function stop() {
state.armed = false;
state.paused = false;
clearInterval(state.timer);
releasePauseWaiters();
updatePauseButton();
setStatus("已停止;已发出的请求无法撤回", "#ffcc80");
log("用户停止任务");
}

function updateRetryFailedButton() {
const button = document.querySelector("#codex-elect-retry-failed");
if (!button) return;
button.disabled = state.running || state.armed || state.failedGroups.size === 0;
button.textContent = state.failedGroups.size
? `重跑失败组(${state.failedGroups.size})`
: "重跑失败组";
}

function retryFailedGroups() {
if (state.running || state.armed) {
setStatus("当前任务仍在运行", "#ffcc80");
return;
}
const retryQueue = state.queue.filter((entry) => state.failedGroups.has(entry.group));
if (!retryQueue.length) {
setStatus("本轮没有失败组", "#ffcc80");
return;
}
if (
!page.confirm(
buildQueuePreview(retryQueue, `重新执行本轮失败组:${[...state.failedGroups].join("、")}`)
)
) {
return;
}
state.armed = true;
state.paused = false;
state.progress = {};
updatePauseButton();
updateRetryFailedButton();
setStatus("正在重新执行失败组", "#ffdf80");
executeQueue(retryQueue);
}

function updatePauseButton() {
const button = document.querySelector("#codex-elect-pause");
if (!button) return;
button.textContent = state.paused ? "恢复" : "暂停";
button.disabled = !state.armed && !state.running;
}

function togglePause() {
if (!state.armed && !state.running) {
setStatus("当前没有可暂停的任务", "#ffcc80");
return;
}
state.paused = !state.paused;
updatePauseButton();
if (state.paused) {
setStatus("已暂停;当前请求完成后不再发出新请求", "#ffcc80");
log("任务已暂停");
} else {
releasePauseWaiters();
setStatus(state.running ? "已恢复执行" : "已恢复倒计时", "#8cff9b");
log("任务已恢复", "ok");
if (!state.running && Date.now() >= targetTimestamp()) executeQueue();
}
}

function exportConfig() {
const data = {
version: 1,
exportedAt: new Date().toISOString(),
queue: state.queue,
settings: state.settings,
successes: state.successes,
};
const blob = new Blob([JSON.stringify(data, null, 2)], {
type: "application/json;charset=utf-8",
});
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = `nankai-elect-config-${new Date().toISOString().slice(0, 10)}.json`;
link.click();
setTimeout(() => URL.revokeObjectURL(url), 1000);
setStatus("配置已导出", "#8cff9b");
}

async function importConfig(file) {
try {
const parsed = JSON.parse(await file.text());
if (!Array.isArray(parsed.queue) || !parsed.settings || typeof parsed.settings !== "object") {
throw new Error("缺少 queue 或 settings");
}
const queue = parsed.queue.map((entry) => {
if (!Number.isFinite(Number(entry.lessonId)) || !entry.no || !entry.group) {
throw new Error("课程条目字段不完整");
}
return {
uid: entry.uid || uid(),
lessonId: Number(entry.lessonId),
no: String(entry.no),
code: String(entry.code || ""),
name: String(entry.name || ""),
teacher: String(entry.teacher || ""),
note: String(entry.note || ""),
priority: Math.max(1, Number(entry.priority) || 1),
group: String(entry.group || "A"),
};
});
state.queue = queue;
state.settings = { ...DEFAULTS, ...parsed.settings };
state.successes = Array.isArray(parsed.successes) ? parsed.successes : [];
state.failureStats = {};
save();
createPanel();
setStatus(`已导入 ${queue.length} 门课程`, "#8cff9b");
log("配置导入成功", "ok");
} catch (error) {
setStatus(`配置导入失败:${error.message}`, "#ff8a8a");
}
}

function viewportSize() {
return {
width: page.visualViewport?.width || page.innerWidth,
height: page.visualViewport?.height || page.innerHeight,
};
}

function savePanelRect(panel) {
if (state.settings.panelCollapsed) return;
const rect = panel.getBoundingClientRect();
state.settings.panelRect = {
left: rect.left,
top: rect.top,
width: rect.width,
height: rect.height,
};
save();
}

function constrainPanel(panel, persist = false) {
const viewport = viewportSize();
const margin = 8;
const collapsed = Boolean(state.settings.panelCollapsed);

if (!collapsed) {
const width = Math.min(panel.getBoundingClientRect().width, Math.max(280, viewport.width - margin * 2));
const height = Math.min(panel.getBoundingClientRect().height, Math.max(180, viewport.height - margin * 2));
panel.style.width = `${width}px`;
panel.style.height = `${height}px`;
}

const rect = panel.getBoundingClientRect();
const maxLeft = Math.max(margin, viewport.width - rect.width - margin);
const maxTop = Math.max(margin, viewport.height - rect.height - margin);
panel.style.left = `${Math.min(Math.max(margin, rect.left), maxLeft)}px`;
panel.style.top = `${Math.min(Math.max(margin, rect.top), maxTop)}px`;
panel.style.right = "auto";

if (persist && !collapsed) savePanelRect(panel);
}

function setPanelCollapsed(panel, collapsed) {
const body = panel.querySelector("#codex-elect-body");
const button = panel.querySelector("#codex-elect-collapse");
if (collapsed) {
savePanelRect(panel);
state.settings.panelCollapsed = true;
body.style.display = "none";
button.textContent = "展开";
panel.style.resize = "none";
panel.style.minHeight = "0";
panel.style.height = "46px";
panel.style.overflow = "hidden";
} else {
state.settings.panelCollapsed = false;
body.style.display = "flex";
button.textContent = "收起";
panel.style.resize = "both";
panel.style.minHeight = "220px";
panel.style.overflow = "hidden";
const rect = state.settings.panelRect || {};
panel.style.width = `${Math.max(330, Number(rect.width) || 410)}px`;
panel.style.height = `${Math.max(220, Number(rect.height) || 620)}px`;
}
constrainPanel(panel);
save();
}

function createPanel() {
document.querySelector("#codex-elect-panel")?.remove();
const panel = document.createElement("section");
panel.id = "codex-elect-panel";
panel.style.cssText = [
"position:fixed", "right:14px", "top:62px", "z-index:2147483647",
"width:410px", "height:620px", "min-width:330px", "min-height:220px",
"max-width:95vw", "max-height:90vh", "resize:both", "overflow:hidden", "padding:12px",
"box-sizing:border-box",
"border:1px solid #2997ff", "border-radius:8px", "background:#101820f2",
"color:#fff", "font:13px/1.45 sans-serif", "box-shadow:0 6px 24px #0009",
].join(";");
if (state.settings.panelRect) {
const rect = state.settings.panelRect;
panel.style.left = `${Math.max(0, rect.left)}px`;
panel.style.top = `${Math.max(0, rect.top)}px`;
panel.style.right = "auto";
panel.style.width = `${Math.max(330, rect.width)}px`;
panel.style.height = `${Math.max(220, rect.height)}px`;
}
panel.innerHTML = `
<div id="codex-elect-handle" style="display:flex;justify-content:space-between;cursor:move;user-select:none">
<b>南开 EAMS 选课队列助手 v2.0</b>
<button id="codex-elect-collapse">收起</button>
</div>
<div id="codex-elect-body" style="height:calc(100% - 30px);display:flex;flex-direction:column;min-height:0">
<div id="codex-elect-controls" style="flex:0 0 auto">
<div style="margin-top:5px;color:#9fd3ff">当前选课轮次 profileId:<b>${escapeHtml(state.profileId)}</b></div>
<div style="margin-top:8px;display:grid;grid-template-columns:minmax(150px,1fr) 54px 54px 54px;gap:5px">
<input id="codex-elect-course" placeholder="课程序号/课程代码/lessonId">
<input id="codex-elect-priority" type="number" min="1" value="1" title="优先级">
<input id="codex-elect-group" value="A" title="备选组">
<button id="codex-elect-add">添加</button>
</div>
<input id="codex-elect-note" placeholder="备注(可选)" style="box-sizing:border-box;width:100%;margin-top:5px">
<div style="color:#9fb3c8;margin-top:4px">每个备选组使用独立标签页,组内按优先级显示。</div>
<div style="color:#ffd180;margin-top:3px">备选组:组名相同表示互为备选,任一请求未成功就切换下一门;达到组尾后循环。组名不同且优先级相同可并发。</div>
<input id="codex-elect-search" type="search" placeholder="筛选当前组:序号/代码/课程/教师/备注/优先级" style="box-sizing:border-box;width:100%;margin-top:5px">
<div id="codex-elect-group-tabs" style="display:flex;gap:5px;flex-wrap:wrap;margin-top:5px"></div>
<div id="codex-elect-queue" style="max-height:38vh;overflow:auto"></div>
<div style="display:flex;gap:7px;align-items:center;flex-wrap:wrap;margin-top:9px">
<label style="display:flex;align-items:center;gap:3px">
时间
<input id="codex-elect-time-text" type="text" inputmode="numeric" value="${state.settings.targetTime}" placeholder="HH:MM:SS" style="width:74px">
<button id="codex-elect-time-pick" type="button" title="选择时间">选择</button>
<input id="codex-elect-time-picker" type="time" step="1" value="${state.settings.targetTime}" style="position:absolute;opacity:0;pointer-events:none;width:1px;height:1px">
</label>
<label>并发 <input id="codex-elect-concurrency" type="number" min="1" value="${state.settings.concurrency}" style="width:46px"></label>
<label>尝试 <input id="codex-elect-attempts" type="number" min="1" max="100" value="${state.settings.maxAttempts}" style="width:45px"></label>
<label>间隔 <input id="codex-elect-interval" type="number" min="50" max="10000" step="50" value="${state.settings.retryIntervalMs}" style="width:65px"> ms</label>
</div>
<label style="display:block;margin-top:7px;color:#ffd180">
<input id="codex-elect-real" type="checkbox" checked> 允许真实提交
</label>
<div style="display:flex;gap:7px;flex-wrap:wrap;margin-top:8px">
<button id="codex-elect-check">检查队列</button>
<button id="codex-elect-arm">启动定时</button>
<button id="codex-elect-pause" disabled>暂停</button>
<button id="codex-elect-stop">停止</button>
<button id="codex-elect-retry-failed" disabled>重跑失败组</button>
<button id="codex-elect-export">导出配置</button>
<button id="codex-elect-import">导入配置</button>
<input id="codex-elect-import-file" type="file" accept="application/json,.json" hidden>
</div>
<div id="codex-elect-status" style="margin-top:8px;color:#d7e8ff">未启动</div>
<div id="codex-elect-progress" style="margin-top:5px;color:#9fd3ff">暂无执行进度</div>
<div id="codex-elect-request-stats" style="margin-top:3px;color:#b7c6d8">暂无请求延迟数据</div>
<div id="codex-elect-server-clock" style="margin-top:3px;color:#c8b6ff">服务器时间:校准中</div>
<div style="margin-top:7px;color:#ffcc80">注意:保持登录和页面开启;不要同时手动提交;结果以“已选课程”为准。</div>
</div>
<div id="codex-elect-log" style="flex:1 1 auto;min-height:70px;margin-top:7px;overflow:auto;border-top:1px solid #456;padding-top:5px"></div>
<div id="codex-elect-failures" style="flex:0 0 auto;margin-top:5px;border-top:1px solid #75433e;padding-top:5px">
<div style="display:flex;justify-content:space-between;align-items:center">
<b style="color:#ffb0a8">失败原因统计</b>
<button id="codex-elect-clear-failures" type="button">清空</button>
</div>
<div id="codex-elect-failure-list" style="max-height:48px;overflow:auto"></div>
</div>
<div id="codex-elect-success" style="flex:0 0 auto;max-height:105px;margin-top:6px;border-top:1px solid #2d7650;padding-top:5px">
<div style="display:flex;justify-content:space-between;align-items:center">
<b style="color:#8cff9b">成功记录</b>
<button id="codex-elect-clear-success" type="button">清空</button>
</div>
<div id="codex-elect-success-list" style="max-height:76px;overflow:auto"></div>
</div>
</div>`;
document.body.appendChild(panel);
state.panel = panel;

panel.querySelector("#codex-elect-add").addEventListener("click", addCourse);
panel.querySelector("#codex-elect-search").addEventListener("input", (event) => {
state.queueSearch = event.target.value;
renderQueue();
const search = panel.querySelector("#codex-elect-search");
if (search) {
search.value = state.queueSearch;
search.focus();
}
});
const timeText = panel.querySelector("#codex-elect-time-text");
const timePicker = panel.querySelector("#codex-elect-time-picker");
panel.querySelector("#codex-elect-time-pick").addEventListener("click", () => {
const normalized = normalizeTime(timeText.value);
if (normalized) timePicker.value = normalized;
if (typeof timePicker.showPicker === "function") {
timePicker.showPicker();
} else {
timePicker.click();
}
});
timePicker.addEventListener("change", () => {
const normalized = normalizeTime(timePicker.value);
if (normalized) timeText.value = normalized;
});
timeText.addEventListener("blur", () => {
const normalized = normalizeTime(timeText.value);
if (normalized) {
timeText.value = normalized;
timePicker.value = normalized;
}
});
panel.querySelector("#codex-elect-arm").addEventListener("click", arm);
panel.querySelector("#codex-elect-pause").addEventListener("click", togglePause);
panel.querySelector("#codex-elect-stop").addEventListener("click", stop);
panel
.querySelector("#codex-elect-retry-failed")
.addEventListener("click", retryFailedGroups);
panel.querySelector("#codex-elect-clear-failures").addEventListener("click", () => {
if (
!Object.keys(state.failureStats).length ||
page.confirm("确定清空失败原因统计吗?")
) {
state.failureStats = {};
save();
renderFailureStats();
}
});
panel.querySelector("#codex-elect-clear-success").addEventListener("click", () => {
if (!state.successes.length || page.confirm("确定清空全部成功记录吗?")) {
state.successes = [];
save();
renderSuccesses();
}
});
panel.querySelector("#codex-elect-export").addEventListener("click", exportConfig);
panel.querySelector("#codex-elect-import").addEventListener("click", () =>
panel.querySelector("#codex-elect-import-file").click()
);
panel.querySelector("#codex-elect-import-file").addEventListener("change", (event) => {
const file = event.target.files?.[0];
if (file) importConfig(file);
event.target.value = "";
});
panel.querySelector("#codex-elect-check").addEventListener("click", () => {
const problems = validateQueue();
if (problems.length) {
setStatus(problems.join(";"), "#ffcc80");
log(`检查提醒:${problems.join(";")}`, "bad");
} else {
setStatus("检查通过:课程均存在,未发现与已选课程冲突", "#8cff9b");
}
});
panel.querySelector("#codex-elect-collapse").addEventListener("click", (event) => {
event.stopPropagation();
setPanelCollapsed(panel, !state.settings.panelCollapsed);
});

const handle = panel.querySelector("#codex-elect-handle");
handle.addEventListener("pointerdown", (event) => {
if (event.target.closest("button")) return;
const start = panel.getBoundingClientRect();
const offsetX = event.clientX - start.left;
const offsetY = event.clientY - start.top;
handle.setPointerCapture(event.pointerId);

const move = (moveEvent) => {
panel.style.left = `${Math.max(0, Math.min(innerWidth - 80, moveEvent.clientX - offsetX))}px`;
panel.style.top = `${Math.max(0, Math.min(innerHeight - 40, moveEvent.clientY - offsetY))}px`;
panel.style.right = "auto";
};
const end = () => {
handle.removeEventListener("pointermove", move);
handle.removeEventListener("pointerup", end);
constrainPanel(panel, true);
};
handle.addEventListener("pointermove", move);
handle.addEventListener("pointerup", end);
});

panel.addEventListener("mouseup", () => {
constrainPanel(panel, true);
});

if (state.viewportHandler) {
page.removeEventListener("resize", state.viewportHandler);
page.visualViewport?.removeEventListener("resize", state.viewportHandler);
}
state.viewportHandler = () => constrainPanel(panel, true);
page.addEventListener("resize", state.viewportHandler);
page.visualViewport?.addEventListener("resize", state.viewportHandler);

setPanelCollapsed(panel, Boolean(state.settings.panelCollapsed));
constrainPanel(panel, true);
renderQueue();
renderProgress();
renderRequestStats();
renderServerClock();
renderFailureStats();
renderSuccesses();
updatePauseButton();
updateRetryFailedButton();
}

if (!$ || !page.electCourseTable) return;
const profile = discoverProfile();
state.profileId = profile.id;
state.profileError = profile.error;
if (profile.error || !profile.id) {
const warning = document.createElement("div");
warning.style.cssText =
"position:fixed;right:12px;top:62px;z-index:2147483647;padding:12px;border:1px solid #f44336;background:#241616;color:#ff9b9b;font:14px sans-serif";
warning.textContent = `南开 EAMS 选课助手未启动:${profile.error}`;
document.body.appendChild(warning);
return;
}
load();
save();
createPanel();
installConnectionWatch();
resumeRecoveryIfNeeded();
calibrateServerClock();
setInterval(calibrateServerClock, 60000);
})();


南开大学自动抢课脚本
https://shview.top/2026/06/14/南开大学自动抢课脚本/
作者
Shview
发布于
2026年6月15日
许可协议