-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
3796 lines (3254 loc) · 155 KB
/
Copy pathscript.js
File metadata and controls
3796 lines (3254 loc) · 155 KB
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
// 确保在 DOM 加载完毕后执行脚本
document.addEventListener('DOMContentLoaded', () => {
// --- DOM 元素获取 ---
const apiKeyBtn = document.getElementById('apiKeyBtn');
const apiKeyBtnText = document.getElementById('apiKeyBtnText');
const apiKeyStatus = document.getElementById('apiKeyStatus');
const apiKeyModal = document.getElementById('apiKeyModal');
const apiKeyInput = document.getElementById('apiKeyInput');
const closeApiKeyModal = document.getElementById('closeApiKeyModal');
const cancelApiKey = document.getElementById('cancelApiKey');
const saveApiKey = document.getElementById('saveApiKey');
const toggleApiKeyVisibilityBtn = document.getElementById('toggleApiKeyVisibility');
const eyeIcon = document.getElementById('eyeIcon');
const eyeOffIcon = document.getElementById('eyeOffIcon');
const newExamBtn = document.getElementById('newExamBtn');
const clearHistoryBtn = document.getElementById('clearHistoryBtn');
const recoverDataBtn = document.getElementById('recoverDataBtn');
const historyList = document.getElementById('historyList');
const setupView = document.getElementById('setup-view');
const examView = document.getElementById('exam-view');
const resultView = document.getElementById('result-view');
const topicsTreeContainer = document.getElementById('topicsTree');
const customTopicInput = document.getElementById('customTopic');
const addCustomTopicBtn = document.getElementById('addCustomTopicBtn');
const customTopicsList = document.getElementById('customTopicsList');
const sourceModelRadio = document.getElementById('sourceModel');
const sourceCustomRadio = document.getElementById('sourceCustom');
const sourcePasteRadio = document.getElementById('sourcePaste');
const customDatabaseContainer = document.getElementById('customDatabaseContainer');
const pasteContentContainer = document.getElementById('pasteContentContainer');
const pasteContentArea = document.getElementById('pasteContentArea');
const previewContainer = document.getElementById('previewContainer');
const previewContent = document.getElementById('previewContent');
const editPreviewBtn = document.getElementById('editPreviewBtn');
const reUploadBtn = document.getElementById('reUploadBtn');
const editPreviewArea = document.getElementById('editPreviewArea');
const editContentArea = document.getElementById('editContentArea');
const saveEditBtn = document.getElementById('saveEditBtn');
const cancelEditBtn = document.getElementById('cancelEditBtn');
const customDatabaseFile = document.getElementById('customDatabaseFile');
const fileNameDisplay = document.getElementById('fileNameDisplay');
const selectFileBtn = document.getElementById('selectFileBtn');
const numQuestionsInput = document.getElementById('numQuestions');
const numQuestionsLabel = document.getElementById('numQuestionsLabel');
const examDifficultyInput = document.getElementById('examDifficulty');
const difficultyLabel = document.getElementById('difficultyLabel');
const difficultyDescription = document.getElementById('difficultyDescription');
const difficultyHint = document.getElementById('difficultyHint');
const generateExamBtn = document.getElementById('generateExamBtn');
const loadingIndicator = document.getElementById('loading-indicator');
const loadingMessage = document.getElementById('loading-message');
const progressBar = document.getElementById('progress-bar');
const progressText = document.getElementById('progress-text');
const examContent = document.getElementById('exam-content');
const examTitle = document.getElementById('exam-title');
const questionsContainer = document.getElementById('questions-container');
const submitExamBtn = document.getElementById('submitExamBtn');
const resultContent = document.getElementById('result-content');
const resultTitle = document.getElementById('result-title');
const resultScore = document.getElementById('result-score');
const exportPdfBtn = document.getElementById('exportPdfBtn');
const resultQuestionsContainer = document.getElementById('result-questions-container');
// 实时遮罩层相关元素
const realtimeOverlay = document.getElementById('realtime-overlay');
const overlayProgressBar = document.getElementById('overlay-progress-bar');
const overlayProgressText = document.getElementById('overlay-progress-text');
const realtimeQuestionsContainer = document.getElementById('realtime-questions-container');
const generationLog = document.getElementById('generation-log');
const toggleLogBtn = document.getElementById('toggle-log');
const generationStatus = document.getElementById('generation-status');
const completionActions = document.getElementById('completion-actions');
const confirmStartExamBtn = document.getElementById('confirm-start-exam');
const countdownTimer = document.getElementById('countdown-timer');
// 移动端侧边栏相关元素
const sidebar = document.getElementById('sidebar');
const toggleSidebarBtn = document.getElementById('toggleSidebarBtn');
const menuIcon = document.getElementById('menuIcon');
const closeIcon = document.getElementById('closeIcon');
const sidebarOverlay = document.getElementById('sidebarOverlay');
// --- 全局状态和数据 ---
// 从本地存储获取API Key
let apiKey = localStorage.getItem('deepseek_api_key') || '';
// 更新API Key状态显示
function updateApiKeyStatus() {
// 确保DOM元素存在
if (!apiKeyStatus || !apiKeyBtnText) {
console.warn('API Key相关DOM元素未找到,跳过状态更新');
return;
}
if (apiKey && apiKey.trim().length > 0) {
const maskedKey = apiKey.length > 12 ?
apiKey.substring(0, 8) + '***' + apiKey.substring(apiKey.length - 4) :
apiKey.substring(0, 4) + '***';
apiKeyStatus.textContent = maskedKey;
apiKeyStatus.classList.remove('text-gray-500');
apiKeyStatus.classList.add('text-green-600');
apiKeyBtnText.textContent = '重新设置';
} else {
apiKeyStatus.textContent = '未设置';
apiKeyStatus.classList.remove('text-green-600');
apiKeyStatus.classList.add('text-gray-500');
apiKeyBtnText.textContent = '设置 API Key';
}
}
// 安全地读取考试历史记录
let examHistory = [];
try {
const historyData = localStorage.getItem('exam_history');
if (historyData) {
examHistory = JSON.parse(historyData);
// 兼容性处理:为旧数据添加status字段
let needUpdate = false;
examHistory = examHistory.map(exam => {
if (!exam.status) {
exam.status = 'completed'; // 旧数据默认为已完成
needUpdate = true;
}
return exam;
});
// 如果有更新,保存到localStorage
if (needUpdate) {
localStorage.setItem('exam_history', JSON.stringify(examHistory));
console.log('已为', examHistory.length, '条旧记录添加状态字段');
}
console.log('成功读取考试历史记录:', examHistory.length, '条记录');
} else {
console.log('未找到考试历史记录');
}
} catch (error) {
console.error('读取考试历史记录失败:', error);
examHistory = [];
}
let currentExam = null; // 用于存储当前正在进行的考试
let customTopics = []; // 存储用户自定义的知识点
let customDatabaseContent = null; // 存储自定义题库内容
let pasteContent = null; // 存储粘贴的题库内容
let currentPreviewContent = null; // 存储预览的内容
let originalPreviewContent = null; // 存储编辑前的预览内容
let isSidebarOpen = false; // 侧边栏状态
// 知识点范畴定义
const topics = [
{
name: 'Java',
children: [
{ name: 'Java 基础' },
{ name: 'Java 并发编程' },
{ name: 'JVM' },
{ name: 'Java 8+' },
]
},
{
name: '数据库',
children: [
{ name: 'MySQL' },
{ name: 'Redis' },
{ name: 'MySQL 调优' },
]
},
{
name: '框架',
children: [
{ name: 'Spring' },
{ name: 'SpringBoot' },
{ name: 'MyBatis' },
{ name: 'SpringCloud' },
]
},
{
name: '中间件',
children: [
{ name: 'Kafka' },
{ name: 'RabbitMQ' },
{ name: 'Nacos' },
{ name: 'Zookeeper' },
]
},
{
name: '网络与服务器',
children: [
{ name: 'Netty' },
{ name: 'Tomcat' },
{ name: 'HTTP' },
{ name: 'TCP/IP' },
]
},
{
name: '其他技术',
children: [
{ name: 'Docker' },
{ name: 'Linux' },
{ name: 'Git' },
{ name: '设计模式' },
]
}
];
// --- 函数定义 ---
/**
* 调试和数据恢复函数
*/
function debugDataStatus() {
console.log('=== 数据状态调试信息 ===');
console.log('当前API Key:', apiKey ? '已设置 (长度: ' + apiKey.length + ')' : '未设置');
console.log('考试历史记录数量:', examHistory.length);
// 检查localStorage原始数据
const rawApiKey = localStorage.getItem('deepseek_api_key');
const rawHistory = localStorage.getItem('exam_history');
console.log('localStorage中的API Key:', rawApiKey ? '存在 (长度: ' + rawApiKey.length + ')' : '不存在');
console.log('localStorage中的历史记录:', rawHistory ? '存在 (长度: ' + rawHistory.length + ')' : '不存在');
if (rawHistory) {
try {
const parsedHistory = JSON.parse(rawHistory);
console.log('解析后的历史记录数量:', parsedHistory.length);
} catch (e) {
console.error('历史记录解析失败:', e);
}
}
// 尝试恢复数据
if (rawApiKey && !apiKey) {
console.log('尝试恢复API Key...');
apiKey = rawApiKey;
updateApiKeyStatus();
}
if (rawHistory && examHistory.length === 0) {
console.log('尝试恢复考试历史记录...');
try {
examHistory = JSON.parse(rawHistory);
renderHistoryList();
console.log('历史记录恢复成功');
} catch (e) {
console.error('历史记录恢复失败:', e);
}
}
console.log('=== 调试信息结束 ===');
}
/**
* 显示API Key设置弹窗
*/
function showApiKeyModal() {
apiKeyInput.value = apiKey; // 设置当前API Key值
apiKeyModal.classList.remove('hidden');
apiKeyInput.focus();
}
/**
* 隐藏API Key设置弹窗
*/
function hideApiKeyModal() {
apiKeyModal.classList.add('hidden');
apiKeyInput.value = ''; // 清空输入框
// 重置密码可见性
apiKeyInput.type = 'password';
eyeIcon.classList.remove('hidden');
eyeOffIcon.classList.add('hidden');
}
/**
* 保存API Key配置
*/
function saveApiKeyConfig() {
const newApiKey = apiKeyInput.value.trim();
if (newApiKey.length === 0) {
alert('请输入有效的API Key');
return;
}
// 简单验证API Key格式(DeepSeek API Key通常以sk-开头)
if (!newApiKey.startsWith('sk-')) {
const confirm = window.confirm('API Key格式可能不正确(通常以sk-开头)。是否仍要保存?');
if (!confirm) {
return;
}
}
apiKey = newApiKey;
localStorage.setItem('deepseek_api_key', apiKey);
updateApiKeyStatus();
hideApiKeyModal();
// 显示成功提示
showTemporaryMessage('API Key 配置已保存', 'success');
}
/**
* 切换API Key输入框的可见性
*/
function toggleApiKeyVisibility() {
if (apiKeyInput.type === 'password') {
apiKeyInput.type = 'text';
eyeIcon.classList.add('hidden');
eyeOffIcon.classList.remove('hidden');
} else {
apiKeyInput.type = 'password';
eyeIcon.classList.remove('hidden');
eyeOffIcon.classList.add('hidden');
}
}
/**
* 显示临时消息提示
* @param {string} message - 消息内容
* @param {string} type - 消息类型 ('success', 'error', 'warning')
*/
function showTemporaryMessage(message, type = 'success') {
const messageEl = document.createElement('div');
messageEl.className = `temporary-message fixed top-4 right-4 z-60 px-4 py-3 rounded-lg shadow-lg text-white font-medium transition-all duration-300 transform translate-x-full`;
// 根据类型设置颜色
if (type === 'success') {
messageEl.classList.add('bg-green-500');
} else if (type === 'error') {
messageEl.classList.add('bg-red-500');
} else if (type === 'warning') {
messageEl.classList.add('bg-orange-500');
}
messageEl.textContent = message;
document.body.appendChild(messageEl);
// 显示动画
setTimeout(() => {
messageEl.classList.remove('translate-x-full');
}, 100);
// 3秒后隐藏
setTimeout(() => {
messageEl.classList.add('translate-x-full');
setTimeout(() => {
if (messageEl.parentNode) {
messageEl.parentNode.removeChild(messageEl);
}
}, 300);
}, 3000);
}
/**
* 切换主内容区的视图
* @param {string} viewName - 要显示的视图名称 ('setup', 'exam', 'result')
*/
function switchView(viewName) {
setupView.classList.add('hidden');
examView.classList.add('hidden');
resultView.classList.add('hidden');
if (viewName === 'setup') {
setupView.classList.remove('hidden');
} else if (viewName === 'exam') {
examView.classList.remove('hidden');
} else if (viewName === 'result') {
resultView.classList.remove('hidden');
}
}
/**
* 渲染知识点选择树
*/
function renderTopicsTree() {
topicsTreeContainer.innerHTML = '';
topics.forEach(category => {
const categoryDiv = document.createElement('div');
categoryDiv.classList.add('mb-2');
const parentCheckboxId = `topic-${category.name.replace(/\s+/g, '-')}`;
categoryDiv.innerHTML = `
<div class="font-bold">
<input type="checkbox" id="${parentCheckboxId}" data-category="${category.name}" class="parent-topic">
<label for="${parentCheckboxId}">${category.name}</label>
</div>
`;
const childrenDiv = document.createElement('div');
childrenDiv.classList.add('ml-4', 'mt-1');
category.children.forEach(topic => {
const topicCheckboxId = `topic-${topic.name.replace(/\s+/g, '-')}`;
childrenDiv.innerHTML += `
<div class="mb-1">
<input type="checkbox" id="${topicCheckboxId}" data-parent="${category.name}" value="${topic.name}" class="child-topic">
<label for="${topicCheckboxId}">${topic.name}</label>
</div>
`;
});
categoryDiv.appendChild(childrenDiv);
topicsTreeContainer.appendChild(categoryDiv);
});
// 添加父复选框联动子复选框的逻辑
document.querySelectorAll('.parent-topic').forEach(parent => {
parent.addEventListener('change', (e) => {
const categoryName = e.target.dataset.category;
document.querySelectorAll(`.child-topic[data-parent="${categoryName}"]`).forEach(child => {
child.checked = e.target.checked;
});
updateStepIndicator();
});
});
// 添加子复选框联动父复选框的逻辑
document.querySelectorAll('.child-topic').forEach(child => {
child.addEventListener('change', (e) => {
const parentName = e.target.dataset.parent;
const parentCheckbox = document.querySelector(`.parent-topic[data-category="${parentName}"]`);
const siblings = document.querySelectorAll(`.child-topic[data-parent="${parentName}"]`);
// 检查是否所有子复选框都被选中
const allChecked = Array.from(siblings).every(sib => sib.checked);
// 检查是否存在被选中的子复选框
const someChecked = Array.from(siblings).some(sib => sib.checked);
// 更新父复选框状态
parentCheckbox.checked = allChecked;
parentCheckbox.indeterminate = someChecked && !allChecked;
updateStepIndicator();
});
});
}
/**
* 切换侧边栏显示状态
*/
function toggleSidebar() {
isSidebarOpen = !isSidebarOpen;
if (isSidebarOpen) {
sidebar.classList.remove('-translate-x-full');
menuIcon.classList.add('hidden');
closeIcon.classList.remove('hidden');
sidebarOverlay.classList.remove('hidden');
document.body.classList.add('overflow-hidden'); // 防止背景滚动
} else {
sidebar.classList.add('-translate-x-full');
menuIcon.classList.remove('hidden');
closeIcon.classList.add('hidden');
sidebarOverlay.classList.add('hidden');
document.body.classList.remove('overflow-hidden');
}
}
/**
* 关闭侧边栏(仅适用于移动设备)
*/
function closeSidebar() {
if (window.innerWidth < 768) { // md 断点是 768px
isSidebarOpen = false;
sidebar.classList.add('-translate-x-full');
menuIcon.classList.remove('hidden');
closeIcon.classList.add('hidden');
sidebarOverlay.classList.add('hidden');
document.body.classList.remove('overflow-hidden');
}
}
/**
* 调整布局适应屏幕大小变化
*/
function handleResize() {
if (window.innerWidth >= 768) { // md 断点是 768px
// 在大屏幕上始终显示侧边栏
sidebar.classList.remove('-translate-x-full');
sidebarOverlay.classList.add('hidden');
document.body.classList.remove('overflow-hidden');
} else if (!isSidebarOpen) {
// 在小屏幕上如果侧边栏应该关闭,确保它是关闭的
sidebar.classList.add('-translate-x-full');
}
}
/**
* 渲染考试历史记录列表
*/
function renderHistoryList() {
historyList.innerHTML = '';
if (examHistory.length === 0) {
historyList.innerHTML = `
<div class="text-center py-8">
<div class="text-gray-400 mb-2">
<svg class="w-12 h-12 mx-auto mb-3 opacity-50" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
</svg>
</div>
<p class="text-sm text-gray-500 mb-1">暂无考试记录</p>
<p class="text-xs text-gray-400">创建新考试开始练习</p>
</div>
`;
return;
}
examHistory.forEach((exam, index) => {
const historyItem = document.createElement('div');
// 检查是否为当前查看的考试
const isCurrentExam = currentExam && currentExam.id === exam.id;
// 根据考试状态设置样式(兼容旧数据)
const isInProgress = exam.status === 'in_progress';
const baseClasses = 'p-2.5 mb-1.5 border rounded-lg hover:bg-gray-50 relative transition-all duration-200 cursor-pointer';
if (isCurrentExam) {
historyItem.classList.add(...baseClasses.split(' '), 'current-exam', 'bg-blue-50', 'border-blue-200', 'shadow-sm');
} else if (isInProgress) {
historyItem.classList.add(...baseClasses.split(' '), 'bg-orange-50', 'border-orange-200', 'hover:bg-orange-100');
} else {
historyItem.classList.add(...baseClasses.split(' '), 'border-gray-200', 'hover:border-gray-300');
}
// 构建状态显示文本(兼容旧数据)
let statusText = '';
let scoreText = '';
let difficultyText = '';
if (isInProgress) {
statusText = '<span class="text-orange-600 font-medium text-xs">● 未交卷</span>';
scoreText = '进行中';
} else {
statusText = '<span class="text-green-600 font-medium text-xs">✓ 已完成</span>';
// 兼容旧数据:如果没有score字段,显示为"已完成"
scoreText = exam.score !== undefined ? `得分: ${exam.score} / 100` : '已完成';
}
// 显示难度信息(兼容旧数据)
if (exam.difficulty) {
const difficultyInfo = getDifficultyInfo(exam.difficulty);
difficultyText = `<span class="text-purple-600 font-medium text-xs">🎯 ${exam.difficulty}级(${difficultyInfo.desc})</span>`;
}
// 操作按钮
let actionButton = '';
if (isInProgress) {
actionButton = `
<button class="continue-exam-btn absolute bottom-2 right-6 text-green-500 hover:text-green-700 p-1 rounded-full hover:bg-green-50 transition-colors" title="继续答题">
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" fill="currentColor" viewBox="0 0 16 16">
<path d="M8 15A7 7 0 1 1 8 1a7 7 0 0 1 0 14zm0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16z"/>
<path d="M6.271 5.055a.5.5 0 0 1 .52.038L11 7.055a.5.5 0 0 1 0 .89L6.791 9.907a.5.5 0 0 1-.791-.39V5.482a.5.5 0 0 1 .271-.427z"/>
</svg>
</button>
`;
}
// 计算题目数量信息
const questionCount = exam.questions ? exam.questions.length : 0;
const questionCountText = questionCount > 0 ? `${questionCount}题` : '';
// 格式化时间显示(年月日时分)
const examDate = new Date(exam.date);
const timeText = examDate.toLocaleString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit'
}).replace(/\//g, '-');
historyItem.innerHTML = `
<div class="exam-item">
<!-- 标题行(独立显示,完整标题) -->
<div class="mb-1.5">
<h4 class="text-sm font-bold text-gray-800 leading-tight line-clamp-2" title="${exam.title}">${exam.title}</h4>
</div>
<!-- 信息行 -->
<div class="flex items-center justify-between text-xs mb-1.5">
<div class="flex items-center space-x-1.5">
${questionCountText ? `<span class="bg-blue-100 text-blue-700 px-1.5 py-0.5 rounded text-xs font-medium">${questionCountText}</span>` : ''}
${difficultyText ? difficultyText.replace('text-purple-600 font-medium text-xs', 'bg-purple-100 text-purple-700 px-1.5 py-0.5 rounded text-xs font-medium').replace('🎯 ', '').replace('级(', '·').replace(')', '') : ''}
${exam.isCustomDatabase ? `<span class="bg-green-100 text-green-700 px-1.5 py-0.5 rounded text-xs font-medium" title="${exam.customDbName || '自定义题库'}">📁</span>` : ''}
</div>
<span class="text-gray-400 text-xs">${timeText}</span>
</div>
<!-- 得分和状态行 -->
<div class="flex items-center justify-between text-xs">
<span class="${isInProgress ? 'text-orange-600 font-medium' : 'text-gray-600'}">${scoreText}</span>
<span class="ml-2 status-badge">${statusText}</span>
</div>
</div>
${actionButton}
<button class="delete-exam-btn absolute top-2 right-1 text-red-400 hover:text-red-600 p-1 rounded-full hover:bg-red-50 transition-colors">
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" fill="currentColor" viewBox="0 0 16 16">
<path d="M5.5 5.5A.5.5 0 0 1 6 6v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5zm2.5 0a.5.5 0 0 1 .5.5v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5zm3 .5a.5.5 0 0 0-1 0v6a.5.5 0 0 0 1 0V6z"/>
<path fill-rule="evenodd" d="M14.5 3a1 1 0 0 1-1 1H13v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V4h-.5a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1H6a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1h3.5a1 1 0 0 1 1 1v1zM4.118 4 4 4.059V13a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1V4.059L11.882 4H4.118zM2.5 3V2h11v1h-11z"/>
</svg>
</button>
`;
// 点击考试项查看详情或继续答题
historyItem.querySelector('.exam-item').addEventListener('click', () => {
if (exam.status === 'in_progress') {
// 继续答题
continueExam(index);
} else {
// 查看结果(兼容旧数据:没有status字段的都认为是已完成)
showExamResult(index);
}
closeSidebar(); // 在移动端关闭侧边栏
});
// 继续答题按钮
const continueBtn = historyItem.querySelector('.continue-exam-btn');
if (continueBtn) {
continueBtn.addEventListener('click', (e) => {
e.stopPropagation(); // 阻止事件冒泡
continueExam(index);
closeSidebar();
});
}
// 点击删除按钮删除考试
historyItem.querySelector('.delete-exam-btn').addEventListener('click', (e) => {
e.stopPropagation(); // 阻止事件冒泡,避免触发考试项点击事件
deleteExam(index);
});
historyList.appendChild(historyItem);
});
}
/**
* 继续进行中的考试
* @param {number} index - 考试历史记录的索引
*/
function continueExam(index) {
if (index < 0 || index >= examHistory.length) {
console.error('无效的考试索引:', index);
alert('无法找到指定的考试记录');
return;
}
const exam = examHistory[index];
if (!exam) {
console.error('考试数据不存在,索引:', index);
alert('考试数据丢失或损坏');
return;
}
// 数据完整性检查
if (!exam.questions || !Array.isArray(exam.questions)) {
console.error('考试题目数据缺失或格式错误:', exam);
alert('该考试的题目数据已损坏,无法继续答题');
return;
}
if (!exam.userAnswers || !Array.isArray(exam.userAnswers)) {
console.warn('用户答案数据缺失,创建新的答案数组');
exam.userAnswers = new Array(exam.questions.length).fill(null);
}
// 确保答案数组长度与题目数组一致
if (exam.userAnswers.length !== exam.questions.length) {
console.warn('答案数组长度与题目数组不一致,进行调整');
const adjustedAnswers = new Array(exam.questions.length).fill(null);
for (let i = 0; i < Math.min(exam.userAnswers.length, exam.questions.length); i++) {
adjustedAnswers[i] = exam.userAnswers[i];
}
exam.userAnswers = adjustedAnswers;
// 更新历史记录中的数据
examHistory[index] = exam;
try {
localStorage.setItem('exam_history', JSON.stringify(examHistory));
} catch (error) {
console.error('保存调整后的考试数据失败:', error);
}
}
currentExam = exam; // 设置当前考试
console.log('继续答题:', exam.title || '未命名考试');
try {
// 渲染考试,使用增强的安全渲染
renderExamSafely(exam);
// 使用 setTimeout 确保DOM完全渲染后再恢复答案
setTimeout(() => {
// 恢复用户之前的答案
exam.questions.forEach((q, questionIndex) => {
const userAnswer = exam.userAnswers[questionIndex];
if (userAnswer) {
const name = `question-${questionIndex}`;
if (Array.isArray(userAnswer)) {
// 多选题
userAnswer.forEach(answer => {
const checkbox = document.querySelector(`input[name="${name}"][value="${answer}"]`);
if (checkbox) checkbox.checked = true;
});
} else {
// 单选题或判断题
const radio = document.querySelector(`input[name="${name}"][value="${userAnswer}"]`);
if (radio) radio.checked = true;
}
}
});
}, 100);
// 更新历史记录列表,高亮当前考试
renderHistoryList();
// 滚动到考试记录的位置
const currentExamElement = historyList.querySelector('.current-exam');
if (currentExamElement) {
currentExamElement.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}
switchView('exam');
} catch (error) {
console.error('继续考试时发生错误:', error);
alert('继续考试时发生错误,请检查数据完整性');
// 即使出错也要更新历史记录列表,确保界面正常
renderHistoryList();
}
}
/**
* 安全地渲染考试内容
* @param {object} exam - 考试对象
*/
function renderExamSafely(exam) {
const examTitle = exam.title || '未命名考试';
document.getElementById('exam-title').textContent = examTitle;
questionsContainer.innerHTML = '';
exam.questions.forEach((q, index) => {
// 对每个题目进行安全检查
if (!q || typeof q.question !== 'string') {
console.warn(`题目 ${index + 1} 数据不完整,跳过渲染`);
const errorEl = document.createElement('div');
errorEl.className = 'mb-6 p-4 border border-red-300 rounded-lg bg-red-50';
errorEl.innerHTML = `
<p class="font-semibold mb-2 text-red-700">${index + 1}. 题目解析失败</p>
<p class="text-red-600 text-sm">该题目数据不完整,无法正常显示</p>
`;
questionsContainer.appendChild(errorEl);
return;
}
const questionEl = document.createElement('div');
questionEl.classList.add('mb-6', 'p-4', 'border-b');
try {
questionEl.innerHTML = `
<p class="font-semibold mb-2">${index + 1}. ${q.question}</p>
<div class="options-container space-y-2">
${renderOptionsSafely(q, index)}
</div>
`;
questionsContainer.appendChild(questionEl);
} catch (error) {
console.error(`渲染题目 ${index + 1} 时发生错误:`, error);
questionEl.innerHTML = `
<p class="font-semibold mb-2 text-red-700">${index + 1}. 题目渲染失败</p>
<p class="text-red-600 text-sm">该题目在渲染过程中发生错误</p>
`;
questionsContainer.appendChild(questionEl);
}
});
// 为所有选项添加变化监听器,实时保存答案
const allInputs = questionsContainer.querySelectorAll('input[type="radio"], input[type="checkbox"]');
allInputs.forEach(input => {
input.addEventListener('change', () => {
saveCurrentAnswers();
});
});
}
/**
* 安全地渲染题目选项
* @param {object} question - 题目对象
* @param {number} questionIndex - 题目索引
* @returns {string} - 选项的 HTML 字符串
*/
function renderOptionsSafely(question, questionIndex) {
const name = `question-${questionIndex}`;
// 处理判断题类型
if (question.type === 'judgment' || question.type === 'truefalse') {
return `
<div class="mb-3 pl-2">
<input type="radio" id="${name}-option-0" name="${name}" value="A" class="mr-2">
<label for="${name}-option-0" class="select-none">A. 正确</label>
</div>
<div class="mb-3 pl-2">
<input type="radio" id="${name}-option-1" name="${name}" value="B" class="mr-2">
<label for="${name}-option-1" class="select-none">B. 错误</label>
</div>
`;
}
// 安全检查:确保其他类型题目有选项数据
if (!question.options || !Array.isArray(question.options) || question.options.length === 0) {
console.error('题目选项数据不完整:', question);
return '<div class="text-red-500 p-2 border border-red-300 rounded bg-red-50">该题目选项数据缺失或格式错误,无法正常显示</div>';
}
const optionType = question.type === 'single' ? 'radio' : 'checkbox';
return question.options.map((option, optionIndex) => {
const optionLetter = String.fromCharCode(65 + optionIndex); // A, B, C...
return `
<div class="mb-3 pl-2">
<input type="${optionType}" id="${name}-option-${optionIndex}" name="${name}" value="${optionLetter}" class="mr-2">
<label for="${name}-option-${optionIndex}" class="select-none">${optionLetter}. ${option}</label>
</div>
`;
}).join('');
}
/**
* 显示指定索引的考试结果
* @param {number} index - 考试历史记录的索引
*/
function showExamResult(index) {
if (index < 0 || index >= examHistory.length) {
console.error('无效的考试索引:', index);
alert('无法找到指定的考试记录');
return;
}
const exam = examHistory[index];
if (!exam) {
console.error('考试数据不存在,索引:', index);
alert('考试数据丢失或损坏');
return;
}
// 数据完整性检查
if (!exam.questions || !Array.isArray(exam.questions)) {
console.error('考试题目数据缺失或格式错误:', exam);
alert('该考试的题目数据已损坏,无法显示结果');
return;
}
if (!exam.userAnswers || !Array.isArray(exam.userAnswers)) {
console.warn('用户答案数据缺失,使用空答案数组');
exam.userAnswers = new Array(exam.questions.length).fill(null);
}
// 确保答案数组长度与题目数组一致
if (exam.userAnswers.length !== exam.questions.length) {
console.warn('答案数组长度与题目数组不一致,进行调整');
const adjustedAnswers = new Array(exam.questions.length).fill(null);
for (let i = 0; i < Math.min(exam.userAnswers.length, exam.questions.length); i++) {
adjustedAnswers[i] = exam.userAnswers[i];
}
exam.userAnswers = adjustedAnswers;
}
currentExam = exam; // 将当前考试设置为历史记录中的考试,以便导出
// 安全地设置结果标题和分数
const examTitle = exam.title || '未命名考试';
const examScore = exam.score !== undefined ? exam.score : 0;
resultTitle.textContent = examTitle;
resultScore.textContent = `最终得分: ${examScore} / 100`;
try {
// 使用增强的renderResults函数,现在包含完整的错误处理
renderResults(exam.questions, exam.userAnswers);
// 更新历史记录列表,高亮当前查看的考试
renderHistoryList();
// 滚动到考试记录的位置
const currentExamElement = historyList.querySelector('.current-exam');
if (currentExamElement) {
currentExamElement.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}
console.log(`显示考试结果: ${examTitle}, 得分: ${examScore}, 索引: ${index}`);
switchView('result');
} catch (error) {
console.error('渲染考试结果时发生错误:', error);
alert('显示考试结果时发生错误,请检查数据完整性');
// 即使出错也要更新历史记录列表,确保界面正常
renderHistoryList();
}
}
/**
* 清空所有考试记录
*/
function clearHistory() {
if (confirm('确定要清空所有考试记录吗?此操作不可恢复。')) {
examHistory = [];
localStorage.removeItem('exam_history');
renderHistoryList();
alert('所有记录已清空。');
}
}
/**
* 添加自定义知识点
*/
function addCustomTopic() {
const value = customTopicInput.value.trim();
if (!value) return;
// 可以同时添加多个,以逗号分隔
const newTopics = value.split(/[,,、;;]/).map(t => t.trim()).filter(t => t);
for (const topic of newTopics) {
if (!customTopics.includes(topic)) {
customTopics.push(topic);
}
}
renderCustomTopics();
customTopicInput.value = '';
updateStepIndicator();
}
/**
* 获取难度描述信息
* @param {number} difficulty - 难度级别 (1-10)
* @returns {object} - 包含描述、提示等信息的对象
*/
function getDifficultyInfo(difficulty) {
const difficultyMap = {
1: { desc: '入门级', hint: '适合零基础学习者,题目涉及最基本的概念和定义' },
2: { desc: '初级', hint: '适合初学者,题目涉及基础知识点的理解和应用' },
3: { desc: '初级+', hint: '适合有少量基础的学习者,题目涉及基础概念的扩展' },
4: { desc: '中级-', hint: '适合有一定基础的学习者,题目开始涉及知识点的综合运用' },
5: { desc: '中等难度', hint: '适合有一定基础的学习者,题目涉及常见概念和应用场景' },
6: { desc: '中级+', hint: '适合有扎实基础的学习者,题目涉及深层次的理解和分析' },
7: { desc: '中高级', hint: '适合有丰富经验的学习者,题目涉及复杂场景和解决方案' },
8: { desc: '高级', hint: '适合专业人士,题目涉及系统性思考和高级技术细节' },
9: { desc: '高级+', hint: '适合资深专家,题目涉及架构设计和最佳实践方案' },
10: { desc: '专家级', hint: '适合技术专家,题目涉及前沿技术和复杂系统设计' }
};
return difficultyMap[difficulty] || difficultyMap[5];
}
/**
* 更新难度显示
*/
function updateDifficultyDisplay() {
const difficulty = parseInt(examDifficultyInput.value);
const info = getDifficultyInfo(difficulty);
difficultyLabel.textContent = difficulty;
difficultyDescription.textContent = info.desc;
difficultyHint.textContent = info.hint;
// 更新滑块的填充效果
const percentage = ((difficulty - 1) / (10 - 1)) * 100;
examDifficultyInput.style.setProperty('--difficulty-value', `${percentage}%`);
console.log(`难度已设置为 ${difficulty} 级 (${info.desc})`);
}
/**
* 渲染自定义知识点标签
*/
function renderCustomTopics() {
customTopicsList.innerHTML = '';
customTopics.forEach(topic => {
const tag = document.createElement('div');
tag.classList.add('bg-blue-100', 'text-blue-800', 'rounded', 'px-2', 'py-1', 'm-1', 'text-sm', 'flex', 'items-center');
tag.innerHTML = `
<span>${topic}</span>
<button class="ml-1 text-blue-500 hover:text-blue-700 font-bold" data-topic="${topic}">×</button>
`;
tag.querySelector('button').addEventListener('click', (e) => {
const topicToRemove = e.target.dataset.topic;
customTopics = customTopics.filter(t => t !== topicToRemove);