-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhomepage.html
More file actions
995 lines (918 loc) · 45.2 KB
/
homepage.html
File metadata and controls
995 lines (918 loc) · 45.2 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
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="requires-auth" content="true">
<meta name="allowed-roles" content="super_admin,admin,operator">
<meta name="redirect-to" content="login.html">
<title>首页</title>
<!-- 引入 Tailwind CSS -->
<script src="https://cdn.tailwindcss.com"></script>
<!-- 引入 React 和 ReactDOM -->
<script src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
<!-- 引入 Babel 用于在浏览器中编译 JSX -->
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<!-- 引入 Supabase 客户端 -->
<script src="https://cdn.jsdelivr.net/npm/@supabase/supabase-js@2"></script>
<!-- 引入权限检查 -->
<script src="js/auth_checker.js"></script>
<!-- 配置文件 -->
<script src="js/config.js"></script>
<!-- 配置加载器 -->
<script src="js/config-loader.js"></script>
<!-- 引入 Supabase API 封装 -->
<script src="js/supabase_api.js"></script>
<style>
/* 自定义滚动条样式 */
.custom-scrollbar::-webkit-scrollbar {
width: 6px;
height: 6px;
}
.custom-scrollbar::-webkit-scrollbar-track {
background: transparent;
}
.custom-scrollbar::-webkit-scrollbar-thumb {
background-color: #d1d5db;
border-radius: 10px;
}
.custom-scrollbar:hover::-webkit-scrollbar-thumb {
background-color: #9ca3af;
}
/* 骨架屏加载动画 */
.skeleton {
background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
background-size: 200% 100%;
animation: shimmer 1.5s infinite;
}
@keyframes shimmer {
0% {
background-position: 200% 0;
}
100% {
background-position: -200% 0;
}
}
</style>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
const { useState, useEffect } = React;
// --- 图标渲染器 (替代 lucide-react) ---
const Icon = ({ name, className }) => {
const icons = {
Home: <React.Fragment><path d="m3 9 9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path><polyline points="9 22 9 12 15 12 15 22"></polyline></React.Fragment>,
List: <React.Fragment><line x1="8" x2="21" y1="6" y2="6"></line><line x1="8" x2="21" y1="12" y2="12"></line><line x1="8" x2="21" y1="18" y2="18"></line><line x1="3" x2="3.01" y1="6" y2="6"></line><line x1="3" x2="3.01" y1="12" y2="12"></line><line x1="3" x2="3.01" y1="18" y2="18"></line></React.Fragment>,
ChevronDown: <polyline points="6 9 12 15 18 9"></polyline>,
LogOut: <React.Fragment><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"></path><polyline points="16 17 21 12 16 7"></polyline><line x1="21" x2="9" y1="12" y2="12"></line></React.Fragment>,
User: <React.Fragment><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path><circle cx="12" cy="7" r="4"></circle></React.Fragment>,
Calendar: <React.Fragment><rect width="18" height="18" x="3" y="4" rx="2" ry="2"></rect><line x1="16" x2="16" y1="2" y2="6"></line><line x1="8" x2="8" y1="2" y2="6"></line><line x1="3" x2="21" y1="10" y2="10"></line></React.Fragment>,
Clock: <React.Fragment><circle cx="12" cy="12" r="10"></circle><polyline points="12 6 12 12 16 14"></polyline></React.Fragment>,
Users: <React.Fragment><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path><circle cx="9" cy="7" r="4"></circle><path d="M23 21v-2a4 4 0 0 0-3-3.87"></path><path d="M16 3.13a4 4 0 0 1 0 7.75"></path></React.Fragment>,
Target: <React.Fragment><circle cx="12" cy="12" r="10"></circle><circle cx="12" cy="12" r="6"></circle><circle cx="12" cy="12" r="2"></circle></React.Fragment>,
Eye: <React.Fragment><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path><circle cx="12" cy="12" r="3"></circle></React.Fragment>,
EyeOff: <React.Fragment><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"></path><line x1="1" x2="23" y1="1" y2="23"></line></React.Fragment>,
CheckCircle: <React.Fragment><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path><polyline points="22 4 12 14.01 9 11.01"></polyline></React.Fragment>,
XCircle: <React.Fragment><circle cx="12" cy="12" r="10"></circle><line x1="15" x2="9" y1="9" y2="15"></line><line x1="9" x2="15" y1="9" y2="15"></line></React.Fragment>,
Plus: <React.Fragment><line x1="12" x2="12" y1="5" y2="19"></line><line x1="5" x2="19" y1="12" y2="12"></line></React.Fragment>,
Edit: <React.Fragment><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"></path></React.Fragment>,
ArrowRight: <polyline points="9 18 15 12 9 6"></polyline>,
X: <React.Fragment><line x1="18" x2="6" y1="6" y2="18"></line><line x1="6" x2="18" y1="6" y2="18"></line></React.Fragment>,
AlertCircle: <React.Fragment><circle cx="12" cy="12" r="10"></circle><line x1="12" x2="12" y1="8" y2="12"></line><line x1="12" x2="12" y1="16" y2="16"></line></React.Fragment>,
Lock: <React.Fragment><rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect><path d="M7 11V7a5 5 0 0 1 10 0v4"></path></React.Fragment>
};
return (
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className={className}>
{icons[name] || <circle cx="12" cy="12" r="10" />}
</svg>
);
};
// 角色名称映射
const roleMap = {
1: '超管',
2: '管理员',
3: '用户'
};
// 角色颜色映射
const roleColorMap = {
1: 'bg-red-100 text-red-800',
2: 'bg-orange-100 text-orange-800',
3: 'bg-blue-100 text-blue-800'
};
// Supabase客户端已在supabase_api.js中初始化,直接使用H5CmsAPI
// API调用函数
const api = {
// 获取统计数据
async getDashboardStats() {
if (!window.H5CmsAPI) throw new Error('API未加载,请刷新页面重试');
const result = await H5CmsAPI.ActivityAPI.getList({
page_size: 1000,
get_all: true
});
if (result.error) throw result.error;
let activities = result.data.list || [];
// 获取当前登录用户信息,用于权限过滤
const currentUser = window.LoginManager?.getUserInfo();
const userRoleId = currentUser?.roleId;
console.log('首页 - 用户角色ID(数字):', userRoleId);
// 根据用户角色过滤活动列表
// 1级(超级管理员)、2级(管理员)可以查看全部活动
// 3级(运营人员)只能查看自己创建的活动
if (userRoleId === 3) {
console.log('首页 - 3级用户,只显示自己创建的活动');
activities = activities.filter(item =>
item.creator_id === currentUser.id
);
console.log('首页 - 过滤前数量:', (result.data.list || []).length);
console.log('首页 - 过滤后数量:', activities.length);
} else {
console.log('首页 - 1级或2级用户,显示全部活动');
}
const totalActivities = activities.length;
const activeActivities = activities.filter(a => a.status === 1).length;
const endedActivities = activities.filter(a => a.status === 2).length;
// 计算总浏览量(假设每个活动都有浏览量字段,否则显示0)
const totalViews = activities.reduce((sum, activity) => {
return sum + (activity.view_count || activity.visits || activity.pv || 0);
}, 0);
// 获取最近的活动 - 按更新时间排序
const recentActivities = activities
.sort((a, b) => new Date(b.update_time || b.updated_at || b.create_time || b.created_at) - new Date(a.update_time || a.updated_at || a.create_time || a.created_at))
.slice(0, 5)
.map(a => ({
id: a.id,
activity_id: a.activity_id, // 保存活动标识符,用于链接跳转
name: a.name,
status: a.status === 0 ? '未发布' : a.status === 1 ? '已发布' : '已停止',
statusColor: a.status === 0 ? 'bg-amber-100 text-amber-700' : a.status === 1 ? 'bg-emerald-100 text-emerald-700' : 'bg-slate-100 text-slate-600',
createTime: formatActivityTime(a.update_time || a.updated_at || a.create_time || a.created_at),
updateTime: a.update_time || a.updated_at || a.create_time || a.created_at, // 保存原始时间值用于计算相对时间
}));
return {
total_activities: totalActivities,
active_activities: activeActivities,
ended_activities: endedActivities,
total_views: totalViews, // 新增总浏览量字段
total_participants: 0,
recent_activities: recentActivities
};
}
};
// 时间格式化函数(全局可用)
const formatActivityTime = (timeInput) => {
if (!timeInput) return '-';
let date;
if (timeInput instanceof Date) {
date = timeInput;
} else {
// 尝试解析时间字符串
date = new Date(timeInput);
// 如果解析失败,尝试处理特殊格式
if (isNaN(date.getTime())) {
// 处理可能的格式,比如 "2026/03/18 10:30:00"
const cleaned = String(timeInput).replace(/\//g, '-');
date = new Date(cleaned);
if (isNaN(date.getTime())) {
return String(timeInput);
}
}
}
// 格式化为北京时间
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
const seconds = String(date.getSeconds()).padStart(2, '0');
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};
// 计算相对时间(如 xx小时前 xx分钟前)
const formatRelativeTime = (timeInput) => {
if (!timeInput) return '';
let date;
if (timeInput instanceof Date) {
date = timeInput;
} else {
date = new Date(timeInput);
if (isNaN(date.getTime())) {
return '';
}
}
const now = new Date();
const diffMs = now - date;
const diffMinutes = Math.floor(diffMs / (1000 * 60));
const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
if (diffDays > 0) {
return `${diffDays}天前`;
} else if (diffHours > 0) {
const remainingMinutes = diffMinutes % 60;
if (remainingMinutes > 0) {
return `${diffHours}小时前${remainingMinutes}分钟前`;
}
return `${diffHours}小时前`;
} else if (diffMinutes > 0) {
return `${diffMinutes}分钟前`;
} else {
return '刚刚';
}
};
// --- 修改密码弹窗组件 ---
const ChangePasswordModal = ({ isOpen, onClose, onSuccess }) => {
const [oldPassword, setOldPassword] = useState('');
const [newPassword, setNewPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
const [showOldPassword, setShowOldPassword] = useState(false);
const [showNewPassword, setShowNewPassword] = useState(false);
const [showConfirmPassword, setShowConfirmPassword] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const [errors, setErrors] = useState([]);
const [successMessage, setSuccessMessage] = useState('');
const validateForm = () => {
const errors = [];
if (!oldPassword.trim()) {
errors.push('请输入旧密码');
}
if (!newPassword.trim()) {
errors.push('请输入新密码');
} else if (newPassword.length < 6) {
errors.push('密码长度至少为6位');
}
if (!confirmPassword.trim()) {
errors.push('请确认密码');
} else if (newPassword !== confirmPassword) {
errors.push('两次输入的密码不一致');
}
return errors;
};
const handleSubmit = async (e) => {
e.preventDefault();
setErrors([]);
setSuccessMessage('');
const validationErrors = validateForm();
if (validationErrors.length > 0) {
setErrors(validationErrors);
return;
}
setIsLoading(true);
try {
const result = await window.H5CmsAPI.AuthAPI.changePassword(oldPassword, newPassword);
if (result.code === 200) {
setSuccessMessage('密码修改成功!');
setTimeout(() => {
onSuccess();
}, 1500);
}
} catch (error) {
setErrors([error.message]);
} finally {
setIsLoading(false);
}
};
if (!isOpen) return null;
return (
<div className="fixed top-[-100px] left-[-100px] right-[-100px] bottom-[-100px] z-[9999] flex items-center justify-center">
<div className="absolute top-[-100px] left-[-100px] right-[-100px] bottom-[-100px] bg-slate-900/40 backdrop-blur-xl"></div>
<div className="relative bg-white rounded-2xl shadow-xl max-w-md w-full max-h-[90vh] overflow-y-auto z-[10000]">
<div className="px-6 py-4 border-b border-slate-200 flex items-center justify-between">
<h2 className="text-lg font-semibold text-slate-800">修改密码</h2>
<button onClick={onClose} className="text-slate-400 hover:text-slate-600 transition-colors">
<Icon name="X" className="w-5 h-5" />
</button>
</div>
<div className="px-6 py-4">
<form onSubmit={handleSubmit} className="space-y-4">
{errors.length > 0 && (
<div className="p-4 bg-red-50 border border-red-200 rounded-lg">
{errors.map((error, index) => (
<div key={index} className="flex items-center text-red-600 text-sm">
<Icon name="AlertCircle" className="w-4 h-4 mr-2 flex-shrink-0" />
{error}
</div>
))}
</div>
)}
{successMessage && (
<div className="p-4 bg-green-50 border border-green-200 rounded-lg">
<div className="flex items-center text-green-600">
<Icon name="CheckCircle" className="w-5 h-5 mr-2" />
{successMessage}
</div>
</div>
)}
<div>
<label className="block text-sm font-medium text-slate-700 mb-2">旧密码</label>
<div className="relative">
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<Icon name="Lock" className="h-5 w-5 text-slate-400" />
</div>
<input
type={showOldPassword ? 'text' : 'password'}
value={oldPassword}
onChange={(e) => setOldPassword(e.target.value)}
className="block w-full pl-10 pr-10 py-2 border border-slate-300 rounded-lg leading-5 bg-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
placeholder="请输入旧密码"
disabled={isLoading}
/>
<div className="absolute inset-y-0 right-0 pr-3 flex items-center">
<button
type="button"
onClick={() => setShowOldPassword(!showOldPassword)}
className="text-slate-400 hover:text-slate-500 focus:outline-none"
disabled={isLoading}
>
{showOldPassword ? <Icon name="EyeOff" className="h-5 w-5" /> : <Icon name="Eye" className="h-5 w-5" />}
</button>
</div>
</div>
</div>
<div>
<label className="block text-sm font-medium text-slate-700 mb-2">新密码</label>
<div className="relative">
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<Icon name="Lock" className="h-5 w-5 text-slate-400" />
</div>
<input
type={showNewPassword ? 'text' : 'password'}
value={newPassword}
onChange={(e) => setNewPassword(e.target.value)}
className="block w-full pl-10 pr-10 py-2 border border-slate-300 rounded-lg leading-5 bg-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
placeholder="请输入新密码"
disabled={isLoading}
/>
<div className="absolute inset-y-0 right-0 pr-3 flex items-center">
<button
type="button"
onClick={() => setShowNewPassword(!showNewPassword)}
className="text-slate-400 hover:text-slate-500 focus:outline-none"
disabled={isLoading}
>
{showNewPassword ? <Icon name="EyeOff" className="h-5 w-5" /> : <Icon name="Eye" className="h-5 w-5" />}
</button>
</div>
</div>
</div>
<div>
<label className="block text-sm font-medium text-slate-700 mb-2">确认新密码</label>
<div className="relative">
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<Icon name="Lock" className="h-5 w-5 text-slate-400" />
</div>
<input
type={showConfirmPassword ? 'text' : 'password'}
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
className="block w-full pl-10 pr-10 py-2 border border-slate-300 rounded-lg leading-5 bg-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
placeholder="请确认新密码"
disabled={isLoading}
/>
<div className="absolute inset-y-0 right-0 pr-3 flex items-center">
<button
type="button"
onClick={() => setShowConfirmPassword(!showConfirmPassword)}
className="text-slate-400 hover:text-slate-500 focus:outline-none"
disabled={isLoading}
>
{showConfirmPassword ? <Icon name="EyeOff" className="h-5 w-5" /> : <Icon name="Eye" className="h-5 w-5" />}
</button>
</div>
</div>
</div>
<div className="pt-4">
<button
type="submit"
disabled={isLoading}
className="w-full flex justify-center py-2 px-4 border border-transparent rounded-lg shadow-sm text-sm font-medium text-white bg-blue-500 hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-colors"
>
{isLoading ? (
<div className="flex items-center">
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
修改中...
</div>
) : '修改密码'}
</button>
</div>
</form>
</div>
</div>
</div>
);
};
// --- 用户菜单弹窗组件 ---
const UserMenuModal = ({ isOpen, onClose, onChangePassword, onLogout }) => {
if (!isOpen) return null;
return (
<div className="fixed top-[-100px] left-[-100px] right-[-100px] bottom-[-100px] z-[9998] flex items-center justify-center">
<div className="absolute top-[-100px] left-[-100px] right-[-100px] bottom-[-100px] bg-slate-900/40 backdrop-blur-xl" onClick={onClose}></div>
<div className="relative bg-white rounded-2xl shadow-xl max-w-sm w-full max-h-[90vh] overflow-y-auto z-[10000]">
<div className="px-6 py-4 border-b border-slate-200">
<h2 className="text-lg font-semibold text-slate-800">用户菜单</h2>
</div>
<div className="px-6 py-4 space-y-3">
<button
onClick={() => {
onClose();
onChangePassword();
}}
className="w-full flex items-center justify-start px-4 py-3 rounded-xl text-slate-700 border-2 border-gray-200 hover:bg-yellow-50 hover:text-yellow-800 hover:border-yellow-400 transition-all"
>
<Icon name="User" className="w-5 h-5 mr-3" />
修改密码
</button>
<button
onClick={() => {
onClose();
onLogout();
}}
className="w-full flex items-center justify-start px-4 py-3 rounded-xl text-slate-700 border-2 border-gray-200 hover:bg-red-50 hover:text-red-800 hover:border-red-400 transition-all"
>
<Icon name="LogOut" className="w-5 h-5 mr-3" />
退出账号
</button>
<button
onClick={onClose}
className="w-full flex items-center justify-start px-4 py-3 rounded-xl text-slate-700 border-2 border-gray-200 hover:bg-blue-50 hover:text-blue-800 hover:border-blue-300 transition-all"
>
<Icon name="X" className="w-5 h-5 mr-3" />
取消
</button>
</div>
</div>
</div>
);
};
// 加载状态组件
const LoadingSpinner = () => (
<div className="flex items-center justify-center p-4">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
</div>
);
// --- 主组件 ---
function App() {
const [currentTime, setCurrentTime] = useState(new Date());
const [activeMenu, setActiveMenu] = useState('home');
const [recentActivities, setRecentActivities] = useState([]);
const [stats, setStats] = useState({
totalActivities: 0,
activeActivities: 0,
endedActivities: 0,
totalViews: 0, // 新增总浏览量字段
totalParticipants: 0
});
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const [lastUpdateTime, setLastUpdateTime] = useState(null); // 新增API连接成功时间
const [systemStatus, setSystemStatus] = useState('checking'); // 'checking' | 'success' | 'error'
const [authChecker, setAuthChecker] = useState(null);
const [isUserMenuOpen, setIsUserMenuOpen] = useState(false);
const [isChangePasswordModalOpen, setIsChangePasswordModalOpen] = useState(false);
// 获取用户信息
const userInfo = LoginManager?.getUserInfo() || { name: '用户', role: 'user' };
const username = userInfo.name || '用户';
const userRoleId = userInfo.roleId;
// 初始化权限检查器和加载数据
useEffect(() => {
// 注意:权限检查器已通过 auth_checker.js 中的 DOMContentLoaded 事件自动初始化
// 这里不再需要手动调用 initPageAuth(),避免重复检查
// 获取已经初始化的权限检查器实例
const checker = window.pageAuthInstance || initPageAuth({
requireAuth: true,
allowedRoles: ['super_admin', 'admin', 'operator'],
redirectTo: 'login.html'
});
setAuthChecker(checker);
// 加载数据
loadDashboardData();
// 清理函数
return () => {
checker.stopPeriodicCheck();
};
}, []);
// 调试日志工具
const pageLogger = {
info: (msg, data) => console.log(`[首页数据加载] ${msg}`, data || ''),
success: (msg, data) => console.log(`%c[首页数据加载] ${msg}`, 'color: #10b981; font-weight: bold;', data || ''),
error: (msg, error) => console.error(`%c[首页数据加载] ${msg}`, 'color: #ef4444; font-weight: bold;', error),
warn: (msg, data) => console.warn(`[首页数据加载] ${msg}`, data || '')
};
const loadDashboardData = async () => {
pageLogger.info('开始加载仪表盘数据...');
console.log('%c=== 首页数据加载开始 ===', 'background: #3b82f6; color: white; padding: 4px 8px; border-radius: 4px;');
try {
setLoading(true);
setError(null);
setSystemStatus('checking'); // 开始检查
pageLogger.info('正在调用 api.getDashboardStats()...');
const startTime = Date.now();
const dashboardStats = await api.getDashboardStats();
const duration = Date.now() - startTime;
pageLogger.success(`API调用成功,耗时 ${duration}ms`, {
总活动数: dashboardStats.total_activities,
进行中: dashboardStats.active_activities,
已结束: dashboardStats.ended_activities,
最近活动数: dashboardStats.recent_activities?.length || 0
});
setStats({
totalActivities: dashboardStats.total_activities,
activeActivities: dashboardStats.active_activities,
endedActivities: dashboardStats.ended_activities,
totalViews: dashboardStats.total_views, // 新增总浏览量
totalParticipants: dashboardStats.total_participants
});
setRecentActivities(dashboardStats.recent_activities);
// 设置API连接成功的时间
setLastUpdateTime(new Date());
setSystemStatus('success'); // 成功状态
pageLogger.success('数据加载完成!');
console.log('%c=== 首页数据加载完成 ===', 'background: #10b981; color: white; padding: 4px 8px; border-radius: 4px;');
} catch (err) {
pageLogger.error('加载失败', {
错误消息: err.message,
错误代码: err.code,
错误详情: err.details,
完整错误: err
});
setError('加载数据失败: ' + err.message);
setSystemStatus('error'); // 失败状态
// 失败时不使用模拟数据,保持空状态
setStats({
totalActivities: 0,
activeActivities: 0,
endedActivities: 0,
totalViews: 0,
totalParticipants: 0
});
setRecentActivities([]);
} finally {
setLoading(false);
}
};
// 实时更新时间
useEffect(() => {
const timer = setInterval(() => {
setCurrentTime(new Date());
}, 1000);
return () => clearInterval(timer);
}, []);
// 格式化日期时间(用于导航栏显示)
const formatDateTime = (date) => {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
const weekday = weekdays[date.getDay()];
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
const seconds = String(date.getSeconds()).padStart(2, '0');
return {
date: `${year}年${month}月${day}日`,
weekday,
time: `${hours}:${minutes}:${seconds}`
};
};
const timeInfo = formatDateTime(currentTime);
// 格式化最后更新时间显示
const formatLastUpdate = (time) => {
if (!time) return '尚未更新';
const timeObj = new Date(time);
const year = timeObj.getFullYear();
const month = String(timeObj.getMonth() + 1).padStart(2, '0');
const day = String(timeObj.getDate()).padStart(2, '0');
const hours = String(timeObj.getHours()).padStart(2, '0');
const minutes = String(timeObj.getMinutes()).padStart(2, '0');
const seconds = String(timeObj.getSeconds()).padStart(2, '0');
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};
// 获取用户信息,判断是否是超级管理员
const currentUserInfo = LoginManager?.getUserInfo();
const isSuperAdmin = currentUserInfo?.roleId === 1 || currentUserInfo?.role === 'super_admin';
// 处理退出登录
const handleLogout = () => {
if (confirm("确定要退出吗?")) {
if (authChecker) {
authChecker.logout();
} else {
LoginManager.clearLoginInfo();
window.location.href = 'login.html';
}
}
};
// 处理修改密码成功
const handleChangePasswordSuccess = () => {
setIsChangePasswordModalOpen(false);
};
const menuItems = [
{ id: 'home', label: '首页', icon: 'Home', path: 'homepage.html' },
{ id: 'activity', label: '活动列表', icon: 'List', path: 'list.html' },
...(isSuperAdmin ? [{ id: 'account', label: '账号管理', icon: 'Users', path: 'account.html' }] : [])
];
// 加载状态组件
const LoadingSpinner = () => (
<div className="flex items-center justify-center p-4">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
</div>
);
// 统计卡片组件
const StatCard = ({ title, value, icon, color, loading }) => {
if (loading) {
return (
<div className="bg-white rounded-xl shadow-sm border border-slate-100 p-6">
<div className="flex items-center justify-between mb-4">
<div className="w-12 h-12 rounded-xl skeleton"></div>
</div>
<div>
<p className="text-2xl font-bold mb-1 h-8 skeleton rounded"></p>
<p className="text-sm h-4 skeleton rounded w-24"></p>
</div>
</div>
);
}
return (
<div className="bg-white rounded-xl shadow-sm border border-slate-100 p-6 hover:shadow-md transition-shadow">
<div className="flex items-center justify-between mb-4">
<div className={`w-12 h-12 rounded-xl flex items-center justify-center ${color}`}>
<Icon name={icon} className="w-6 h-6 text-white" />
</div>
</div>
<div>
<p className="text-2xl font-bold text-slate-800 mb-1">{value}</p>
<p className="text-sm text-slate-500">{title}</p>
</div>
</div>
);
};
return (
<div className="min-h-screen bg-[#f1f5f9] flex flex-col font-sans">
{/* 顶部固定导航栏 */}
<header className="h-16 bg-white border-b border-slate-200 flex items-center justify-between px-6 shrink-0 shadow-sm z-30 fixed top-0 left-0 right-0">
{/* 左侧标题 */}
<div className="flex items-center space-x-4 w-1/3">
<h1 className="font-bold text-slate-800">活动管理系统</h1>
</div>
{/* 右侧信息 */}
<div className="flex items-center space-x-6">
{/* 日期时间 */}
<div className="flex items-center space-x-4 text-sm text-slate-600">
<span>{timeInfo.date}</span>
<span>{timeInfo.weekday}</span>
<span className="font-mono">{timeInfo.time}</span>
</div>
</div>
</header>
<div className="flex pt-16 min-h-screen">
{/* 左侧侧边导航栏 */}
<aside className="w-48 bg-white border-r border-slate-200 shrink-0 shadow-[2px_0_8px_rgba(0,0,0,0.02)] fixed left-0 top-16 h-[calc(100vh-4rem)] overflow-y-auto z-10">
<nav className="py-2 h-full flex flex-col overflow-hidden">
{menuItems.map((item) => (
<a
key={item.id}
href={item.path}
className={`flex items-center px-6 py-3 text-sm font-medium transition-all
${activeMenu === item.id
? 'text-blue-600 bg-blue-50 border-r-4 border-blue-600'
: 'text-slate-600 hover:bg-slate-50 hover:text-slate-900'
}
`}
>
<Icon name={item.icon} className="w-5 h-5 mr-3" />
{item.label}
</a>
))}
{/* 用户信息 - 底部 */}
<div className="mt-auto pt-0 border-t border-slate-200">
<div
className="relative"
onClick={() => setIsUserMenuOpen(true)}
>
<div className="flex items-center px-6 py-3 text-sm font-medium text-slate-600 hover:bg-slate-50 cursor-pointer">
<Icon name="User" className="w-5 h-5 flex-shrink-0" />
<span className="ml-3 text-ellipsis overflow-hidden whitespace-nowrap">
{username}
{userRoleId && roleMap[userRoleId] && (
<span className={`ml-2 text-xs ${roleColorMap[userRoleId] || 'bg-gray-100 text-gray-800'} px-1.5 py-0.5 rounded`}>
{roleMap[userRoleId]}
</span>
)}
</span>
</div>
</div>
</div>
</nav>
</aside>
{/* 主内容区域 */}
<main className="flex-1 p-6 ml-48 space-y-6">
{/* 欢迎标题 */}
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold text-slate-800">你好,{username}!</h1>
<p className="text-slate-500 mt-1">这是你的数据总览</p>
</div>
</div>
{/* 数据总览卡片 */}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-5">
<StatCard
title="总活动数"
value={stats.totalActivities}
icon="Calendar"
color="bg-blue-500"
loading={loading}
/>
<StatCard
title="进行中活动"
value={stats.activeActivities}
icon="Target"
color="bg-emerald-500"
loading={loading}
/>
<StatCard
title="总浏览量"
value={stats.totalViews.toLocaleString()}
icon="Eye"
color="bg-cyan-500"
loading={loading}
/>
<StatCard
title="总参与人数"
value={stats.totalParticipants.toLocaleString()}
icon="Users"
color="bg-violet-500"
loading={loading}
/>
</div>
{/* 下方两栏布局 */}
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
{/* 快速开始 - 最近操作的活动 */}
<div className="lg:col-span-2">
<div className="bg-white rounded-xl shadow-sm border border-slate-100 overflow-hidden">
<div className="flex items-center justify-between px-6 py-5 border-b border-slate-100">
<h2 className="text-lg font-semibold text-slate-800">快速开始</h2>
<a
href="list.html"
className="flex items-center text-sm text-blue-600 hover:text-blue-700 font-medium transition-colors"
>
查看全部
<Icon name="ArrowRight" className="w-4 h-4 ml-1" />
</a>
</div>
<div className="divide-y divide-slate-100">
{loading ? (
// 骨架屏加载状态
Array.from({ length: 5 }).map((_, index) => (
<div key={index} className="px-6 py-4 flex items-center justify-between">
<div className="flex items-center space-x-4">
<div className="w-10 h-10 skeleton rounded-lg flex-shrink-0"></div>
<div className="space-y-2">
<div className="h-5 skeleton rounded w-48"></div>
<div className="h-4 skeleton rounded w-36"></div>
</div>
</div>
<div className="flex items-center space-x-3">
<div className="h-6 skeleton rounded-full w-16"></div>
<div className="w-8 h-8 skeleton rounded-lg"></div>
</div>
</div>
))
) : (
// 实际内容
recentActivities.map((activity) => (
<div key={activity.id} className="px-6 py-4 hover:bg-slate-50 transition-colors flex items-center justify-between">
<div className="flex items-center space-x-4">
<div className="w-10 h-10 bg-slate-100 rounded-lg flex items-center justify-center flex-shrink-0">
<Icon name="Calendar" className="w-5 h-5 text-slate-500" />
</div>
<div>
<h3 className="font-medium text-slate-800">{activity.name}</h3>
<p className="text-sm text-slate-500 flex items-center">
<Icon name="Clock" className="w-3.5 h-3.5 mr-1.5" />
{activity.createTime}
<span className="ml-2 text-xs text-slate-400">
{formatRelativeTime(activity.updateTime)}
</span>
</p>
</div>
</div>
<div className="flex items-center space-x-3">
<span className={`px-3 py-1 rounded-full text-xs font-medium ${activity.statusColor}`}>
{activity.status}
</span>
<a
href={`detail.html#${activity.activity_id}/base`}
className="p-2 text-slate-400 hover:text-slate-600 hover:bg-slate-100 rounded-lg transition-colors"
title="编辑基础信息"
>
<Icon name="Edit" className="w-4 h-4" />
</a>
</div>
</div>
))
)}
</div>
</div>
</div>
{/* 快捷操作 */}
<div className="space-y-6">
{/* 快捷操作卡片 */}
<div className="bg-white rounded-xl shadow-sm border border-slate-100 overflow-hidden">
<div className="px-6 py-5 border-b border-slate-100">
<h2 className="text-lg font-semibold text-slate-800">快捷操作</h2>
</div>
<div className="p-4 space-y-2">
<a
href="list.html"
className="flex items-center px-4 py-3 rounded-lg text-slate-700 hover:bg-slate-50 hover:text-slate-900 transition-colors"
>
<div className="w-8 h-8 bg-blue-50 rounded-lg flex items-center justify-center mr-3">
<Icon name="List" className="w-4 h-4 text-blue-600" />
</div>
<span className="font-medium">活动列表</span>
</a>
<a
href="list.html?new=true"
className="flex items-center px-4 py-3 rounded-lg text-slate-700 hover:bg-slate-50 hover:text-slate-900 transition-colors"
>
<div className="w-8 h-8 bg-emerald-50 rounded-lg flex items-center justify-center mr-3">
<Icon name="Plus" className="w-4 h-4 text-emerald-600" />
</div>
<span className="font-medium">新建活动</span>
</a>
</div>
</div>
{/* 系统状态卡片 */}
<div className={`rounded-xl shadow-sm overflow-hidden ${
systemStatus === 'checking'
? 'bg-gradient-to-br from-amber-500 to-orange-600'
: systemStatus === 'success'
? 'bg-gradient-to-br from-emerald-500 to-green-600'
: 'bg-gradient-to-br from-red-500 to-rose-600'
}`}>
<div className="p-6 text-white">
<div className="flex items-center space-x-3 mb-4">
<div className="w-10 h-10 bg-white/20 rounded-lg flex items-center justify-center">
{systemStatus === 'checking' ? (
<div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white"></div>
) : systemStatus === 'success' ? (
<Icon name="CheckCircle" className="w-5 h-5 text-white" />
) : (
<Icon name="XCircle" className="w-5 h-5 text-white" />
)}
</div>
<div>
<h3 className="font-semibold">
{systemStatus === 'checking'
? '系统检查中'
: systemStatus === 'success'
? '系统运行正常'
: '系统运行失败'}
</h3>
<p className={`text-sm ${
systemStatus === 'checking' ? 'text-amber-100'
: systemStatus === 'success' ? 'text-emerald-100'
: 'text-red-100'
}`}>
{systemStatus === 'checking'
? 'API连接中'
: systemStatus === 'success'
? 'API连接成功'
: 'API连接失败'}
</p>
</div>
</div>
<div className={`text-sm ${
systemStatus === 'checking' ? 'text-amber-100'
: systemStatus === 'success' ? 'text-emerald-100'
: 'text-red-100'
}`}>
{systemStatus === 'checking'
? '正在连接服务器...'
: `最后更新:${formatLastUpdate(lastUpdateTime)}`}
</div>
</div>
</div>
</div>
</div>
</main>
</div>
{/* 用户菜单弹窗 */}
<UserMenuModal
isOpen={isUserMenuOpen}
onClose={() => setIsUserMenuOpen(false)}
onChangePassword={() => setIsChangePasswordModalOpen(true)}
onLogout={handleLogout}
/>
{/* 修改密码弹窗 */}
<ChangePasswordModal
isOpen={isChangePasswordModalOpen}
onClose={() => setIsChangePasswordModalOpen(false)}
onSuccess={handleChangePasswordSuccess}
/>
</div>
);
}
// 渲染应用
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
</script>
</body>
</html>