File size: 79,144 Bytes
1fcca97
 
 
 
 
 
 
 
 
db9f45b
 
1fcca97
 
 
 
 
430716a
 
1fcca97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70abfc9
1fcca97
70abfc9
 
 
 
 
 
 
 
 
 
 
 
 
 
1fcca97
 
 
 
 
 
 
 
 
70abfc9
 
 
1fcca97
70abfc9
1fcca97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
603a19f
1fcca97
 
 
 
 
 
603a19f
1fcca97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
603a19f
 
1fcca97
 
 
 
 
 
 
 
 
 
603a19f
1fcca97
603a19f
 
 
 
1fcca97
 
 
 
 
603a19f
1fcca97
603a19f
1fcca97
 
 
 
 
 
 
 
 
 
 
 
 
 
603a19f
1fcca97
603a19f
1fcca97
603a19f
 
 
1fcca97
 
 
 
 
603a19f
1fcca97
 
 
 
 
 
603a19f
 
 
 
 
1fcca97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
603a19f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70abfc9
 
 
 
 
603a19f
70abfc9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
603a19f
70abfc9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
603a19f
70abfc9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
603a19f
 
 
70abfc9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
603a19f
 
 
 
1fcca97
603a19f
1fcca97
 
 
 
603a19f
 
1fcca97
 
603a19f
 
1fcca97
603a19f
 
 
 
1fcca97
 
603a19f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1fcca97
 
603a19f
 
 
 
 
 
 
 
1fcca97
 
603a19f
 
 
 
1fcca97
603a19f
 
 
 
 
1fcca97
603a19f
 
 
 
 
 
 
 
 
 
 
 
 
1fcca97
 
 
 
603a19f
 
 
 
 
 
 
 
 
 
 
1fcca97
603a19f
 
 
1fcca97
 
 
 
603a19f
 
 
1fcca97
 
 
 
603a19f
1fcca97
 
 
 
 
 
603a19f
 
1fcca97
5160d1d
 
1fcca97
 
 
 
 
 
 
 
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
# -*- coding: utf-8 -*-

from flask import Flask, render_template, request, redirect, url_for, make_response, jsonify, session
import requests
import json
import os
from urllib.parse import quote
from concurrent.futures import ThreadPoolExecutor
import hashlib
from webdav_sync import start_webdav_sync_if_configured

# --- 应用配置 (Application Configuration) ---
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
TEMPLATE_DIR = os.path.join(SCRIPT_DIR, 'templates')
HISTORY_FILE = os.path.join(SCRIPT_DIR, 'history.json')
ENV_FILE = os.path.join(SCRIPT_DIR, '.env')
# 在应用导入阶段拉取远端,并启动定时同步
_webdav_syncer = start_webdav_sync_if_configured(HISTORY_FILE)

app = Flask(__name__, template_folder=TEMPLATE_DIR)
app.secret_key = os.urandom(24)


# --- 环境变量加载 (.env 支持) ---
def _load_env_file(path: str = ENV_FILE):
    if not os.path.exists(path):
        return
    try:
        with open(path, 'r', encoding='utf-8') as f:
            for raw in f:
                line = raw.strip()
                if not line or line.startswith('#'):
                    continue
                if line.startswith('export '):
                    line = line[len('export '):].strip()
                if '=' not in line:
                    continue
                key, value = line.split('=', 1)
                key = key.strip()
                value = value.strip().strip('\"').strip("'")
                # 仅在未设置时从文件填充,避免覆盖真实环境变量
                if key and key not in os.environ:
                    os.environ[key] = value
    except Exception as e:
        print(f"Warning: failed to load .env file: {e}")


# 尝试在应用导入时加载 .env
_load_env_file()


# --- 数据处理与持久化 (Data Handling & Persistence) ---

def _compute_entry_id(username: str, password: str, seid: str) -> str:
    """基于 (username, password, seid) 计算稳定ID,不写入文件,仅在内存中使用。"""
    raw = f"{username}|||{password}|||{seid}".encode('utf-8')
    return hashlib.sha1(raw).hexdigest()


def load_history():
    """从 JSON 文件加载查询历史(仅最小字段)。为每条记录计算内存态ID。"""
    if not os.path.exists(HISTORY_FILE):
        return []
    try:
        with open(HISTORY_FILE, 'r', encoding='utf-8') as f:
            content = f.read()
            items = json.loads(content) if content else []
            # 为每条记录补充计算得到的 id(不写回磁盘)
            enriched = []
            for e in items:
                username = e.get('username')
                password = e.get('password')
                seid = e.get('seid')
                eid = _compute_entry_id(username or '', password or '', seid or '')
                enriched.append({**e, 'id': eid})
            return enriched
    except (json.JSONDecodeError, IOError) as e:
        print(f"Error loading history file: {e}")
        return []

def save_history(history_data):
    """将查询历史保存到 JSON 文件,并进行去重,仅保留所需字段。
    仅保存以下字段:seid、examName、username、studentName、password、totalScore、unionOrder。
    """
    ALLOWED_FIELDS = {"seid", "examName", "username", "studentName", "password", "totalScore", "unionOrder"}

    # 去重键:(username, password, seid)
    unique_entries = {}
    for entry in history_data:
        key = (entry.get('username'), entry.get('password'), entry.get('seid'))
        if key in unique_entries:
            continue
        # 仅保留允许的字段
        minimal_entry = {k: entry.get(k) for k in ALLOWED_FIELDS}
        unique_entries[key] = minimal_entry

    deduplicated_history = list(unique_entries.values())

    try:
        with open(HISTORY_FILE, 'w', encoding='utf-8') as f:
            json.dump(deduplicated_history, f, indent=4, ensure_ascii=False)
    except IOError as e:
        print(f"Error saving history file: {e}")

def process_segment_data(segments):
    """[优化] 处理分数段数据,过滤无效和首尾无人的分数段。
    (Process score segment data, filtering invalid and empty-head/tail segments.)"""
    if not isinstance(segments, list) or not segments:
        return []
    try:
        # Filter out segments with a max score below a reasonable threshold (e.g., 10)
        valid_segments = [s for s in segments if float(s.get('maxscore', 0)) > 10]
    except (ValueError, TypeError):
        valid_segments = segments # Fallback if conversion fails
    
    first_idx, last_idx = -1, -1
    # Find the first and last segments that actually have people in them
    for i, segment in enumerate(valid_segments):
        if isinstance(segment.get('num'), (int, float)) and segment['num'] > 0:
            if first_idx == -1: first_idx = i
            last_idx = i
    
    # Return the slice of segments from the first person to the last person
    return valid_segments[first_idx : last_idx + 1] if first_idx != -1 else []


# --- 核心 API 逻辑 (Core API Logic) ---

def login_and_get_session(user, pw):
    """登录并获取会话ID。 (Login and get session ID.)"""
    login_url = f"https://www.yunchengji.net/app/login?j_username={user}&j_password={pw}"
    student_login_url = "https://www.yunchengji.net/app/student/login"
    headers = {'User-Agent': "ycj/5.7.0(Android;12)<okhttp>(<okhttp/3.10.0>)", 'Accept-Encoding': "gzip"}
    try:
        with requests.Session() as s:
            s.headers.update(headers)
            # First login request
            response1 = s.post(login_url, headers={'content-length': "0"}, allow_redirects=False, timeout=10)
            response1.raise_for_status()
            # Check if SESSIONID cookie is set
            if not s.cookies.get("SESSIONID"):
                return False, "登录失败:无法获取会话ID,请检查用户名和密码。"
            # Second request to finalize student login
            response2 = s.get(student_login_url, timeout=10)
            response2.raise_for_status()
            return True, s.cookies.get("SESSIONID")
    except requests.exceptions.RequestException as e:
        return False, f"登录过程中发生网络错误: {e}"

def fetch_data(session_id, url, error_context, seid=None):
    """通用数据获取函数。 (Generic data fetching function.)"""
    headers = {
        'User-Agent': "Mozilla/5.0 (Linux; Android 12) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.72 Mobile Safari/537.36",
        'Accept': "application/json, text/plain, */*",
        'Cookie': f"SESSIONID={session_id}",
    }
    if seid:
        headers['Referer'] = f"https://www.yunchengji.net/app/student/report/html/report.html?seid={seid}"
    try:
        response = requests.get(url, headers=headers, timeout=10)
        response.raise_for_status()
        return True, response.json()
    except requests.exceptions.RequestException as e:
        return False, f"获取{error_context}时发生网络错误: {e}"
    except json.JSONDecodeError:
        return False, f"解析{error_context}失败:服务器返回的不是有效的JSON格式。"

def get_processed_subject_details(session_id, seid, subject_id):
    """封装了获取和处理单个科目所有详细数据的逻辑。
    (Encapsulates logic to fetch and process all details for a single subject.)"""
    base_url = "https://www.yunchengji.net/app/student/cj"
    # Fetch data from three different endpoints
    _, q_data = fetch_data(session_id, f"{base_url}/question-list?seid={seid}&subjectid={subject_id}", "题目列表", seid)
    _, a_data = fetch_data(session_id, f"{base_url}/report-subject?seid={seid}&subjectid={subject_id}", "科目分析", seid)
    _, lq_data = fetch_data(session_id, f"{base_url}/lose-question-list?seid={seid}&subjectid={subject_id}", "失分列表", seid)
    
    # Process question scores
    q_scores_list = q_data.get("desc", {}).get("questions", [])
    scores_dict = {q['title']: {'score': q.get('score'), 'totalScore': q.get('totalScore')} for q in q_scores_list if q.get('title')}
    
    # Process question rates and merge with scores
    quest_rates = a_data.get("desc", {}).get("questRates", [])
    processed_questions = []
    for rate_info in quest_rates:
        if rate_info.get('bqFlag'): # This is a section header
            processed_questions.append({'is_header': True, 'data': rate_info, 'questions': []})
        elif processed_questions: # This is a question under a header
            title = rate_info.get('title')
            score_details = scores_dict.get(title, {'score': 'N/A', 'totalScore': 'N/A'})
            processed_questions[-1]['questions'].append({**rate_info, **score_details})

    # Calculate section totals
    for section in processed_questions:
        if section['is_header']:
            my_total = sum(float(q.get('score', 0)) for q in section['questions'] if str(q.get('score')).replace('.', '', 1).isdigit())
            section_total = sum(float(q.get('totalScore', 0)) for q in section['questions'] if str(q.get('totalScore')).replace('.', '', 1).isdigit())
            section['data']['my_section_score'] = f"{my_total:.2f}".rstrip('0').rstrip('.')
            section['data']['section_total_score'] = f"{section_total:.2f}".rstrip('0').rstrip('.')
            
    return {
        "analysis": a_data.get("desc"),
        "lose_question_analysis": lq_data.get("desc"),
        "processed_questions": processed_questions
    }


# --- 模板上下文 (Template Context) ---

@app.context_processor
def utility_processor():
    """向模板注入实用函数。 (Inject utility functions into templates.)"""
    def get_rate_color_style(my_rate_str, avg_rate_str):
        """Generates a background color style based on the difference between my rate and the average rate."""
        try:
            my_rate = float(str(my_rate_str).strip('%'))
            avg_rate = float(str(avg_rate_str).strip('%'))
            diff = my_rate - avg_rate
            if diff > 0.1: # Better than average
                intensity = min(diff / 30.0, 1.0) # Cap intensity at 30% difference
                return f"background-color: hsl(130, 80%, {92 - (intensity * 20):.0f}%) !important;"
            elif diff < -0.1: # Worse than average
                intensity = min(abs(diff) / 30.0, 1.0) # Cap intensity at 30% difference
                return f"background-color: hsl(0, 90%, {92 - (intensity * 15):.0f}%) !important;"
            return ""
        except (ValueError, TypeError):
            return ""
    return dict(get_rate_color_style=get_rate_color_style)


# --- Flask 路由 (Flask Routes) ---

@app.route('/', methods=['GET'])
def index():
    """渲染主页面。 (Render the main page.)"""
    # 不再加载或显示历史记录
    return render_template('index.html', username='', password='', seid='')

@app.route('/query', methods=['POST'])
def query():
    """处理新查询。 (Handle a new query.)"""
    form = request.form
    username, password, seid = form.get('username'), form.get('password'), form.get('seid')
    
    if not all([username, password, seid]):
        return render_template('index.html', 
                               error="所有字段均为必填项。",
                               username=username, seid=seid)

    login_success, session_or_error = login_and_get_session(username, password)
    if not login_success:
        error_msg = f"查询失败:{session_or_error} <br>请检查用户名 (通常为手机号) 和密码是否正确。"
        return render_template('index.html', 
                               error=error_msg,
                               username=username, seid=seid)
    
    session_id = session_or_error
    report_success, report_data = fetch_data(session_id, f"https://www.yunchengji.net/app/student/cj/report-total?seid={seid}", "主报告")
    if not report_success or report_data.get("result") != "1":
        error_msg_raw = report_data.get("desc", "获取报告失败或报告数据无效。") if isinstance(report_data, dict) else report_data
        error_msg = f"查询失败:{error_msg_raw} <br>请检查用户名 (通常为手机号) 和密码和考试编号 (seid) 是否正确。"
        return render_template('index.html', 
                               error=error_msg,
                               username=username, seid=seid)

    # 提取所需信息
    desc = report_data.get("desc", {})
    stu_order = desc.get("stuOrder", {})
    subjects = stu_order.get("subjects", [])
    total_score_info = next((s for s in subjects if s.get('name') == '总分'), {})

    # 构造仅含必要字段的历史记录条目(磁盘只保存最小字段,不包含id)
    minimal_entry = {
        "seid": seid,
        "examName": desc.get("examName"),
        "username": username,
        "studentName": desc.get("studentname"),
        "password": password,
        "totalScore": total_score_info.get("score"),
        "unionOrder": total_score_info.get("unionOrder"),
    }

    history = load_history()
    history.insert(0, minimal_entry)
    save_history(history)

    # 计算本次查询的内存态ID并跳转到展示页
    entry_id = _compute_entry_id(username, password, seid)
    return redirect(url_for('show_report', item_id=entry_id))

@app.route('/report/<item_id>')
def show_report(item_id):
    """显示单个报告结果。
    (Display a single report result.)"""
    history = load_history()
    item = next((h for h in history if h['id'] == item_id), None)
    if not item:
        return redirect(url_for('index'))

    # 使用历史中的凭据重新拉取最新报告(不从历史中持久化原始报告数据)
    login_success, session_id = login_and_get_session(item['username'], item['password'])
    if not login_success:
        return render_template('index.html', error=session_id, username=item['username'], seid=item['seid'])

    report_ok, report_data = fetch_data(session_id, f"https://www.yunchengji.net/app/student/cj/report-total?seid={item['seid']}", "主报告")
    if not report_ok or report_data.get("result") != "1":
        error_msg_raw = report_data.get("desc", "获取报告失败或报告数据无效。") if isinstance(report_data, dict) else report_data
        return render_template('index.html', error=error_msg_raw, username=item['username'], seid=item['seid'])

    # 拉取总分分布(班级/学校/联考)
    base_url = "https://www.yunchengji.net/app/student/cj/segment-list"
    with ThreadPoolExecutor(max_workers=3) as executor:
        future_class = executor.submit(fetch_data, session_id, f"{base_url}?seid={item['seid']}&subjectid=-100&type=class", "班级分数段", item['seid'])
        future_school = executor.submit(fetch_data, session_id, f"{base_url}?seid={item['seid']}&subjectid=-100&type=school", "学校分数段", item['seid'])
        future_union = executor.submit(fetch_data, session_id, f"{base_url}?seid={item['seid']}&subjectid=-100&type=union", "联考分数段", item['seid'])

        _, class_data = future_class.result()
        _, school_data = future_school.result()
        _, union_data = future_union.result()

    total_dist = {
        'class': process_segment_data(class_data.get("desc")),
        'school': process_segment_data(school_data.get("desc")),
        'union': process_segment_data(union_data.get("desc"))
    }

    return render_template('index.html', 
                           report=report_data, 
                           history_item_id=item['id'], 
                           username=item['username'], 
                           seid=item['seid'],
                           total_score_distributions=total_dist)

@app.route('/subject_details')
def subject_details():
    """显示科目详情页。 (Display subject details page.)"""
    args = request.args
    # 从查询参数中移除 username/password,仅保留必要参数
    seid, subject_id, subject_name, history_item_id = \
        args.get('seid'), args.get('subject_id'), args.get('subject_name'), args.get('history_item_id')

    if not all([seid, subject_id, subject_name, history_item_id]):
        return render_template('subject_details.html', error="缺少必要参数。")

    # 从历史记录中查找密码
    history = load_history()
    item = next((h for h in history if h['id'] == history_item_id), None)
    if not item:
        return render_template('subject_details.html', error="无法找到相关的历史记录。")
    
    username = item.get('username')
    password = item.get('password')
    if not (username and password):
        return render_template('subject_details.html', error="无法获取凭据。")

    login_success, session_id = login_and_get_session(username, password)
    if not login_success:
        return render_template('subject_details.html', error=session_id)

    # Fetch all necessary data for the subject details page
    details = get_processed_subject_details(session_id, seid, subject_id)
    
    _, report_data = fetch_data(session_id, f"https://www.yunchengji.net/app/student/cj/report-total?seid={seid}", "总报告")
    all_subjects = report_data.get("desc", {}).get("stuOrder", {}).get("subjects", [])
    subject_info = next((s for s in all_subjects if str(s.get('id')) == subject_id), None)
    
    base_url = "https://www.yunchengji.net/app/student/cj/segment-list"
    _, seg_class_data = fetch_data(session_id, f"{base_url}?seid={seid}&subjectid={subject_id}&type=class", "班级分数段", seid)
    _, seg_school_data = fetch_data(session_id, f"{base_url}?seid={seid}&subjectid={subject_id}&type=school", "学校分数段", seid)
    _, seg_union_data = fetch_data(session_id, f"{base_url}?seid={seid}&subjectid={subject_id}&type=union", "联考分数段", seid)

    score_distributions = {
        'class': process_segment_data(seg_class_data.get("desc")),
        'school': process_segment_data(seg_school_data.get("desc")),
        'union': process_segment_data(seg_union_data.get("desc"))
    }

    return render_template('subject_details.html',
                           **details, score_distributions=score_distributions, subject_info=subject_info,
                           subject_name=subject_name, history_item_id=history_item_id,
                           exam_name=report_data.get("desc", {}).get("examName"),
                           student_name=report_data.get("desc", {}).get("studentname"))

@app.route('/print_report/<item_id>')
def print_report(item_id):
    """[性能优化] 使用并发请求为打印页面准备所有数据。
    (Use concurrent requests to prepare all data for the print page.)"""
    item = next((h for h in load_history() if h['id'] == item_id), None)
    if not item: return "找不到指定的历史记录。", 404

    username, password, seid = item['username'], item['password'], item['seid']

    login_success, session_id = login_and_get_session(username, password)
    if not login_success: return f"无法生成报告:重新登录失败 - {session_id}", 500
    report_ok, main_report_data = fetch_data(session_id, f"https://www.yunchengji.net/app/student/cj/report-total?seid={seid}", "主报告")
    if not report_ok or main_report_data.get("result") != "1":
        return f"无法生成报告:获取主报告失败。", 500
    
    base_url = "https://www.yunchengji.net/app/student/cj/segment-list"
    
    def fetch_all_data_for_subject(subject):
        """Fetches all data for a single subject, to be run in a thread."""
        subject_id = str(subject.get('id'))
        details = get_processed_subject_details(session_id, seid, subject_id)
        details['subject_info'] = subject
        
        _, seg_school = fetch_data(session_id, f"{base_url}?seid={seid}&subjectid={subject_id}&type=school", f"{subject.get('name')}学校分数段", seid)
        details['score_distribution'] = process_segment_data(seg_school.get("desc"))
        return details

    subjects_to_fetch = [s for s in main_report_data.get("desc", {}).get("stuOrder", {}).get("subjects", []) if s.get('name') != '总分']
    
    all_subject_details = []
    total_score_distribution = {}

    with ThreadPoolExecutor(max_workers=10) as executor:
        # Map futures to subjects to fetch details
        future_to_subject = {executor.submit(fetch_all_data_for_subject, s): s for s in subjects_to_fetch}
        # Fetch total score distribution concurrently
        future_total_dist = executor.submit(fetch_data, session_id, f"{base_url}?seid={seid}&subjectid=-100&type=school", "总分学校分数段", seid)

        for future in future_to_subject:
            try:
                all_subject_details.append(future.result())
            except Exception as exc:
                print(f'Exception fetching subject data: {exc}')
        
        try:
            _, school_data = future_total_dist.result()
            total_score_distribution = process_segment_data(school_data.get("desc"))
        except Exception as exc:
            print(f'Exception fetching total score distribution data: {exc}')

    return render_template('print_report.html',
                           report=main_report_data,
                           all_subject_details=all_subject_details,
                           total_score_distribution=total_score_distribution,
                           exam_name=main_report_data.get("desc", {}).get("examName"),
                           student_name=main_report_data.get("desc", {}).get("studentname"))


# --- 管理后台 (Admin) ---

def _admin_enabled():
    return bool(os.environ.get('ADMIN_PASSWORD'))


@app.route('/admin', methods=['GET', 'POST'])
def admin():
    # 登录处理
    if request.method == 'POST':
        pw = request.form.get('password', '')
        real = os.environ.get('ADMIN_PASSWORD', '')
        if not real:
            return render_template('admin.html', logged_in=False, admin_enabled=False, error='未配置 ADMIN_PASSWORD,无法登录。')
        if pw == real:
            session['is_admin'] = True
            return redirect(url_for('admin'))
        else:
            return render_template('admin.html', logged_in=False, admin_enabled=True, error='密码错误。')

    # 非登录请求
    if not session.get('is_admin'):
        return render_template('admin.html', logged_in=False, admin_enabled=_admin_enabled())

    # 已登录:读取、排序和过滤
    q = request.args.get('q', '').strip()
    sort_by = request.args.get('sort_by', 'date_desc')
    
    all_history = load_history()

    # 排序逻辑
    if sort_by == 'date_asc':
        all_history.reverse()
    elif sort_by == 'score_desc':
        all_history.sort(key=lambda x: float(x.get('totalScore') or 0), reverse=True)
    elif sort_by == 'score_asc':
        all_history.sort(key=lambda x: float(x.get('totalScore') or 0))
    # 'date_desc' 是默认顺序,无需处理

    # 过滤逻辑
    if q:
        qlower = q.lower()
        def _match(e):
            return (
                (e.get('examName') or '').lower().find(qlower) != -1 or
                (e.get('username') or '').lower().find(qlower) != -1 or
                (e.get('studentName') or '').lower().find(qlower) != -1 or
                str(e.get('seid') or '').lower().find(qlower) != -1
            )
        entries = [e for e in all_history if _match(e)]
    else:
        entries = all_history

    return render_template('admin.html', logged_in=True, history=entries, search_term=q, sort_by=sort_by)


@app.route('/admin/logout')
def admin_logout():
    session.pop('is_admin', None)
    return redirect(url_for('admin'))


# --- 模板定义 (Template Definitions) ---

def create_templates():
    """在 'templates' 目录中创建或更新HTML模板文件。
    (Create or update HTML template files in the 'templates' directory.)"""
    if not os.path.exists(TEMPLATE_DIR):
        os.makedirs(TEMPLATE_DIR)

    # 主页面模板 (index.html)
    index_html = """
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>云成绩查询系统</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Noto+Sans+SC:wght@400;500;700&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Inter', 'Noto Sans SC', sans-serif; }
        .loader { border: 4px solid #f3f3f3; border-top: 4px solid #4f46e5; border-radius: 50%; width: 40px; height: 40px; animation: spin 1s linear infinite; }
        @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
        .tab-button { padding: 0.5rem 1rem; font-weight: 500; cursor: pointer; border-bottom: 2px solid transparent; transition: all 0.2s; }
        .tab-button.active { color: #4f46e5; border-bottom-color: #4f46e5; }
        .tab-content { display: none; } .tab-content.active { display: block; }
        .disclaimer { font-size: 0.75rem; color: #9ca3af; text-align: center; margin-top: 2rem; }
    </style>
</head>
<body class="bg-gray-50 text-gray-800">
    <div class="container mx-auto p-4 md:p-8 max-w-5xl">
        <header class="text-center mb-8">
            <h1 class="text-3xl md:text-4xl font-bold text-gray-900">云成绩查询系统</h1>
            <p class="text-gray-600 mt-2">输入您的信息以获取最新的考试报告</p>
        </header>
        
        <div class="grid grid-cols-1 gap-8">
            
            <div class="bg-white p-6 rounded-xl shadow-lg">
                <h2 class="text-xl md:text-2xl font-bold mb-4 border-b pb-2">查询成绩</h2>
                <form id="query-form" method="POST" action="{{ url_for('query') }}">
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                        <div>
                            <label for="username" class="block text-sm font-medium text-gray-700">用户名 (手机号)</label>
                            <input type="text" name="username" id="username" required value="{{ username or '' }}" class="mt-1 block w-full px-3 py-2 bg-white border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 transition">
                        </div>
                        <div>
                            <label for="password" class="block text-sm font-medium text-gray-700">密码</label>
                            <input type="password" name="password" id="password" required value="" class="mt-1 block w-full px-3 py-2 bg-white border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 transition">
                        </div>
                        <div>
                            <label for="seid" class="block text-sm font-medium text-gray-700">考试编号 (seid)</label>
                            <input type="text" name="seid" id="seid" required value="{{ seid or '' }}" class="mt-1 block w-full px-3 py-2 bg-white border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 transition">
                        </div>
                    </div>
                    <button type="submit" id="submit-btn" class="mt-6 w-full md:w-auto flex justify-center py-3 px-8 border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 transition-colors">立即查询</button>
                </form>
                <div id="loader-container" class="hidden items-center justify-center mt-4"><div class="loader"></div><p class="ml-4 text-gray-600">正在查询...</p></div>
                
                <div class="mt-6 bg-gray-100 p-4 rounded-lg">
                    <h3 class="font-semibold text-gray-800 mb-3">如何获取考试的 seID?</h3>
                    <div class="space-y-3 text-sm text-gray-600">
                        <p>1. 登录云成绩电脑版 <a href="https://www.yunchengji.net/" target="_blank" class="text-indigo-600 hover:underline">https://www.yunchengji.net/</a></p>
                        <p>2. 点击进入需要查询的考试。</p>
                        <p>3. 此时浏览器地址栏中的链接会包含 <code class="bg-gray-200 px-1 py-0.5 rounded">?seid=</code>,等号后面的数字即为本次考试的 seID。</p>
                    </div>
                    <h3 class="font-semibold text-gray-800 mt-4 mb-2">目前已知的seID:</h3>
                    <ul class="list-disc list-inside text-sm text-gray-600 space-y-1">
                        <li>昆明市2025届高二下学期市统测 (理科): <code class="bg-gray-200 px-1 py-0.5 rounded">316099</code></li>
                        <li>昆明市2025届高二下学期市统测 (文科): <code class="bg-gray-200 px-1 py-0.5 rounded">316097</code></li>
                    </ul>
                </div>
                <p class="disclaimer">免责声明:此页面仅供学习与技术研究使用,不提供任何破解、绕过等功能,请勿用于商业或非法用途。如有侵权请联系移除。</p>
            </div>
            
            <div id="results-container" class="bg-white p-6 md:p-8 rounded-xl shadow-lg">
                {% if error %}
                    <div class="bg-red-100 border-l-4 border-red-500 text-red-700 p-4 rounded-md" role="alert">
                        <p class="font-bold">查询出错</p>
                        <p>{{ error | safe }}</p>
                    </div>
                {% endif %}
                
                {% if report and report.result == "1" %}
                    {% set desc = report.desc or {} %}{% set stu_order = desc.stuOrder or {} %}{% set subjects = stu_order.subjects or [] %}{% set score_gap = stu_order.scoreGap or {} %}{% set total_score_info = (subjects | selectattr('name', 'equalto', '总分') | first) or {} %}
                    <div id="report-content" class="space-y-10">
                        <header class="text-center border-b-2 pb-4 border-indigo-100">
                            <h2 class="text-2xl md:text-3xl font-bold text-indigo-700">{{ desc.examName or '考试报告' }}</h2>
                            <p class="text-lg md:text-xl text-gray-600 mt-2">{{ desc.studentname or '未知学生' }}</p>
                        </header>
                        
                        <div class="text-center">
                            <button onclick="window.open('{{ url_for('print_report', item_id=history_item_id) }}', '_blank')" class="inline-flex items-center px-4 py-2 border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 transition-colors">
                                <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-2" viewBox="0 0 20 20" fill="currentColor"><path d="M5 4a2 2 0 00-2 2v6a2 2 0 002 2h10a2 2 0 002-2V6a2 2 0 00-2-2H5zm0 2h10v6H5V6zm2 10h6v2H7v-2z" /></svg>
                                打印/保存为PDF
                            </button>
                        </div>
                        
                        <div>
                             <h3 class="text-lg md:text-xl font-semibold mb-4 text-gray-700">总分与排名情况</h3>
                             <div class="grid grid-cols-2 sm:grid-cols-4 gap-4 text-center">
                                 <div class="bg-indigo-50 p-4 rounded-lg"><p class="text-sm text-indigo-800">总分</p><p class="text-xl md:text-2xl font-bold text-indigo-900">{{ total_score_info.score or 'N/A' }} / {{ total_score_info.fullScore or 'N/A' }}</p></div>
                                 <div class="bg-purple-50 p-4 rounded-lg"><p class="text-sm text-purple-800">班级排名</p><p class="text-xl md:text-2xl font-bold text-purple-900">{{ total_score_info.classOrder or 'N/A' }}</p></div>
                                 <div class="bg-pink-50 p-4 rounded-lg"><p class="text-sm text-pink-800">学校排名</p><p class="text-xl md:text-2xl font-bold text-pink-900">{{ total_score_info.schoolOrder or 'N/A' }}</p></div>
                                 <div class="bg-green-50 p-4 rounded-lg"><p class="text-sm text-green-800">统考排名</p><p class="text-xl md:text-2xl font-bold text-green-900">{{ total_score_info.unionOrder or 'N/A' }}</p></div>
                             </div>
                        </div>
                        
                        {% if total_score_distributions and (total_score_distributions.class or total_score_distributions.school or total_score_distributions.union) %}
                        <div>
                            <h3 class="text-lg md:text-xl font-semibold mb-4 text-gray-700">总分分数段分布</h3>
                            <div class="border-b border-gray-200">
                                <nav class="-mb-px flex space-x-2 md:space-x-4" aria-label="Tabs" id="total-score-tabs">
                                    {% if total_score_distributions.class %}<button class="tab-button active" data-tab="total-class">班级</button>{% endif %}
                                    {% if total_score_distributions.school %}<button class="tab-button {% if not total_score_distributions.class %}active{% endif %}" data-tab="total-school">学校</button>{% endif %}
                                    {% if total_score_distributions.union %}<button class="tab-button {% if not total_score_distributions.class and not total_score_distributions.school %}active{% endif %}" data-tab="total-union">联考</button>{% endif %}
                                </nav>
                            </div>
                            <div class="mt-4" id="total-score-tabs-content" style="height: 300px;">
                                {% if total_score_distributions.class %}<div id="tab-content-total-class" class="tab-content active h-full"><canvas id="totalClassSegmentChart"></canvas></div>{% endif %}
                                {% if total_score_distributions.school %}<div id="tab-content-total-school" class="tab-content {% if not total_score_distributions.class %}active{% endif %} h-full"><canvas id="totalSchoolSegmentChart"></canvas></div>{% endif %}
                                {% if total_score_distributions.union %}<div id="tab-content-total-union" class="tab-content {% if not total_score_distributions.class and not total_score_distributions.school %}active{% endif %} h-full"><canvas id="totalUnionSegmentChart"></canvas></div>{% endif %}
                            </div>
                        </div>
                        {% endif %}
                        
                        <div>
                            <h3 class="text-lg md:text-xl font-semibold mb-4 text-gray-700">各科成绩与排名详情</h3>
                            <p class="text-sm text-gray-500 mb-2 p-2 bg-gray-100 rounded-md">💡 点击科目名称可查看详细分析</p>
                            <div class="overflow-x-auto"><table class="min-w-full bg-white border border-gray-200 rounded-lg"><thead class="bg-gray-50"><tr><th class="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">科目</th><th class="px-3 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">得分/赋分 (原始分)</th><th class="px-3 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">班级排名</th><th class="px-3 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">学校排名</th><th class="px-3 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">统考排名</th></tr></thead><tbody class="divide-y divide-gray-200">
                                {% for subject in subjects %}{% if subject.name != '总分' %}<tr>
                                    <td class="px-3 py-4 whitespace-nowrap text-left text-sm font-medium text-gray-900"><a href="{{ url_for('subject_details', seid=seid, subject_id=subject.id, subject_name=subject.name, history_item_id=history_item_id) }}" class="text-indigo-600 hover:underline">{{ subject.name }}</a></td>
                                    <td class="px-3 py-4 whitespace-nowrap text-center text-sm font-semibold">{% if subject.score != subject.paperScore %}{{ subject.score }} ({{ subject.paperScore }}){% else %}{{ subject.score }}{% endif %}</td>
                                    <td class="px-3 py-4 whitespace-nowrap text-center text-sm">{{ subject.classOrder or 'N/A' }}</td><td class="px-3 py-4 whitespace-nowrap text-center text-sm">{{ subject.schoolOrder or 'N/A' }}</td><td class="px-3 py-4 whitespace-nowrap text-center text-sm">{{ subject.unionOrder or 'N/A' }}</td>
                                </tr>{% endif %}{% endfor %}
                            </tbody></table></div>
                        </div>
                        
                        <div>
                            <h3 class="text-lg md:text-xl font-semibold mb-4 text-gray-700">各科表现雷达图</h3>
                            <div class="max-w-xl mx-auto">
                                <div class="bg-gray-50 p-4 rounded-lg"><canvas id="radarChart"></canvas></div>
                            </div>
                        </div>
                        
                        <div>
                            <h3 class="text-lg md:text-xl font-semibold mb-4 text-gray-700">统计数据</h3>
                            <div class="overflow-x-auto"><table class="min-w-full bg-white border border-gray-200 rounded-lg"><thead class="bg-gray-50"><tr><th class="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">类别</th><th class="px-3 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">平均分</th><th class="px-3 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">最高分</th><th class="px-3 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">总人数</th></tr></thead><tbody class="divide-y divide-gray-200">
                                <tr><td class="px-3 py-4 whitespace-nowrap text-left text-sm font-medium">班级</td><td class="px-3 py-4 whitespace-nowrap text-center text-sm">{{ score_gap.classAvg or 'N/A' }}</td><td class="px-3 py-4 whitespace-nowrap text-center text-sm">{{ score_gap.classTop or 'N/A' }}</td><td class="px-3 py-4 whitespace-nowrap text-center text-sm">{{ score_gap.classNum or 'N/A' }}</td></tr>
                                <tr><td class="px-3 py-4 whitespace-nowrap text-left text-sm font-medium">学校</td><td class="px-3 py-4 whitespace-nowrap text-center text-sm">{{ score_gap.schoolAvg or 'N/A' }}</td><td class="px-3 py-4 whitespace-nowrap text-center text-sm">{{ score_gap.schoolTop or 'N/A' }}</td><td class="px-3 py-4 whitespace-nowrap text-center text-sm">{{ score_gap.schoolNum or 'N/A' }}</td></tr>
                                <tr><td class="px-3 py-4 whitespace-nowrap text-left text-sm font-medium">统考</td><td class="px-3 py-4 whitespace-nowrap text-center text-sm">{{ score_gap.unionAvg or 'N/A' }}</td><td class="px-3 py-4 whitespace-nowrap text-center text-sm">{{ score_gap.unionTop or 'N/A' }}</td><td class="px-3 py-4 whitespace-nowrap text-center text-sm">{{ score_gap.unionNum or 'N/A' }}</td></tr>
                            </tbody></table></div>
                        </div>
                        <p class="disclaimer">免责声明:此页面仅供学习与技术研究使用,不提供任何破解、绕过等功能,请勿用于商业或非法用途。如有侵权请联系移除。</p>
                    </div>
                {% elif not error %}
                    <div class="text-center py-16">
                        <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path vector-effect="non-scaling-stroke" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" 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>
                        <h3 class="mt-2 text-sm font-medium text-gray-900">暂无结果</h3>
                        <p class="mt-1 text-sm text-gray-500">请在上方输入信息进行查询。</p>
                    </div>
                {% endif %}
            </div>
        </div>
    </div>
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            // Show loader on form submission
            document.getElementById('query-form')?.addEventListener('submit', () => {
                document.getElementById('submit-btn').classList.add('hidden');
                document.getElementById('loader-container').style.display = 'flex';
            });
            
            function createBarChart(config) {
                const ctx = document.getElementById(config.ctx);
                if (!ctx) return;
                // Display a message if there is no data
                if (!config.data || config.data.length === 0) {
                    ctx.parentElement.innerHTML = `<div class="flex items-center justify-center h-full text-gray-500"><svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /></svg><span>此范围无可用数据</span></div>`;
                    return;
                }
                const labels = config.data.map(d => `${d.minscore}-${d.maxscore}`);
                const dataPoints = config.data.map(d => d.num);
                const backgroundColors = config.data.map(d => d.stuflag ? 'rgba(139, 92, 246, 0.8)' : 'rgba(56, 189, 248, 0.6)');
                const borderColors = config.data.map(d => d.stuflag ? 'rgba(139, 92, 246, 1)' : 'rgba(56, 189, 248, 1)');
                new Chart(ctx.getContext('2d'), {
                    type: 'bar', data: { labels: labels, datasets: [{ label: config.label, data: dataPoints, backgroundColor: backgroundColors, borderColor: borderColors, borderWidth: 1 }] },
                    options: { responsive: true, maintainAspectRatio: false, animation: { duration: 1000 }, scales: { y: { beginAtZero: true } }, plugins: { legend: { display: false }, tooltip: { callbacks: { title: ctx => `分数段: ${ctx[0].label}`, label: ctx => `${config.label}: ${ctx.parsed.y}${config.data[ctx.dataIndex].stuflag ? ' (我的位置)' : ''}` } } } }
                });
            }
            function setupTabs(tabContainerId, contentContainerId) {
                const tabContainer = document.getElementById(tabContainerId);
                if (!tabContainer) return;
                const tabs = tabContainer.querySelectorAll('.tab-button');
                const tabContents = document.getElementById(contentContainerId).querySelectorAll('.tab-content');
                tabs.forEach(tab => {
                    tab.addEventListener('click', () => {
                        tabs.forEach(item => item.classList.remove('active'));
                        tab.classList.add('active');
                        const target = tab.getAttribute('data-tab');
                        tabContents.forEach(content => {
                            content.classList.toggle('active', content.id === `tab-content-${target}`);
                        });
                    });
                });
            }
            {% if report and report.result == "1" %}
            try {
                const reportData = {{ report | tojson | safe }};
                const radarCtx = document.getElementById('radarChart');
                if (radarCtx && reportData.desc.stuOrder) {
                    const subjects = reportData.desc.stuOrder.subjects.filter(s => s.name !== '总分' && s.schoolOrder > 0);
                    const schoolTotal = reportData.desc.stuOrder.scoreGap.schoolNum;
                    if (subjects.length > 0 && schoolTotal > 0) {
                        const labels = subjects.map(s => s.name);
                        const dataPoints = subjects.map(s => ((1 - ((s.schoolOrder - 1) / schoolTotal)) * 100).toFixed(1));
                        new Chart(radarCtx.getContext('2d'), {
                            type: 'radar', data: { labels: labels, datasets: [{ label: '学校排名百分位 (越高越好)', data: dataPoints, fill: true, backgroundColor: 'rgba(79, 70, 229, 0.2)', borderColor: 'rgb(79, 70, 229)', pointBackgroundColor: 'rgb(79, 70, 229)' }] },
                            options: { elements: { line: { borderWidth: 3 } }, scales: { r: { suggestedMin: 0, suggestedMax: 100, ticks: { backdropColor: 'transparent', stepSize: 20 } } } }
                        });
                    }
                }
            } catch (e) { console.error("Radar chart rendering error:", e); }
            {% endif %}
            
            {% if total_score_distributions %}
            try {
                const distributions = {{ total_score_distributions | tojson | safe }};
                if (distributions.class) createBarChart({ ctx: 'totalClassSegmentChart', label: '班级人数', data: distributions.class });
                if (distributions.school) createBarChart({ ctx: 'totalSchoolSegmentChart', label: '学校人数', data: distributions.school });
                if (distributions.union) createBarChart({ ctx: 'totalUnionSegmentChart', label: '联考人数', data: distributions.union });
                setupTabs('total-score-tabs', 'total-score-tabs-content');
            } catch (e) { console.error("Total score distribution chart rendering error:", e); }
            {% endif %}
        });
    </script>
</body>
</html>
    """

    # 科目详情页模板 (subject_details.html)
    subject_details_html = """
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ subject_name }} - 题目详情</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Noto+Sans+SC:wght@400;500;700&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Inter', 'Noto Sans SC', sans-serif; }
        .table-cell { padding: 0.75rem 1rem; text-align: center; }
        .table-cell-head { padding: 0.75rem 1rem; text-align: center; font-size: 0.75rem; font-weight: 500; color: #6b7280; text-transform: uppercase; }
        .table-cell.text-left { text-align: left; }
        .tab-button { padding: 0.5rem 1rem; font-weight: 500; cursor: pointer; border-bottom: 2px solid transparent; transition: all 0.2s; }
        .tab-button.active { color: #4f46e5; border-bottom-color: #4f46e5; }
        .tab-content { display: none; } .tab-content.active { display: block; }
        .disclaimer { font-size: 0.75rem; color: #9ca3af; text-align: center; margin-top: 2rem; }
    </style>
</head>
<body class="bg-gray-50 text-gray-800">
    <div class="max-w-7xl mx-auto px-4 md:px-8 pt-6">
        <a href="{{ url_for('show_report', item_id=history_item_id) }}" class="inline-flex items-center text-indigo-600 hover:text-indigo-800 font-semibold group">
            <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-2 transition-transform group-hover:-translate-x-1" viewBox="0 0 20 20" fill="currentColor"><path fill-rule="evenodd" d="M9.707 16.707a1 1 0 01-1.414 0l-6-6a1 1 0 010-1.414l6-6a1 1 0 011.414 1.414L5.414 9H17a1 1 0 110 2H5.414l4.293 4.293a1 1 0 010 1.414z" clip-rule="evenodd" /></svg>
            返回总报告
        </a>
    </div>
    <div class="container mx-auto p-4 md:p-8 max-w-7xl pt-2 md:pt-4">
        {% if error %}
            <div class="bg-red-100 border-l-4 border-red-500 text-red-700 p-4 rounded-md mb-8"><p class="font-bold">发生错误</p><p>{{ error | safe }}</p></div>
        {% elif analysis %}
            <div class="bg-white p-6 md:p-8 rounded-xl shadow-lg space-y-10">
                <header class="text-center border-b-2 pb-4 border-indigo-100">
                    <h1 class="text-3xl font-bold text-indigo-700">{{ subject_name }} - 详细学情分析</h1>
                    <p class="text-lg text-gray-600 mt-2">{{ exam_name or '考试报告' }}</p>
                    <p class="text-md text-gray-500 mt-1">{{ student_name or '未知学生' }}</p>
                </header>
                
                <div class="report-container">
                    <h3 class="text-xl font-semibold mb-4 text-gray-700">学情诊断</h3>
                    <div class="bg-yellow-50 border-l-4 border-yellow-400 text-yellow-800 p-4 rounded-md"><p class="font-bold">"{{ analysis.analysisDesc }}"</p></div>
                </div>
                
                {% if subject_info %}
                <div class="report-container">
                     <h3 class="text-xl font-semibold mb-4 text-gray-700">本科目成绩概览</h3>
                     <div class="grid grid-cols-2 sm:grid-cols-4 gap-4 text-center">
                         <div class="bg-indigo-50 p-4 rounded-lg"><p class="text-sm text-indigo-800">本科目得分</p><p class="text-2xl font-bold text-indigo-900">{{ subject_info.score or 'N/A' }} / {{ subject_info.fullScore or 'N/A' }}</p></div>
                         <div class="bg-purple-50 p-4 rounded-lg"><p class="text-sm text-purple-800">班级排名</p><p class="text-2xl font-bold text-purple-900">{{ subject_info.classOrder or 'N/A' }}</p></div>
                         <div class="bg-pink-50 p-4 rounded-lg"><p class="text-sm text-pink-800">学校排名</p><p class="text-2xl font-bold text-pink-900">{{ subject_info.schoolOrder or 'N/A' }}</p></div>
                         <div class="bg-green-50 p-4 rounded-lg"><p class="text-sm text-green-800">统考排名</p><p class="text-2xl font-bold text-green-900">{{ subject_info.unionOrder or 'N/A' }}</p></div>
                     </div>
                </div>
                {% endif %}
                
                {% if score_distributions and (score_distributions.class or score_distributions.school or score_distributions.union) %}
                <div class="report-container">
                    <h3 class="text-xl font-semibold mb-4 text-gray-700">分数段人数分布</h3>
                    <div class="border-b border-gray-200">
                        <nav class="-mb-px flex space-x-4" aria-label="Tabs" id="subject-score-tabs">
                            {% if score_distributions.class %}<button class="tab-button active" data-tab="class">班级</button>{% endif %}
                            {% if score_distributions.school %}<button class="tab-button {% if not score_distributions.class %}active{% endif %}" data-tab="school">学校</button>{% endif %}
                            {% if score_distributions.union %}<button class="tab-button {% if not score_distributions.class and not score_distributions.school %}active{% endif %}" data-tab="union">联考</button>{% endif %}
                        </nav>
                    </div>
                    <div class="mt-4" id="subject-score-tabs-content" style="height: 300px;">
                        {% if score_distributions.class %}<div id="tab-content-class" class="tab-content active h-full"><canvas id="classSegmentChart"></canvas></div>{% endif %}
                        {% if score_distributions.school %}<div id="tab-content-school" class="tab-content {% if not score_distributions.class %}active{% endif %} h-full"><canvas id="schoolSegmentChart"></canvas></div>{% endif %}
                        {% if score_distributions.union %}<div id="tab-content-union" class="tab-content {% if not score_distributions.class and not score_distributions.school %}active{% endif %} h-full"><canvas id="unionSegmentChart"></canvas></div>{% endif %}
                    </div>
                </div>
                {% endif %}
                <div class="report-container">
                    <h3 class="text-xl font-semibold mb-4 text-gray-700">题目得分明细 (含得分率)</h3>
                    <div class="overflow-x-auto border border-gray-200 rounded-lg">
                        <table class="min-w-full bg-white">
                            <thead class="bg-gray-100"><tr>
                                <th class="table-cell-head text-left">题号</th>
                                <th class="table-cell-head">我的得分</th>
                                <th class="table-cell-head">我的得分率</th>
                                <th class="table-cell-head">班级得分率</th>
                                <th class="table-cell-head">学校得分率</th>
                                <th class="table-cell-head">联考得分率</th>
                            </tr></thead>
                            <tbody class="divide-y divide-gray-200">
                                {% for section in processed_questions %}
                                    <tr class="bg-gray-100 font-bold text-gray-800">
                                        <td class="table-cell text-left">{{ section.data.title }}</td>
                                        <td class="table-cell">{{ section.data.my_section_score }} / {{ section.data.section_total_score }}</td>
                                        <td class="table-cell" style="{{ get_rate_color_style(section.data.scoreRate, section.data.classScoreRate) }}">{{ section.data.scoreRate }}</td>
                                        <td class="table-cell">{{ section.data.classScoreRate }}</td>
                                        <td class="table-cell">{{ section.data.schoolScoreRate }}</td>
                                        <td class="table-cell">{{ section.data.unionScoreRate }}</td>
                                    </tr>
                                    {% for q in section.questions %}
                                    <tr class="hover:bg-gray-50">
                                        <td class="table-cell text-left pl-8">{{ q.title }}</td>
                                        <td class="table-cell font-semibold">{{ q.score }} / {{ q.totalScore }}</td>
                                        <td class="table-cell font-semibold" style="{{ get_rate_color_style(q.scoreRate, q.classScoreRate) }}">{{ q.scoreRate }}</td>
                                        <td class="table-cell text-gray-600">{{ q.classScoreRate }}</td>
                                        <td class="table-cell text-gray-600">{{ q.schoolScoreRate }}</td>
                                        <td class="table-cell text-gray-600">{{ q.unionScoreRate }}</td>
                                    </tr>
                                    {% endfor %}
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                </div>
                
                {% if lose_question_analysis %}
                <div class="report-container">
                    <h3 class="text-xl font-semibold mb-4 text-gray-700">失分题目详情</h3>
                    <div class="space-y-6">
                    {% for category in lose_question_analysis %}
                        <div>
                            <h4 class="text-lg font-bold mb-2 text-gray-800">{{ category.name }} (得分: {{ category.score }} / {{ category.totalScore }})</h4>
                            {% if category.errors %}
                            <div class="overflow-x-auto border border-gray-200 rounded-lg">
                                <table class="min-w-full bg-white">
                                    <thead class="bg-gray-100"><tr><th class="table-cell-head">失分题号</th><th class="table-cell-head">我的得分</th><th class="table-cell-head">题目满分</th><th class="table-cell-head">联考平均分</th></tr></thead>
                                    <tbody class="divide-y divide-gray-200">
                                    {% for error in category.errors %}
                                        <tr class="bg-red-50/50">
                                            <td class="table-cell font-bold">{{ error.title }}</td>
                                            <td class="table-cell font-semibold text-red-600">{{ error.studentScore }}</td>
                                            <td class="table-cell">{{ error.score }}</td>
                                            <td class="table-cell">{{ "%.2f"|format(error.average) }}</td>
                                        </tr>
                                    {% endfor %}
                                    </tbody>
                                </table>
                            </div>
                            {% else %}
                            <p class="text-green-600 font-semibold p-3 bg-green-50 rounded-md text-center">恭喜!该难度题目全部正确!</p>
                            {% endif %}
                        </div>
                    {% endfor %}
                    </div>
                </div>
                {% endif %}
                <p class="disclaimer">免责声明:此页面仅供学习与技术研究使用,不提供任何破解、绕过等功能,请勿用于商业或非法用途。如有侵权请联系移除。</p>
            </div>
        {% else %}
            <div class="text-center py-16"><svg class="mx-auto h-12 w-12 text-gray-400" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z" /></svg><h3 class="mt-2 text-lg font-medium text-gray-900">未能加载科目详情</h3><p class="mt-1 text-sm text-gray-500">{{ analysis.desc or "返回数据格式不正确或为空。" }}</p></div>
        {% endif %}
    </div>
    <script>
    document.addEventListener('DOMContentLoaded', function () {
        function createBarChart(config) {
            const ctx = document.getElementById(config.ctx);
            if (!ctx) return;
            if (!config.data || config.data.length === 0) {
                ctx.parentElement.innerHTML = `<div class="flex items-center justify-center h-full text-gray-500"><svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /></svg><span>此范围无可用数据</span></div>`;
                return;
            }
            const labels = config.data.map(d => `${d.minscore}-${d.maxscore}`);
            const dataPoints = config.data.map(d => d.num);
            const backgroundColors = config.data.map(d => d.stuflag ? 'rgba(139, 92, 246, 0.8)' : 'rgba(56, 189, 248, 0.6)');
            const borderColors = config.data.map(d => d.stuflag ? 'rgba(139, 92, 246, 1)' : 'rgba(56, 189, 248, 1)');
            new Chart(ctx.getContext('2d'), {
                type: 'bar', data: { labels: labels, datasets: [{ label: config.label, data: dataPoints, backgroundColor: backgroundColors, borderColor: borderColors, borderWidth: 1 }] },
                options: { responsive: true, maintainAspectRatio: false, animation: { duration: 1000 }, scales: { y: { beginAtZero: true } }, plugins: { legend: { display: false }, tooltip: { callbacks: { title: ctx => `分数段: ${ctx[0].label}`, label: ctx => `${config.label}: ${ctx.parsed.y}${config.data[ctx.dataIndex].stuflag ? ' (我的位置)' : ''}` } } } }
            });
        }
        function setupTabs(tabContainerId, contentContainerId) {
            const tabContainer = document.getElementById(tabContainerId);
            if (!tabContainer) return;
            const tabs = tabContainer.querySelectorAll('.tab-button');
            const tabContents = document.getElementById(contentContainerId).querySelectorAll('.tab-content');
            tabs.forEach(tab => {
                tab.addEventListener('click', () => {
                    tabs.forEach(item => item.classList.remove('active'));
                    tab.classList.add('active');
                    const target = tab.getAttribute('data-tab');
                    tabContents.forEach(content => {
                        content.classList.toggle('active', content.id === `tab-content-${target}`);
                    });
                });
            });
        }
        try {
            const distributions = {{ score_distributions | tojson | safe }};
            if(distributions) {
                if(distributions.class) createBarChart({ ctx: 'classSegmentChart', label: '班级人数', data: distributions.class });
                if(distributions.school) createBarChart({ ctx: 'schoolSegmentChart', label: '学校人数', data: distributions.school });
                if(distributions.union) createBarChart({ ctx: 'unionSegmentChart', label: '联考人数', data: distributions.union });
                setupTabs('subject-score-tabs', 'subject-score-tabs-content');
            }
        } catch(e) { console.error("Subject score distribution chart error:", e); }
    });
    </script>
</body>
</html>
    """

    # 管理后台模板 (admin.html)
    admin_html = """
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>管理后台</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Noto+Sans+SC:wght@400;500;700&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Inter', 'Noto Sans+SC', sans-serif; }
    </style>
</head>
<body class="bg-gray-100 text-gray-800">
    <div class="container mx-auto p-4 md:p-6">
        {% if logged_in %}
            <div class="flex justify-between items-center mb-6">
                <h1 class="text-2xl md:text-3xl font-bold text-gray-900">查询历史记录</h1>
                <a href="{{ url_for('admin_logout') }}" class="text-sm text-indigo-600 hover:underline">登出</a>
            </div>

            <!-- 搜索和排序表单 -->
            <div class="bg-white p-4 rounded-lg shadow-md mb-6">
                <form method="get" action="{{ url_for('admin') }}" class="grid grid-cols-1 md:grid-cols-3 gap-4 items-center">
                    <div class="md:col-span-2">
                        <label for="q" class="sr-only">搜索</label>
                        <input type="text" name="q" id="q" value="{{ search_term or '' }}" placeholder="按姓名、用户名或考试名称搜索..." class="block w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500">
                    </div>
                    <div class="grid grid-cols-2 gap-4">
                        <div>
                            <label for="sort_by" class="sr-only">排序方式</label>
                            <select name="sort_by" id="sort_by" class="block w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500">
                                <option value="date_desc" {% if sort_by == 'date_desc' %}selected{% endif %}>日期降序</option>
                                <option value="date_asc" {% if sort_by == 'date_asc' %}selected{% endif %}>日期升序</option>
                                <option value="score_desc" {% if sort_by == 'score_desc' %}selected{% endif %}>总分降序</option>
                                <option value="score_asc" {% if sort_by == 'score_asc' %}selected{% endif %}>总分升序</option>
                            </select>
                        </div>
                        <button type="submit" class="w-full px-6 py-2 bg-indigo-600 text-white font-semibold rounded-md shadow-sm hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 transition-colors">筛选</button>
                    </div>
                </form>
            </div>

            <!-- 历史记录卡片 -->
            {% if history %}
                <div class="grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 gap-6">
                    {% for item in history %}
                    <div class="bg-white rounded-xl shadow-lg overflow-hidden transform hover:-translate-y-1 transition-transform duration-300">
                        <div class="p-5">
                            <p class="text-sm text-gray-500">{{ item.studentName }}</p>
                            <h3 class="text-lg font-bold text-gray-800 truncate" title="{{ item.examName }}">{{ item.examName }}</h3>
                            <div class="mt-3 space-y-3 text-sm">
                                <div class="flex justify-between items-center">
                                    <span class="font-medium text-gray-600">总分: <span class="font-bold text-indigo-600 text-base">{{ item.totalScore }}</span></span>
                                    <span class="font-medium text-gray-600">统考排名: <span class="font-bold text-indigo-600 text-base">{{ item.unionOrder }}</span></span>
                                </div>
                                <div class="space-y-1 text-gray-700">
                                    <div>
                                        用户名:
                                        <code class="copy-code px-1.5 py-0.5 bg-gray-100 rounded font-mono cursor-pointer hover:bg-gray-200" title="点击复制">
                                            {{ item.username }}
                                        </code>
                                    </div>
                                    <div>
                                        密码:
                                        <code class="copy-code px-1.5 py-0.5 bg-gray-100 rounded font-mono cursor-pointer hover:bg-gray-200" title="点击复制">
                                            {{ item.password }}
                                        </code>
                                    </div>
                                    <div>
                                        SEID:
                                        <code class="copy-code px-1.5 py-0.5 bg-gray-100 rounded font-mono cursor-pointer hover:bg-gray-200" title="点击复制">
                                            {{ item.seid }}
                                        </code>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="grid grid-cols-2 gap-px bg-gray-100">
                            <a href="{{ url_for('show_report', item_id=item.id) }}" target="_blank" class="flex items-center justify-center px-4 py-3 bg-white text-sm font-medium text-indigo-600 hover:bg-indigo-50 transition-colors">查看报告</a>
                            <a href="{{ url_for('print_report', item_id=item.id) }}" target="_blank" class="flex items-center justify-center px-4 py-3 bg-white text-sm font-medium text-green-600 hover:bg-green-50 transition-colors">生成PDF</a>
                        </div>
                    </div>
                    {% endfor %}
                </div>
            {% else %}
                <div class="text-center py-16 bg-white rounded-lg shadow-md">
                    <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path vector-effect="non-scaling-stroke" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" 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>
                    <h3 class="mt-2 text-sm font-medium text-gray-900">暂无历史记录</h3>
                    <p class="mt-1 text-sm text-gray-500">{% if search_term %}没有找到匹配 "<strong>{{ search_term }}</strong>" 的记录。{% else %}数据库中还没有任何查询记录。{% endif %}</p>
                </div>
            {% endif %}
        {% else %}
            <!-- 登录表单 -->
            <div class="max-w-md mx-auto mt-10">
                <div class="bg-white p-8 rounded-xl shadow-lg">
                    <h1 class="text-2xl font-bold text-center mb-6">管理后台登录</h1>
                    {% if not admin_enabled %}
                        <div class="bg-yellow-100 border-l-4 border-yellow-500 text-yellow-700 p-4 rounded-md mb-4" role="alert">
                            <p><strong>提示:</strong>后台功能已禁用。</p>
                            <p>如需启用,请在环境变量中设置 <code class="font-mono bg-yellow-200 px-1 rounded">ADMIN_PASSWORD</code>。</p>
                        </div>
                    {% endif %}
                    {% if error %}
                        <div class="bg-red-100 border-l-4 border-red-500 text-red-700 p-4 rounded-md mb-4" role="alert">
                            <p>{{ error }}</p>
                        </div>
                    {% endif %}
                    <form method="post" action="{{ url_for('admin') }}">
                        <div class="mb-4">
                            <label for="password" class="block text-sm font-medium text-gray-700">密码</label>
                            <input type="password" name="password" id="password" required class="mt-1 block w-full px-3 py-2 bg-white border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 transition">
                        </div>
                        <button type="submit" {% if not admin_enabled %}disabled{% endif %} class="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 disabled:bg-gray-400 disabled:cursor-not-allowed transition-colors">登录</button>
                    </form>
                </div>
            </div>
        {% endif %}
    </div>
    <script>
        // 行内代码点击复制
        document.addEventListener('DOMContentLoaded', function () {
            const codes = document.querySelectorAll('.copy-code');
            codes.forEach(function (el) {
                el.addEventListener('click', function () {
                    const text = el.innerText.trim();
                    navigator.clipboard.writeText(text).then(function () {
                        const originalTitle = el.getAttribute('title') || '';
                        el.setAttribute('title', '已复制');
                        el.classList.add('bg-green-100');
                        setTimeout(function () {
                            el.classList.remove('bg-green-100');
                            el.setAttribute('title', originalTitle || '点击复制');
                        }, 1200);
                    }).catch(function (err) {
                        console.error('无法复制: ', err);
                    });
                });
            });
        });
    </script>
</body>
</html>
    """

    # [重构] 打印专用模板 (print_report.html)
    print_html = """
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>{{ report.desc.examName }} - {{ report.desc.studentname }} 的成绩报告</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        @media print {
            body { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
            .no-print { display: none; }
        }
        body { font-family: 'Inter', 'Noto Sans+SC', sans-serif; }
        .table-cell { padding: 0.5rem 0.75rem; text-align: center; border: 1px solid #e5e7eb; }
        .table-cell-head { font-weight: 600; background-color: #f9fafb; }
        .page-break { page-break-after: always; }
    </style>
</head>
<body class="bg-white text-gray-900">
    <div class="max-w-4xl mx-auto p-8">
        <div class="no-print mb-6 text-center">
            <button onclick="window.print()" class="px-6 py-2 bg-indigo-600 text-white font-semibold rounded-md shadow-sm hover:bg-indigo-700">打印</button>
            <a href="{{ url_for('show_report', item_id=history_item_id) }}" class="ml-4 px-6 py-2 bg-gray-200 text-gray-800 font-semibold rounded-md hover:bg-gray-300">返回</a>
        </div>

        {% if report and report.result == "1" %}
            {% set desc = report.desc or {} %}
            {% set stu_order = desc.stuOrder or {} %}
            {% set subjects = stu_order.subjects or [] %}
            {% set score_gap = stu_order.scoreGap or {} %}
            {% set total_score_info = (subjects | selectattr('name', 'equalto', '总分') | first) or {} %}

            <div class="space-y-8">
                <header class="text-center border-b-2 border-gray-200 pb-4">
                    <h1 class="text-3xl font-bold text-gray-800">{{ desc.examName or '考试报告' }}</h1>
                    <p class="text-xl text-gray-600 mt-2">{{ desc.studentname or '未知学生' }}</p>
                </header>

                <div>
                     <h2 class="text-xl font-bold mb-3 text-gray-700 border-b pb-2">总览</h2>
                     <div class="grid grid-cols-4 gap-4 text-center">
                         <div class="bg-gray-50 p-3 border border-gray-200 rounded"><p class="text-sm text-gray-600">总分</p><p class="text-2xl font-bold">{{ total_score_info.score or 'N/A' }}</p></div>
                         <div class="bg-gray-50 p-3 border border-gray-200 rounded"><p class="text-sm text-gray-600">班级排名</p><p class="text-2xl font-bold">{{ total_score_info.classOrder or 'N/A' }}</p></div>
                         <div class="bg-gray-50 p-3 border border-gray-200 rounded"><p class="text-sm text-gray-600">学校排名</p><p class="text-2xl font-bold>{{ total_score_info.schoolOrder or 'N/A' }}</p></div>
                         <div class="bg-gray-50 p-3 border border-gray-200 rounded"><p class="text-sm text-gray-600">统考排名</p><p class="text-2xl font-bold">{{ total_score_info.unionOrder or 'N/A' }}</p></div>
                     </div>
                </div>

                <div>
                    <h2 class="text-xl font-bold mb-3 text-gray-700 border-b pb-2">各科成绩详情</h2>
                    <table class="w-full border-collapse border border-gray-300">
                        <thead>
                            <tr>
                                <th class="table-cell table-cell-head">科目</th>
                                <th class="table-cell table-cell-head">得分/赋分 (原始分)</th>
                                <th class="table-cell table-cell-head">班级排名</th>
                                <th class="table-cell table-cell-head">学校排名</th>
                                <th class="table-cell table-cell-head">统考排名</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for subject in subjects %}
                                {% if subject.name != '总分' %}
                                <tr>
                                    <td class="table-cell font-semibold">{{ subject.name }}</td>
                                    <td class="table-cell">{% if subject.score != subject.paperScore %}{{ subject.score }} ({{ subject.paperScore }}){% else %}{{ subject.score }}{% endif %}</td>
                                    <td class="table-cell">{{ subject.classOrder or 'N/A' }}</td>
                                    <td class="table-cell">{{ subject.schoolOrder or 'N/A' }}</td>
                                    <td class="table-cell">{{ subject.unionOrder or 'N/A' }}</td>
                                </tr>
                                {% endif %}
                            {% endfor %}
                        </tbody>
                    </table>
                </div>

                <div>
                    <h2 class="text-xl font-bold mb-3 text-gray-700 border-b pb-2">统计数据</h2>
                    <table class="w-full border-collapse border border-gray-300">
                        <thead>
                            <tr>
                                <th class="table-cell table-cell-head">类别</th>
                                <th class="table-cell table-cell-head">平均分</th>
                                <th class="table-cell table-cell-head">最高分</th>
                                <th class="table-cell table-cell-head">总人数</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr><td class="table-cell font-semibold">班级</td><td class="table-cell">{{ score_gap.classAvg or 'N/A' }}</td><td class="table-cell">{{ score_gap.classTop or 'N/A' }}</td><td class="table-cell">{{ score_gap.classNum or 'N/A' }}</td></tr>
                            <tr><td class="table-cell font-semibold">学校</td><td class="table-cell">{{ score_gap.schoolAvg or 'N/A' }}</td><td class="table-cell">{{ score_gap.schoolTop or 'N/A' }}</td><td class="table-cell">{{ score_gap.schoolNum or 'N/A' }}</td></tr>
                            <tr><td class="table-cell font-semibold">统考</td><td class="table-cell">{{ score_gap.unionAvg or 'N/A' }}</td><td class="table-cell">{{ score_gap.unionTop or 'N/A' }}</td><td class="table-cell">{{ score_gap.unionNum or 'N/A' }}</td></tr>
                        </tbody>
                    </table>
                </div>
            </div>
        {% else %}
            <p class="text-center text-red-600">无法加载报告数据。</p>
        {% endif %}
    </div>
</body>
</html>
    """

    with open(os.path.join(TEMPLATE_DIR, 'index.html'), 'w', encoding='utf-8') as f:
        f.write(index_html)
    with open(os.path.join(TEMPLATE_DIR, 'subject_details.html'), 'w', encoding='utf-8') as f:
        f.write(subject_details_html)
    with open(os.path.join(TEMPLATE_DIR, 'admin.html'), 'w', encoding='utf-8') as f:
        f.write(admin_html)
    with open(os.path.join(TEMPLATE_DIR, 'print_report.html'), 'w', encoding='utf-8') as f:
        f.write(print_html)

create_templates()

if __name__ == '__main__':
    create_templates()
    try:
        save_history(load_history())
    except Exception as _:
        pass
    # Run the Flask application
    app.run(host='0.0.0.0', port=7860, debug=False)