-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
7226 lines (6354 loc) · 336 KB
/
app.js
File metadata and controls
7226 lines (6354 loc) · 336 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
// 代谢指纹数据定义
const metaboliteData = [
// 脂质代谢相关
{ id: 'LDL_C', name: 'LDL胆固醇', category: 'lipid', unit: 'mmol/L', refMin: 1.8, refMax: 3.4 },
{ id: 'HDL_C', name: 'HDL胆固醇', category: 'lipid', unit: 'mmol/L', refMin: 1.0, refMax: 1.6 },
{ id: 'TG', name: '甘油三酯', category: 'lipid', unit: 'mmol/L', refMin: 0.4, refMax: 1.7 },
{ id: 'TC', name: '总胆固醇', category: 'lipid', unit: 'mmol/L', refMin: 3.0, refMax: 5.2 },
{ id: 'ApoB', name: '载脂蛋白B', category: 'lipid', unit: 'g/L', refMin: 0.6, refMax: 1.1 },
// 糖代谢相关
{ id: 'Glucose', name: '葡萄糖', category: 'glucose', unit: 'mmol/L', refMin: 3.9, refMax: 6.1 },
{ id: 'HbA1c', name: '糖化血红蛋白', category: 'glucose', unit: '%', refMin: 4.0, refMax: 6.0 },
{ id: 'Insulin', name: '胰岛素', category: 'glucose', unit: 'mIU/L', refMin: 2.6, refMax: 24.9 },
{ id: 'HOMA_IR', name: '胰岛素抵抗指数', category: 'glucose', unit: '', refMin: 0, refMax: 2.5 },
// 氨基酸代谢
{ id: 'Leucine', name: '亮氨酸', category: 'amino', unit: 'μmol/L', refMin: 80, refMax: 180 },
{ id: 'Isoleucine', name: '异亮氨酸', category: 'amino', unit: 'μmol/L', refMin: 40, refMax: 100 },
{ id: 'Valine', name: '缬氨酸', category: 'amino', unit: 'μmol/L', refMin: 150, refMax: 300 },
{ id: 'BCAA', name: '支链氨基酸', category: 'amino', unit: 'μmol/L', refMin: 270, refMax: 580 },
{ id: 'Phenylalanine', name: '苯丙氨酸', category: 'amino', unit: 'μmol/L', refMin: 40, refMax: 80 },
{ id: 'Tyrosine', name: '酪氨酸', category: 'amino', unit: 'μmol/L', refMin: 40, refMax: 90 },
// 炎症标志物
{ id: 'CRP', name: 'C反应蛋白', category: 'inflammation', unit: 'mg/L', refMin: 0, refMax: 3 },
{ id: 'IL6', name: '白细胞介素-6', category: 'inflammation', unit: 'pg/mL', refMin: 0, refMax: 7 },
{ id: 'TNF_alpha', name: '肿瘤坏死因子-α', category: 'inflammation', unit: 'pg/mL', refMin: 0, refMax: 8 },
{ id: 'Homocysteine', name: '同型半胱氨酸', category: 'inflammation', unit: 'μmol/L', refMin: 5, refMax: 15 },
// 能量代谢
{ id: 'Lactate', name: '乳酸', category: 'energy', unit: 'mmol/L', refMin: 0.5, refMax: 2.2 },
{ id: 'Pyruvate', name: '丙酮酸', category: 'energy', unit: 'μmol/L', refMin: 30, refMax: 100 },
{ id: 'Ketone', name: '酮体', category: 'energy', unit: 'mmol/L', refMin: 0.02, refMax: 0.5 },
{ id: 'Acetylcarnitine', name: '乙酰肉碱', category: 'energy', unit: 'μmol/L', refMin: 5, refMax: 25 },
// 氧化应激
{ id: 'MDA', name: '丙二醛', category: 'oxidative', unit: 'nmol/mL', refMin: 0, refMax: 6 },
{ id: 'SOD', name: '超氧化物歧化酶', category: 'oxidative', unit: 'U/mL', refMin: 120, refMax: 220 },
{ id: 'GSH', name: '谷胱甘肽', category: 'oxidative', unit: 'μmol/L', refMin: 400, refMax: 800 }
];
// 代谢物类别名称映射
const categoryNames = {
lipid: '脂质代谢',
glucose: '糖代谢',
amino: '氨基酸代谢',
inflammation: '炎症标志物',
energy: '能量代谢',
oxidative: '氧化应激'
};
// 亚健康状态定义 - 包含疾病预警和分类建议
const subtypes = {
sedentary: {
name: '运动不足型',
description: '能量代谢相关指标异常,提示缺乏规律运动',
indicators: ['Lactate', 'Pyruvate', 'Ketone', 'Acetylcarnitine'],
diet: [
'增加优质蛋白质摄入:鸡肉、鱼肉、鸡蛋、豆腐、希腊酸奶',
'适量补充B族维生素:全麦面包、燕麦、菠菜、西兰花、香蕉',
'控制精制糖摄入:避免蛋糕、糖果、甜饮料',
'多吃富含铁的食物:瘦肉、动物肝脏、菠菜、红枣',
'食谱示例:早餐(燕麦粥+鸡蛋+蓝莓)、午餐(鸡胸肉沙拉)、晚餐(清蒸鱼+糙米+蔬菜)'
],
lifestyle: [
'作息时间:建议22:30前入睡,7:00起床,保证7-8小时睡眠',
'避免久坐:每小时起身活动5-10分钟,可进行伸展运动',
'规律作息:保持固定的睡眠和起床时间,包括周末',
'减少熬夜:避免23:00后使用电子设备,睡前1小时放松',
'压力管理:每天进行10-15分钟冥想或深呼吸练习',
'工作休息:每工作1小时休息5分钟,避免连续工作超过2小时'
],
exercise: [
'每周至少150分钟中等强度运动:快走、慢跑、游泳、骑自行车',
'力量训练:每周2-3次,每次20-30分钟,包括深蹲、俯卧撑、哑铃训练',
'日常活动:每天步行8000-10000步,每小时起身活动5-10分钟',
'运动强度:心率保持在最大心率的60-70%(最大心率=220-年龄)',
'运动计划:周一、三、五进行有氧运动30分钟,周二、四进行力量训练20分钟'
],
recommendations: [
'建议每周进行至少150分钟中等强度有氧运动',
'增加日常活动量,如步行、爬楼梯等',
'结合抗阻训练,每周2-3次',
'避免久坐,每小时起身活动5-10分钟',
'循序渐进,从低强度运动开始'
],
diseases: [
{ name: '代谢综合征', symptoms: '腹部肥胖、血压升高、血糖异常、血脂异常' },
{ name: '2型糖尿病', symptoms: '多饮、多尿、多食、体重下降、疲劳乏力' },
{ name: '心血管疾病', symptoms: '胸闷、心悸、气短、运动耐量下降' }
]
},
obese: {
name: '肥胖代谢紊乱型',
description: '脂质代谢异常,与体重管理相关',
indicators: ['LDL_C', 'TG', 'TC', 'ApoB', 'HDL_C'],
diet: [
'🚫 限制高脂肪食物:油炸食品、肥肉、奶油',
'🚫 避免高糖饮料:碳酸饮料、奶茶、果汁',
'增加蔬菜水果摄入:每天5份以上,如菠菜、西兰花、苹果、蓝莓',
'选择全谷物食品:燕麦、糙米、全麦面包',
'控制总热量摄入:每日减少300-500大卡',
'食谱示例:早餐(蔬菜蛋卷+全麦吐司)、午餐( grilled chicken salad)、晚餐(清蒸鱼+糙米饭+凉拌菜)'
],
lifestyle: [
'作息时间:建议22:00前入睡,6:30起床,保证7-8小时睡眠',
'避免熬夜:晚上10点后避免进食,避免使用电子设备',
'压力管理:每天进行15-20分钟冥想或瑜伽,避免情绪性进食',
'定期监测:每周固定时间测量体重和腰围,记录变化',
'睡眠质量:保持卧室安静、黑暗,温度控制在18-20℃',
'进餐规律:固定三餐时间,避免暴饮暴食和夜间进食'
],
exercise: [
'每周300分钟中等强度运动:快走、游泳、骑自行车、椭圆机',
'力量训练:每周3-4次,每次30分钟,包括深蹲、卧推、引体向上',
'日常活动:每天步行10000-12000步,减少久坐时间',
'运动强度:心率保持在最大心率的60-75%(最大心率=220-年龄)',
'运动计划:周一、三、五进行有氧运动45分钟,周二、四、六进行力量训练30分钟'
],
recommendations: [
'控制总热量摄入,创造适度热量缺口',
'减少饱和脂肪和反式脂肪摄入',
'增加膳食纤维摄入,多吃蔬菜水果',
'限制精制碳水化合物和含糖饮料',
'定期监测体重和腰围变化',
'必要时寻求专业营养师指导'
],
diseases: [
{ name: '动脉粥样硬化', symptoms: '头晕、胸闷、肢体麻木、记忆力下降' },
{ name: '冠心病', symptoms: '胸痛、胸闷、气短、心悸、出汗' },
{ name: '脂肪肝', symptoms: '右上腹不适、乏力、食欲减退' },
{ name: '高血压', symptoms: '头痛、头晕、耳鸣、心悸、视力模糊' }
]
},
inflammatory: {
name: '炎症饮食相关型',
description: '炎症标志物升高,可能与饮食结构有关',
indicators: ['CRP', 'IL6', 'TNF_alpha', 'Homocysteine'],
diet: [
'🚫 避免加工食品:薯片、快餐、腌制食品',
'🚫 减少红肉摄入:每周不超过500g',
'增加Omega-3脂肪酸:三文鱼、鳕鱼、亚麻籽、核桃',
'多吃抗氧化食物:蓝莓、草莓、菠菜、西兰花、绿茶',
'采用地中海饮食:橄榄油、坚果、全谷物、新鲜蔬果',
'食谱示例:早餐(希腊酸奶+蓝莓+亚麻籽)、午餐(地中海沙拉)、晚餐(烤三文鱼+糙米+蔬菜)'
],
lifestyle: [
'作息时间:建议22:30前入睡,7:00起床,保证7-8小时睡眠',
'戒烟限酒:完全戒烟,限制酒精摄入(男性每日不超过25g,女性不超过15g)',
'压力管理:每天进行20分钟冥想或深呼吸练习,每周进行1-2次瑜伽',
'环境优化:避免暴露在污染环境中,保持室内空气流通',
'睡眠质量:睡前避免咖啡因和电子设备,创造良好的睡眠环境',
'情绪管理:培养兴趣爱好,与朋友家人保持良好沟通'
],
exercise: [
'适度有氧运动:每周150-200分钟,如快走、游泳、瑜伽',
'压力缓解运动:每周2-3次瑜伽或太极,每次30分钟',
'运动强度:心率保持在最大心率的50-65%(最大心率=220-年龄)',
'避免过度运动:避免高强度训练,注重恢复',
'运动计划:周一、三、五进行有氧运动30分钟,周二、四进行瑜伽或太极30分钟'
],
recommendations: [
'采用地中海饮食模式',
'增加Omega-3脂肪酸摄入(深海鱼、坚果)',
'多吃富含抗氧化物质的食物',
'减少加工食品和高糖食品摄入',
'戒烟限酒',
'保证充足睡眠,管理压力'
],
diseases: [
{ name: '动脉粥样硬化', symptoms: '血管炎症、斑块形成、血流受阻' },
{ name: '自身免疫性疾病', symptoms: '关节肿痛、皮疹、疲劳、发热' },
{ name: '心血管疾病', symptoms: '胸痛、气短、心悸、水肿' }
]
},
glucose: {
name: '糖代谢异常型',
description: '葡萄糖相关代谢物异常,提示糖代谢问题',
indicators: ['Glucose', 'HbA1c', 'Insulin', 'HOMA_IR'],
diet: [
'🚫 限制精制碳水化合物:白面包、白米饭、糕点',
'🚫 避免含糖饮料:汽水、果汁、奶茶',
'选择低升糖指数食物:燕麦、豆类、非淀粉类蔬菜',
'增加膳食纤维:蔬菜、水果、全谷物',
'控制餐后血糖:少量多餐,避免暴饮暴食',
'食谱示例:早餐(燕麦粥+鸡蛋)、午餐(鸡肉+蔬菜+糙米)、晚餐(豆腐+蔬菜+全麦意面)'
],
lifestyle: [
'进餐时间:固定三餐时间,早餐7:30-8:30,午餐11:30-12:30,晚餐18:00-19:00',
'避免暴饮暴食:控制每餐食量,采用小碗盛装,细嚼慢咽',
'体重管理:每周监测体重,目标是将BMI控制在18.5-24之间',
'血糖监测:每周测量2-3次空腹血糖,每3个月测量一次糖化血红蛋白',
'作息规律:建议22:30前入睡,7:00起床,保证7-8小时睡眠',
'压力管理:每天进行15分钟冥想,避免长期处于高压状态'
],
exercise: [
'餐后30分钟运动:散步、轻度有氧运动,帮助控制血糖',
'有氧运动:每周150-200分钟,如快走、游泳、骑自行车',
'抗阻训练:每周2-3次,每次20-30分钟,增强肌肉代谢',
'运动强度:心率保持在最大心率的50-70%(最大心率=220-年龄)',
'运动计划:早餐后散步10分钟,午餐后散步15分钟,晚餐后散步15分钟,每周3次力量训练'
],
recommendations: [
'控制碳水化合物摄入总量',
'选择低升糖指数食物',
'增加膳食纤维摄入',
'规律进餐,避免暴饮暴食',
'餐后适度活动有助于血糖控制',
'定期监测空腹和餐后血糖'
],
diseases: [
{ name: '2型糖尿病', symptoms: '多饮多尿、体重下降、视力模糊、伤口愈合慢' },
{ name: '糖尿病并发症', symptoms: '手脚麻木、视力下降、蛋白尿、皮肤瘙痒' },
{ name: '代谢综合征', symptoms: '腹型肥胖、高血压、高血糖、高血脂' }
]
},
amino: {
name: '氨基酸代谢紊乱型',
description: '支链氨基酸等异常,与蛋白质代谢相关',
indicators: ['Leucine', 'Isoleucine', 'Valine', 'BCAA', 'Phenylalanine', 'Tyrosine'],
diet: [
'优化蛋白质来源:鱼肉、鸡肉、鸡蛋、豆腐、乳制品',
'适量摄入优质蛋白:每公斤体重0.8-1.0g',
'🚫 避免过量红肉:每周不超过300g',
'增加植物蛋白:豆类、坚果、藜麦',
'补充维生素B6:香蕉、土豆、鸡肉、鱼类',
'食谱示例:早餐(希腊酸奶+坚果)、午餐(烤鸡+蔬菜)、晚餐(豆腐汤+糙米)'
],
lifestyle: [
'作息时间:建议22:30前入睡,7:00起床,保证7-8小时睡眠',
'避免过度劳累:工作时间控制在8小时以内,避免熬夜和高强度工作',
'情绪管理:保持情绪稳定,避免长期处于紧张状态',
'定期体检:每6个月进行一次肝肾功能检查,监测氨基酸代谢指标',
'休息充足:保证每天有足够的休息时间,避免连续工作超过5天',
'水分摄入:每天饮水量保持在1500-2000ml,促进代谢废物排出'
],
exercise: [
'适度运动:每周150-180分钟,如快走、游泳、瑜伽',
'力量训练:每周2-3次,每次20-25分钟,避免过度训练',
'运动恢复:保证充足休息,运动后拉伸和放松',
'补充水分:运动前后充分补水,保持身体水分平衡',
'运动计划:周一、三、五进行轻度有氧运动30分钟,周二、四进行轻度力量训练20分钟'
],
recommendations: [
'优化蛋白质摄入结构,选择优质蛋白',
'适量摄入乳制品、鱼类、豆类',
'避免过量摄入红肉',
'保持均衡饮食,避免单一食物过量',
'关注肝肾功能健康',
'必要时进行蛋白质代谢相关检查'
],
diseases: [
{ name: '肝脏疾病', symptoms: '乏力、食欲减退、腹胀、黄疸' },
{ name: '肾脏疾病', symptoms: '水肿、尿量改变、腰痛、高血压' },
{ name: '代谢性疾病', symptoms: '发育迟缓、智力障碍、特殊体味' }
]
}
};
// 用户数据存储
let users = {};
// 尝试从localStorage加载用户数据
const storedUsers = localStorage.getItem('metascanUsers');
if (storedUsers) {
try {
users = JSON.parse(storedUsers);
} catch (e) {
console.error('Failed to parse users data:', e);
users = {};
}
}
// 当前用户
let currentUser = null;
const storedCurrentUser = localStorage.getItem('metascanCurrentUser');
if (storedCurrentUser) {
try {
currentUser = JSON.parse(storedCurrentUser);
} catch (e) {
console.error('Failed to parse current user data:', e);
currentUser = null;
}
}
// 历史数据存储 - 按用户存储
let historicalData = {};
// 当前检测结果
let currentResult = null;
// 清空系统所有账号数据
function clearAllData() {
// 清除所有相关的localStorage数据
localStorage.removeItem('metascanUsers');
localStorage.removeItem('metascanCurrentUser');
// 清除所有用户的检测数据
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
if (key.startsWith('metascanData_') || key.startsWith('metascanPrescriptions_') || key.startsWith('metascanSharedPrescriptions_') || key.startsWith('metascanReferrals_') || key.startsWith('metascanNotifications_')) {
localStorage.removeItem(key);
}
}
// 重置内存中的数据
users = {};
currentUser = null;
historicalData = {};
// 显示成功消息
showNotification('系统数据已清空');
}
// 初始化页面
document.addEventListener('DOMContentLoaded', function() {
// 清空系统数据(仅执行一次)
clearAllData();
// 检查用户登录状态
checkLoginStatus();
initializeInputForm();
initializeMetaboliteCategories();
// 设置活动跟踪
setupActivityTracking();
// 启动通知检查
startNotificationCheck();
// 初始化通知徽章
updateNotificationBadge();
// 添加全局点击事件监听器,点击页面其他位置关闭通知
document.addEventListener('click', function(event) {
const notificationPanel = document.getElementById('notificationPanel');
const notificationButton = document.querySelector('.nav-tab[onclick="toggleNotifications()"]');
// 检查点击的目标是否在通知面板内或者是通知按钮本身
if (notificationPanel && notificationPanel.style.display === 'block') {
const isClickInsidePanel = notificationPanel.contains(event.target);
const isClickOnButton = notificationButton && notificationButton.contains(event.target);
if (!isClickInsidePanel && !isClickOnButton) {
notificationPanel.style.display = 'none';
}
}
});
});
// 检查登录状态
function checkLoginStatus() {
if (currentUser) {
// 用户已登录,隐藏登录页面
document.getElementById('loginPage').style.display = 'none';
// 加载用户数据
loadUserData();
// 如果是医生,显示医生仪表盘
if (currentUser.role === 'doctor') {
showDoctorDashboard();
}
} else {
// 用户未登录,显示登录页面
document.getElementById('loginPage').style.display = 'flex';
}
}
// 切换表单
function toggleForm(formType) {
try {
// 隐藏所有表单
const loginForm = document.getElementById('loginForm');
const registerForm = document.getElementById('registerForm');
const forgotForm = document.getElementById('forgotForm');
if (loginForm) loginForm.style.display = 'none';
if (registerForm) registerForm.style.display = 'none';
if (forgotForm) forgotForm.style.display = 'none';
// 显示选中的表单
if (formType === 'login' && loginForm) {
loginForm.style.display = 'flex';
} else if (formType === 'register' && registerForm) {
registerForm.style.display = 'flex';
} else if (formType === 'forgot' && forgotForm) {
forgotForm.style.display = 'flex';
}
// 清除错误信息
const loginError = document.getElementById('loginError');
if (loginError) loginError.style.display = 'none';
} catch (e) {
console.error('Error in toggleForm:', e);
}
}
// 重置密码功能
function resetPassword() {
const username = document.getElementById('forgotUsername').value.trim();
const newPassword = document.getElementById('newPassword').value;
const confirmNewPassword = document.getElementById('confirmNewPassword').value;
const role = document.querySelector('input[name="forgotRole"]:checked').value;
if (!username || !newPassword || !confirmNewPassword) {
showError('请填写所有字段');
return;
}
if (newPassword !== confirmNewPassword) {
showError('两次输入的新密码不一致');
return;
}
// 检查用户是否存在
if (!users[username]) {
showError('用户名不存在');
return;
}
// 验证角色
if (users[username].role !== role) {
showError('角色选择错误');
return;
}
// 更新密码
users[username].password = hashPassword(newPassword);
localStorage.setItem('metascanUsers', JSON.stringify(users));
// 显示成功消息
showNotification('密码重置成功!');
// 切换回登录表单
toggleForm('login');
// 填充用户名
document.getElementById('username').value = username;
}
// 登录功能
function login() {
const username = document.getElementById('username').value.trim();
const password = document.getElementById('password').value;
const role = document.querySelector('input[name="role"]:checked').value;
if (!username || !password) {
showError('请输入用户名和密码');
return;
}
// 检查用户是否存在
if (!users[username]) {
showError('用户名或密码错误');
return;
}
// 验证密码(使用加密后的密码)
if (users[username].password !== hashPassword(password)) {
showError('用户名或密码错误');
return;
}
// 验证角色
if (users[username].role !== role) {
showError('角色选择错误');
return;
}
// 登录成功
currentUser = {
username: username,
role: role,
lastActivity: new Date().toISOString()
};
localStorage.setItem('metascanCurrentUser', JSON.stringify(currentUser));
// 如果是医生登录,记录登录时间
if (role === 'doctor') {
sessionStorage.setItem('doctorLoginTime', Date.now().toString());
}
// 隐藏登录页面,显示主应用页面
document.getElementById('loginPage').style.display = 'none';
document.querySelector('.container').style.display = 'block';
// 根据角色显示不同的导航栏
if (role === 'doctor') {
// 显示医生导航栏,隐藏患者导航栏
document.querySelector('.nav-tabs:not(.doctor-nav)').style.display = 'none';
document.querySelector('.doctor-nav').style.display = 'flex';
// 显示医生仪表盘
showDoctorDashboard();
} else {
// 显示患者导航栏,隐藏医生导航栏
document.querySelector('.nav-tabs:not(.doctor-nav)').style.display = 'flex';
document.querySelector('.doctor-nav').style.display = 'none';
// 显示数据录入页面
showTab('input');
}
// 加载用户数据
loadUserData();
// 显示成功消息
showNotification('登录成功!');
// 启动会话超时检查
startSessionTimeout();
}
// 会话超时检查
function startSessionTimeout() {
// 每5分钟检查一次会话状态
setInterval(() => {
if (currentUser) {
const lastActivity = new Date(currentUser.lastActivity);
const now = new Date();
const timeDiff = now - lastActivity;
const minutesDiff = timeDiff / (1000 * 60);
// 如果超过30分钟没有活动,自动退出登录
if (minutesDiff > 30) {
logout();
showNotification('会话已超时,请重新登录');
}
}
}, 5 * 60 * 1000);
}
// 更新活动时间
function updateActivity() {
if (currentUser) {
currentUser.lastActivity = new Date().toISOString();
localStorage.setItem('metascanCurrentUser', JSON.stringify(currentUser));
}
}
// 为所有用户交互添加活动时间更新
function setupActivityTracking() {
// 鼠标移动
document.addEventListener('mousemove', updateActivity);
// 键盘输入
document.addEventListener('keypress', updateActivity);
// 点击
document.addEventListener('click', updateActivity);
// 滚动
window.addEventListener('scroll', updateActivity);
}
// 简单的密码加密函数
function hashPassword(password) {
// 使用简单的哈希算法,实际生产环境应使用更安全的加密方法
let hash = 0;
for (let i = 0; i < password.length; i++) {
const char = password.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash = hash & hash;
}
return hash.toString();
}
// 注册功能
function register() {
const username = document.getElementById('regUsername').value.trim();
const password = document.getElementById('regPassword').value;
const confirmPassword = document.getElementById('regConfirmPassword').value;
const role = document.querySelector('input[name="regRole"]:checked').value;
if (!username || !password || !confirmPassword) {
showError('请填写所有字段');
return;
}
if (password !== confirmPassword) {
showError('两次输入的密码不一致');
return;
}
if (password.length < 6) {
showError('密码长度至少需要6位');
return;
}
if (users[username]) {
showError('用户名已存在');
return;
}
// 创建新用户,密码加密存储
users[username] = {
password: hashPassword(password),
role: role,
createdAt: new Date().toISOString()
};
// 保存用户数据
localStorage.setItem('metascanUsers', JSON.stringify(users));
// 自动登录
currentUser = { username: username, role: role, lastActivity: new Date().toISOString() };
localStorage.setItem('metascanCurrentUser', JSON.stringify(currentUser));
// 初始化用户数据
if (role === 'patient') {
historicalData[username] = [];
localStorage.setItem(`metascanData_${username}`, JSON.stringify([]));
}
// 隐藏登录页面,显示主应用页面
document.getElementById('loginPage').style.display = 'none';
document.querySelector('.container').style.display = 'block';
// 根据角色显示不同的导航栏
if (role === 'doctor') {
// 显示医生导航栏,隐藏患者导航栏
document.querySelector('.nav-tabs:not(.doctor-nav)').style.display = 'none';
document.querySelector('.doctor-nav').style.display = 'flex';
// 显示医生仪表盘
showDoctorDashboard();
} else {
// 显示患者导航栏,隐藏医生导航栏
document.querySelector('.nav-tabs:not(.doctor-nav)').style.display = 'flex';
document.querySelector('.doctor-nav').style.display = 'none';
// 显示数据录入页面
showTab('input');
}
// 显示成功消息
showNotification('注册成功!');
// 启动会话超时检查
startSessionTimeout();
}
// 加载用户数据
function loadUserData() {
if (currentUser) {
historicalData[currentUser.username] = JSON.parse(localStorage.getItem(`metascanData_${currentUser.username}`)) || [];
}
}
// 显示错误信息
function showError(message) {
const errorElement = document.getElementById('loginError');
errorElement.textContent = message;
errorElement.style.display = 'block';
}
// 切换下拉菜单
function toggleDropdown(event) {
event.stopPropagation();
const dropdowns = document.getElementsByClassName('dropdown-content');
for (let i = 0; i < dropdowns.length; i++) {
const dropdown = dropdowns[i];
// 检查下拉菜单是否与点击的按钮相关联
const btn = dropdown.previousElementSibling;
if (btn && btn.classList.contains('dropdown-btn')) {
dropdown.classList.toggle('show');
}
}
}
// 点击页面其他地方关闭下拉菜单
window.onclick = function(event) {
// 关闭下拉菜单
if (!event.target.matches('.dropdown-btn') && !event.target.closest('.dropdown-btn')) {
const dropdowns = document.getElementsByClassName('dropdown-content');
for (let i = 0; i < dropdowns.length; i++) {
const openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
// 关闭通知面板
const notificationPanel = document.getElementById('notificationPanel');
if (notificationPanel && notificationPanel.style.display === 'block') {
if (!event.target.closest('#notificationPanel') && !event.target.closest('[onclick*="toggleNotifications"]')) {
notificationPanel.style.display = 'none';
}
}
};
// 退出登录
function logout() {
currentUser = null;
localStorage.removeItem('metascanCurrentUser');
// 保存用户数据,确保数据不会丢失
localStorage.setItem('metascanUsers', JSON.stringify(users));
// 显示登录页面,隐藏主应用页面
document.getElementById('loginPage').style.display = 'flex';
document.querySelector('.container').style.display = 'none';
showNotification('已退出登录');
}
// 显示医生仪表盘
function showDoctorDashboard() {
// 隐藏所有标签页
document.querySelectorAll('.tab-content').forEach(tab => {
tab.style.display = 'none';
});
// 显示医生仪表盘
document.getElementById('doctorDashboard').style.display = 'block';
// 加载患者列表
loadPatientList();
// 更新数据概览
updateDashboardOverview();
// 绘制统计图表
setTimeout(() => {
drawRiskDistributionChart();
drawSubtypeDistributionChart();
}, 100);
}
// 更新仪表盘数据概览
function updateDashboardOverview() {
// 更新欢迎卡片的日期
const currentDateEl = document.getElementById('currentDate');
if (currentDateEl) {
const now = new Date();
currentDateEl.textContent = now.toLocaleDateString('zh-CN', {
year: 'numeric',
month: 'long',
day: 'numeric',
weekday: 'long'
});
}
// 更新在线时长(模拟)
const onlineTimeEl = document.getElementById('onlineTime');
if (onlineTimeEl) {
const loginTime = sessionStorage.getItem('doctorLoginTime') || Date.now();
const elapsed = Date.now() - parseInt(loginTime);
const hours = Math.floor(elapsed / (1000 * 60 * 60));
const minutes = Math.floor((elapsed % (1000 * 60 * 60)) / (1000 * 60));
onlineTimeEl.textContent = hours > 0 ? `${hours}小时${minutes}分钟` : `${minutes}分钟`;
}
// 获取所有患者用户
const patients = [];
for (const [username, userData] of Object.entries(users)) {
if (userData.role === 'patient') {
patients.push({ username, ...userData });
}
}
// 计算统计数据
let totalPatients = patients.length;
let highRiskPatients = 0;
let totalTests = 0;
let totalPrescriptions = 0;
let pendingPatients = 0;
let todayPatients = 0;
// 待处理事项列表
const pendingItems = [];
// 获取今天的日期(仅日期部分)
const today = new Date();
today.setHours(0, 0, 0, 0);
patients.forEach(patient => {
// 获取患者数据
const patientData = JSON.parse(localStorage.getItem(`metascanData_${patient.username}`)) || [];
totalTests += patientData.length;
// 检查是否有高风险记录
if (patientData.length > 0) {
const latestRecord = patientData[patientData.length - 1];
if (latestRecord.overallRisk > 60) {
highRiskPatients++;
}
// 检查是否有未处理的检测(没有对应的医嘱)
const prescriptions = JSON.parse(localStorage.getItem(`metascanPrescriptions_${patient.username}`)) || [];
if (prescriptions.length < patientData.length) {
pendingPatients++;
pendingItems.push({
type: 'diagnosis',
patient: patient.username,
date: latestRecord.date,
risk: latestRecord.overallRisk
});
}
// 检查是否有今日的检测
const recordDate = new Date(latestRecord.timestamp);
recordDate.setHours(0, 0, 0, 0);
if (recordDate.getTime() === today.getTime()) {
todayPatients++;
}
}
// 检查是否有新消息
const chatMessages = JSON.parse(localStorage.getItem(`metascanChat_${patient.username}`)) || [];
const hasNewMessage = chatMessages.some(msg => {
const msgDate = new Date(msg.timestamp);
return msgDate >= today && msg.sender === patient.username;
});
if (hasNewMessage) {
pendingItems.push({
type: 'message',
patient: patient.username,
date: new Date().toLocaleDateString('zh-CN')
});
}
// 获取医嘱数量
const prescriptions = JSON.parse(localStorage.getItem(`metascanPrescriptions_${patient.username}`)) || [];
totalPrescriptions += prescriptions.length;
});
// 更新DOM
const totalPatientsEl = document.getElementById('totalPatients');
if (totalPatientsEl) totalPatientsEl.textContent = totalPatients;
const highRiskPatientsEl = document.getElementById('highRiskPatients');
if (highRiskPatientsEl) highRiskPatientsEl.textContent = highRiskPatients;
const totalTestsEl = document.getElementById('totalTests');
if (totalTestsEl) totalTestsEl.textContent = totalTests;
const totalPrescriptionsEl = document.getElementById('totalPrescriptions');
if (totalPrescriptionsEl) totalPrescriptionsEl.textContent = totalPrescriptions;
const pendingPatientsEl = document.getElementById('pendingPatients');
if (pendingPatientsEl) pendingPatientsEl.textContent = pendingPatients;
const todayPatientsEl = document.getElementById('todayPatients');
if (todayPatientsEl) todayPatientsEl.textContent = todayPatients;
// 更新待处理事项
updatePendingList(pendingItems);
// 更新最近活动
updateRecentActivity();
// 绘制趋势图表
setTimeout(() => {
drawOverallTrendChart();
drawTestTrendChart();
}, 100);
}
// 更新待处理事项列表
function updatePendingList(items) {
const pendingList = document.getElementById('pendingList');
const pendingCount = document.getElementById('pendingCount');
if (!pendingList || !pendingCount) return;
pendingCount.textContent = items.length;
if (items.length === 0) {
pendingList.innerHTML = `
<div style="text-align: center; color: #666; padding: 40px 20px;">
<div style="font-size: 2.5rem; margin-bottom: 15px;">🎉</div>
<div style="font-size: 1rem;">暂无待处理事项</div>
<div style="font-size: 0.85rem; color: #999; margin-top: 5px;">继续保持!</div>
</div>
`;
return;
}
pendingList.innerHTML = items.map((item, index) => {
const icon = item.type === 'diagnosis' ? '📊' : '💬';
const title = item.type === 'diagnosis' ? '待诊断' : '新消息';
const bgColor = item.type === 'diagnosis' ? '#fff3e0' : '#e3f2fd';
const borderColor = item.type === 'diagnosis' ? '#ffe0b2' : '#bbdefb';
return `
<div style="background: ${bgColor}; border: 2px solid ${borderColor}; border-radius: 12px; padding: 15px; margin-bottom: 10px; animation: fadeInUp 0.4s ease; animation-delay: ${index * 0.05}s;">
<div style="display: flex; align-items: center; gap: 12px;">
<div style="width: 40px; height: 40px; background: white; border-radius: 10px; display: flex; align-items: center; justify-content: center; font-size: 1.2rem; flex-shrink: 0;">
${icon}
</div>
<div style="flex: 1; min-width: 0;">
<div style="font-weight: 700; color: #1a2980; margin-bottom: 3px;">${title}</div>
<div style="font-size: 0.9rem; color: #333; margin-bottom: 3px;">患者: ${item.patient}</div>
<div style="font-size: 0.8rem; color: #666;">📅 ${item.date}</div>
</div>
<button onclick="handlePendingItem('${item.type}', '${item.patient}')" style="padding: 8px 15px; background: linear-gradient(135deg, #1a2980 0%, #26d0ce 100%); color: white; border: none; border-radius: 20px; cursor: pointer; font-size: 0.85rem; font-weight: 600; flex-shrink: 0;">
处理
</button>
</div>
</div>
`;
}).join('');
}
// 处理待处理事项
function handlePendingItem(type, patientUsername) {
if (type === 'diagnosis' || type === 'message') {
showTab('doctorPatients');
setTimeout(() => {
showPatientDetails(patientUsername);
}, 100);
}
}
// 更新最近活动
function updateRecentActivity() {
const recentActivity = document.getElementById('recentActivity');
if (!recentActivity) return;
// 从localStorage获取活动记录
let activities = JSON.parse(localStorage.getItem('metascanDoctorActivities')) || [];
if (activities.length === 0) {
recentActivity.innerHTML = `
<div style="text-align: center; color: #666; padding: 40px 20px;">
<div style="font-size: 2.5rem; margin-bottom: 15px;">📝</div>
<div style="font-size: 1rem;">暂无活动记录</div>
<div style="font-size: 0.85rem; color: #999; margin-top: 5px;">活动将显示在这里</div>
</div>
`;
return;
}
// 只显示最近10条
activities = activities.slice(0, 10);
recentActivity.innerHTML = activities.map((activity, index) => {
const time = new Date(activity.timestamp);
const timeStr = time.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
let icon = '📋';
let bgColor = '#f8f9ff';
let borderColor = '#e0e6ed';
if (activity.type === 'diagnosis') {
icon = '📊';
bgColor = '#fff3e0';
borderColor = '#ffe0b2';
} else if (activity.type === 'prescription') {
icon = '📋';
bgColor = '#e8f5e9';
borderColor = '#c8e6c9';
} else if (activity.type === 'message') {
icon = '💬';
bgColor = '#e3f2fd';
borderColor = '#bbdefb';
}
return `
<div style="background: ${bgColor}; border-left: 4px solid ${borderColor}; border-radius: 8px; padding: 12px; margin-bottom: 8px; animation: fadeInUp 0.4s ease; animation-delay: ${index * 0.03}s;">
<div style="display: flex; align-items: center; gap: 10px;">
<div style="font-size: 1.2rem;">${icon}</div>
<div style="flex: 1; min-width: 0;">
<div style="font-weight: 600; color: #1a2980; font-size: 0.9rem;">${activity.title}</div>
<div style="font-size: 0.8rem; color: #666; margin-top: 3px;">${activity.message}</div>
</div>
<div style="font-size: 0.75rem; color: #999; flex-shrink: 0;">${timeStr}</div>
</div>
</div>
`;
}).join('');
}
// 添加医生活动记录
function addDoctorActivity(type, title, message) {
let activities = JSON.parse(localStorage.getItem('metascanDoctorActivities')) || [];
activities.unshift({
type: type,
title: title,
message: message,
timestamp: new Date().toISOString()
});
// 只保留最近50条
activities = activities.slice(0, 50);
localStorage.setItem('metascanDoctorActivities', JSON.stringify(activities));
}
// 绘制总体风险趋势图表
function drawOverallTrendChart() {
const ctx = document.getElementById('overallTrendChart');
if (!ctx) return;
// 生成最近7天的模拟数据
const labels = [];
const lowRiskData = [];
const mediumRiskData = [];
const highRiskData = [];
for (let i = 6; i >= 0; i--) {
const date = new Date();
date.setDate(date.getDate() - i);
labels.push(date.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' }));
// 模拟数据
lowRiskData.push(Math.floor(Math.random() * 20) + 10);
mediumRiskData.push(Math.floor(Math.random() * 15) + 5);
highRiskData.push(Math.floor(Math.random() * 10) + 2);
}
new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets: [
{
label: '低风险',
data: lowRiskData,
borderColor: '#27ae60',