-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdetail.html
More file actions
2875 lines (2700 loc) · 154 KB
/
detail.html
File metadata and controls
2875 lines (2700 loc) · 154 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
<!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>
<script src="https://cdn.tailwindcss.com"></script>
<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>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/qrcodejs@1.0.0/qrcode.min.js"></script>
<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 封装 (必须在 text/babel 之前加载) -->
<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; }
</style>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
const { useState, useEffect } = React;
const Icon = ({ name, className }) => {
const icons = {
Home: React.createElement(React.Fragment, null,
React.createElement("path", { d: "m3 9 9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" }),
React.createElement("polyline", { points: "9 22 9 12 15 12 15 22" })
),
List: React.createElement(React.Fragment, null,
React.createElement("line", { x1: "8", x2: "21", y1: "6", y2: "6" }),
React.createElement("line", { x1: "8", x2: "21", y1: "12", y2: "12" }),
React.createElement("line", { x1: "8", x2: "21", y1: "18", y2: "18" }),
React.createElement("line", { x1: "3", x2: "3.01", y1: "6", y2: "6" }),
React.createElement("line", { x1: "3", x2: "3.01", y1: "12", y2: "12" }),
React.createElement("line", { x1: "3", x2: "3.01", y1: "18", y2: "18" })
),
ChevronDown: React.createElement("polyline", { points: "6 9 12 15 18 9" }),
Edit: React.createElement(React.Fragment, null,
React.createElement("path", { d: "M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" }),
React.createElement("path", { d: "M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z" })
),
Gift: React.createElement(React.Fragment, null,
React.createElement("polyline", { points: "20 12 20 22 4 22 4 12" }),
React.createElement("rect", { width: "20", height: "5", x: "2", y: "7" }),
React.createElement("line", { x1: "12", x2: "12", y1: "22", y2: "7" }),
React.createElement("path", { d: "M12 7H7.5a2.5 2.5 0 0 1 0-5C11 2 12 7 12 7z" }),
React.createElement("path", { d: "M12 7h4.5a2.5 2.5 0 0 0 0-5C13 2 12 7 12 7z" })
),
Layout: React.createElement(React.Fragment, null,
React.createElement("rect", { width: "18", height: "18", x: "3", y: "3", rx: "2", ry: "2" }),
React.createElement("line", { x1: "3", x2: "21", y1: "9", y2: "9" }),
React.createElement("line", { x1: "9", x2: "9", y1: "21", y2: "9" })
),
BarChart: React.createElement(React.Fragment, null,
React.createElement("line", { x1: "12", x2: "12", y1: "20", y2: "10" }),
React.createElement("line", { x1: "18", x2: "18", y1: "20", y2: "4" }),
React.createElement("line", { x1: "6", x2: "6", y1: "20", y2: "16" })
),
QrCode: React.createElement(React.Fragment, null,
React.createElement("rect", { width: "5", height: "5", x: "3", y: "3", rx: "1" }),
React.createElement("rect", { width: "5", height: "5", x: "16", y: "3", rx: "1" }),
React.createElement("rect", { width: "5", height: "5", x: "16", y: "16", rx: "1" }),
React.createElement("rect", { width: "5", height: "5", x: "3", y: "16", rx: "1" })
),
Download: React.createElement(React.Fragment, null,
React.createElement("path", { d: "M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" }),
React.createElement("polyline", { points: "7 10 12 15 17 10" }),
React.createElement("line", { x1: "12", x2: "12", y1: "15", y2: "3" })
),
Save: React.createElement(React.Fragment, null,
React.createElement("path", { d: "M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z" }),
React.createElement("polyline", { points: "17 21 17 13 7 13 7 21" }),
React.createElement("polyline", { points: "7 3 7 8 15 8" })
),
User: React.createElement(React.Fragment, null,
React.createElement("path", { d: "M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2" }),
React.createElement("circle", { cx: "12", cy: "7", r: "4" })
),
LogOut: React.createElement(React.Fragment, null,
React.createElement("path", { d: "M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" }),
React.createElement("polyline", { points: "16 17 21 12 16 7" }),
React.createElement("line", { x1: "21", x2: "9", y1: "12", y2: "12" })
),
Link: React.createElement(React.Fragment, null,
React.createElement("path", { d: "M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71" }),
React.createElement("path", { d: "M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71" })
),
X: React.createElement(React.Fragment, null,
React.createElement("line", { x1: "18", x2: "6", y1: "6", y2: "18" }),
React.createElement("line", { x1: "6", x2: "18", y1: "6", y2: "18" })
),
Eye: React.createElement(React.Fragment, null,
React.createElement("path", { d: "M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" }),
React.createElement("circle", { cx: "12", cy: "12", r: "3" })
),
EyeOff: React.createElement(React.Fragment, null,
React.createElement("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" }),
React.createElement("line", { x1: "1", x2: "23", y1: "1", y2: "23" })
),
AlertCircle: React.createElement(React.Fragment, null,
React.createElement("circle", { cx: "12", cy: "12", r: "10" }),
React.createElement("line", { x1: "12", x2: "12", y1: "8", y2: "12" }),
React.createElement("line", { x1: "12", x2: "12.01", y1: "16", y2: "16" })
),
Lock: React.createElement(React.Fragment, null,
React.createElement("rect", { x: "3", y: "11", width: "18", height: "11", rx: "2", ry: "2" }),
React.createElement("path", { d: "M7 11V7a5 5 0 0 1 10 0v4" })
),
CheckCircle: React.createElement(React.Fragment, null,
React.createElement("path", { d: "M22 11.08V12a10 10 0 1 1-5.93-9.14" }),
React.createElement("polyline", { points: "22 4 12 14.01 9 11.01" })
),
XCircle: React.createElement(React.Fragment, null,
React.createElement("circle", { cx: "12", cy: "12", r: "10" }),
React.createElement("line", { x1: "15", x2: "9", y1: "9", y2: "15" }),
React.createElement("line", { x1: "9", x2: "15", y1: "9", y2: "15" })
)
};
return React.createElement("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] || React.createElement("circle", { cx: "12", cy: "12", r: "10" }));
};
// 生成随机16位活动码
const generateActivityCode = () => {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
return Array.from({ length: 16 }, () => chars[Math.floor(Math.random() * chars.length)]).join('');
};
// 生成随机邀请码
const generateInviteCode = () => {
return Math.random().toString(36).substr(2, 8).toUpperCase();
};
// 角色名称映射
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'
};
// --- 修改密码弹窗组件 ---
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>
);
};
function App() {
const [currentTime, setCurrentTime] = useState(new Date());
const [showUserMenu, setShowUserMenu] = useState(false);
const [isUserMenuOpen, setIsUserMenuOpen] = useState(false);
const [isChangePasswordModalOpen, setIsChangePasswordModalOpen] = useState(false);
const [activeMenu, setActiveMenu] = useState('base');
const [authChecker, setAuthChecker] = useState(null);
// 统计数据状态
const [statsDataLoaded, setStatsDataLoaded] = useState(false);
const [processedStatsData, setProcessedStatsData] = useState({
totalVisits: 0,
totalUniqueVisitors: 0,
totalSubmits: 0,
conversionRate: 0,
weekData: [
{ date: "3/1", visits: 0, submits: 0 },
{ date: "3/2", visits: 0, submits: 0 },
{ date: "3/3", visits: 0, submits: 0 },
{ date: "3/4", visits: 0, submits: 0 },
{ date: "3/5", visits: 0, submits: 0 },
{ date: "3/6", visits: 0, submits: 0 },
{ date: "3/7", visits: 0, submits: 0 }
],
sourceData: [
{ name: "微信朋友圈", value: 0, color: "#3B82F6" },
{ name: "公众号", value: 0, color: "#10B981" },
{ name: "直接访问", value: 0, color: "#F59E0B" },
{ name: "其他", value: 0, color: "#EF4444" }
],
userRecords: []
});
// 获取用户信息
const userInfo = LoginManager?.getUserInfo() || { name: '用户', role: 'user' };
const userRoleId = userInfo.roleId;
// 处理退出登录
const handleLogout = () => {
if (confirm("确定要退出吗?")) {
if (authChecker) {
authChecker.logout();
} else {
LoginManager.clearLoginInfo();
window.location.href = 'login.html';
}
}
};
// 处理修改密码成功
const handleChangePasswordSuccess = () => {
setIsChangePasswordModalOpen(false);
};
const username = userInfo.name || '用户';
const isAdmin = userInfo.role === 'admin' || userInfo.role === 'super_admin';
const [activityDetail, setActivityDetail] = useState({
id: '0001',
name: '未加载',
activityId: '', // 用户输入的自定义唯一标识符
activityCode: generateActivityCode(), // 活动码,随机生成
status: '已发布',
fee: 99.9,
creator: window.LoginManager?.getUserInfo()?.real_name || window.LoginManager?.getUserInfo()?.username || '未知用户',
inviteCode: generateInviteCode(),
createTime: '2026-03-01 10:00:00',
startTime: '2026-03-10 00:00:00',
endTime: '2026-04-10 23:59:59',
isInvitation: 0,
imgPath: '',
shareTitle: '无主标题',
shareSubtitle: '无副标题',
shareThumbnail: '',
description: '<p>未加载描述</p>',
maximumLimit: 1,
price: 0,
physicalInventory: 100,
lotteryConfig: {
nulotteryProbability: 30,
oulotteryProbability: 20,
numberInActivity: 3,
needToBindMobile: 0,
calculateRange: 'daily',
numberInRange: 1,
payMchId: '1234567890'
}
});
// 奖品列表数据
const [prizeList, setPrizeList] = useState([]);
// 加载奖品列表
const loadPrizeList = async (activityId) => {
if (!activityId || !window.H5CmsAPI) return;
try {
const result = await H5CmsAPI.PrizeAPI.getList(activityId);
if (result.data && Array.isArray(result.data)) {
setPrizeList(result.data);
// 奖品列表加载完成后,更新原始数据
setOriginalData(prev => ({
...prev,
prizeList: [...result.data]
}));
}
} catch (error) {
console.error('加载奖品列表失败:', error);
// 如果API调用失败,不显示错误提示,保持空列表
}
};
// 奖池列表数据
const [prizePoolList, setPrizePoolList] = useState([]);
const [prizePoolLoading, setPrizePoolLoading] = useState(false);
// 加载奖池列表
const loadPrizePoolList = async (activityId, params = {}) => {
if (!activityId || !window.H5CmsAPI) return;
setPrizePoolLoading(true);
try {
const result = await H5CmsAPI.PrizePoolAPI.getList(activityId, params);
if (result.data && Array.isArray(result.data)) {
setPrizePoolList(result.data);
}
} catch (error) {
console.error('加载奖池列表失败:', error);
// 保持空列表而不显示错误提示
} finally {
setPrizePoolLoading(false);
}
};
// 计算范围选项
const calculateRangeOptions = [
{ value: 'daily', label: '天' },
{ value: 'weekly', label: '周' },
{ value: 'monthly', label: '月' }
];
// 链接生成器状态(移到顶层符合Hook规则)
const [qrSize, setQrSize] = useState(400);
const [customSize, setCustomSize] = useState(400);
const [logoType, setLogoType] = useState('none');
const [qrCodeUrl, setQrCodeUrl] = useState('');
const [generating, setGenerating] = useState(false);
const [activityLink, setActivityLink] = useState('');
const [darkColor, setDarkColor] = useState('#000000');
const [lightColor, setLightColor] = useState('#ffffff');
const [transparentBg, setTransparentBg] = useState(false);
const [logoImage, setLogoImage] = useState(null);
const [logoSize, setLogoSize] = useState(25);
const [selectedPageId, setSelectedPageId] = useState(null);
// 初始化页面选择和活动链接
useEffect(() => {
const baseUrl = window.location.origin + window.location.pathname.replace('detail.html', '');
const activityIdentifier = activityDetail.activity_id || activityDetail.activityId;
// 确保 activityDetail 和 pages 都加载完成
if (activityIdentifier && pages.length > 0) {
// 初始化 selectedPageId
if (!selectedPageId) {
const firstPageId = pages.length > 0 ? pages[0].id : 'page-1';
setSelectedPageId(firstPageId);
}
// 确保活动链接已生成
if (!activityLink) {
const targetPageId = selectedPageId || (pages.length > 0 ? pages[0].id : 'page-1');
const defaultLink = `${baseUrl}page#${activityIdentifier}/${targetPageId}`;
setActivityLink(defaultLink);
}
}
}, [activityDetail.activity_id, activityDetail.activityId, pages]);
// 页面配置状态(从数据库获取)
const [pages, setPages] = useState([{ id: 'page-1' }]);
// 用户提交记录表格状态(移到顶层符合Hook规则)
const [searchTerm, setSearchTerm] = useState('');
const [currentPage, setCurrentPage] = useState(1);
const [showExportDropdown, setShowExportDropdown] = useState(false);
// 奖品弹窗状态(移到顶层符合Hook规则)
const [showPrizeModal, setShowPrizeModal] = useState(false);
const [editingPrize, setEditingPrize] = useState(null);
const [prizeFormData, setPrizeFormData] = useState({
id: '',
name: '',
type: 1,
amount: 0,
num: 0,
maxWinCount: 1,
winTimeRange: 'day'
});
useEffect(() => {
const timer = setInterval(() => setCurrentTime(new Date()), 1000);
// 初始化权限检查器
const checker = initPageAuth({
requireAuth: true,
allowedRoles: ['super_admin', 'admin', 'operator'],
redirectTo: 'login.html'
});
setAuthChecker(checker);
return () => {
clearInterval(timer);
checker.stopPeriodicCheck();
};
}, []);
// 当切换到数据看板菜单时加载统计数据
useEffect(() => {
if (activeMenu === 'data' && !statsDataLoaded && activityDetail.id) {
const loadStatsData = async () => {
try {
const [statsResult, trendResult, submissionsResult] = await Promise.all([
// 获取活动统计数据
H5CmsAPI.StatisticsAPI.getActivityStats(activityDetail.id).catch(error => {
console.error('获取活动统计数据失败:', error);
return { code: 500, data: null };
}),
// 获取活动趋势数据
H5CmsAPI.StatisticsAPI.getActivityTrend(activityDetail.id, { timeRange: '7' }).catch(error => {
console.error('获取活动趋势数据失败:', error);
return { code: 500, data: null };
}),
// 获取用户提交记录
H5CmsAPI.StatisticsAPI.getSubmissions(activityDetail.id, { page: 1, pageSize: 5 }).catch(error => {
console.error('获取用户提交记录失败:', error);
return { code: 500, data: null };
})
]);
// 处理数据,确保有默认值
const processedStatsData = statsResult.code === 200 ? statsResult.data : {
totalVisits: 0,
totalUniqueVisitors: 0,
totalSubmits: 0,
conversionRate: 0,
weekData: [],
sourceData: [],
userRecords: []
};
const processedTrendData = trendResult.code === 200 ? trendResult.data : [];
const processedSubmissionsData = submissionsResult.code === 200 ? submissionsResult.data : { list: [], total: 0, page: 1, pageSize: 5 };
// 设置处理后的数据
setProcessedStatsData({
totalVisits: processedStatsData.totalVisits,
totalUniqueVisitors: processedStatsData.totalUniqueVisitors,
totalSubmits: processedStatsData.totalSubmits,
conversionRate: processedStatsData.conversionRate,
weekData: processedStatsData.weekData.length > 0 ? processedStatsData.weekData : processedTrendData.length > 0 ? processedTrendData : [
{ date: "3/1", visits: 0, submits: 0 },
{ date: "3/2", visits: 0, submits: 0 },
{ date: "3/3", visits: 0, submits: 0 },
{ date: "3/4", visits: 0, submits: 0 },
{ date: "3/5", visits: 0, submits: 0 },
{ date: "3/6", visits: 0, submits: 0 },
{ date: "3/7", visits: 0, submits: 0 }
],
sourceData: processedStatsData.sourceData.length > 0 ? processedStatsData.sourceData : [
{ name: "微信朋友圈", value: 0, color: "#3B82F6" },
{ name: "公众号", value: 0, color: "#10B981" },
{ name: "直接访问", value: 0, color: "#F59E0B" },
{ name: "其他", value: 0, color: "#EF4444" }
],
userRecords: processedSubmissionsData.list.length > 0 ? processedSubmissionsData.list : processedStatsData.userRecords.length > 0 ? processedStatsData.userRecords : []
});
} catch (error) {
console.error('加载统计数据失败:', error);
// 保留默认值,显示空状态
} finally {
setStatsDataLoaded(true);
}
};
loadStatsData();
}
}, [activeMenu, statsDataLoaded, activityDetail.id]);
// 从URL参数获取活动ID
const getActivityIdFromUrl = () => {
// 优先尝试从hash获取:格式 #activityId/pageId 或 #activityId
const hash = window.location.hash.slice(1);
if (hash && hash.length > 0) {
// 如果hash包含斜杠,第一部分是activityId
const parts = hash.split('/');
return parts[0];
}
// 回退:从query获取
const params = new URLSearchParams(window.location.search);
return params.get('id');
};
// 加载活动详情
const loadActivityDetail = async (activityIdentifier) => {
try {
if (!window.H5CmsAPI) {
console.error('API未加载');
alert('API未加载,请刷新页面重试');
return;
}
console.log('正在加载活动详情,标识符=', activityIdentifier);
// 先尝试按自定义activity_id查找
let data = null;
try {
const result = await H5CmsAPI.ActivityAPI.getByActivityId(activityIdentifier);
data = result.data;
console.log('按activity_id加载成功');
} catch (e) {
console.log('按activity_id加载失败:', e.message);
// 如果按activity_id查找失败,设置activity_id为当前标识符,让用户可以继续编辑
console.log('没有找到现有活动,将作为新活动编辑');
// 保留活动标识符,让用户在保存时创建活动
const currentUser = window.LoginManager?.getUserInfo();
const newActivityDetail = {
...activityDetail,
activity_id: activityIdentifier,
creator: currentUser?.real_name || currentUser?.username || '未知用户',
createTime: new Date().toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' }),
status: '未发布'
};
setActivityDetail(newActivityDetail);
// 为新活动设置原始数据
setOriginalData({
activityDetail: { ...newActivityDetail },
prizeList: []
});
return;
}
console.log('加载活动详情成功:', data);
// 权限检查:3级用户只能查看自己创建的活动
// 使用数据库中的 roleId 数字属性判断用户等级
const currentUser = window.LoginManager?.getUserInfo();
const userRoleId = currentUser?.roleId;
console.log('用户角色ID(数字):', userRoleId);
if (userRoleId === 3 && data.creator_id !== currentUser.id) {
console.error('权限不足:3级用户只能查看自己创建的活动');
console.log('当前用户ID:', currentUser.id);
console.log('活动创建者ID:', data.creator_id);
alert('您没有权限查看此活动!');
// 重定向到活动列表
window.location.href = 'list.html';
return;
}
setActivityDetail(prev => ({
...prev,
...data,
// 还原扩展字段
...(data.extended || {}),
// 字段映射
activityId: data.activity_id,
activityCode: data.activity_code,
// 状态转换
status: data.status === 1 ? '已发布' : (data.status === 2 ? '已停止' : '未发布'),
startTime: data.start_time,
endTime: data.end_time,
maximumLimit: data.maximum_limit,
physicalInventory: data.physical_inventory,
shareTitle: data.share_title,
shareSubtitle: data.share_subtitle,
shareThumbnail: data.share_thumbnail,
isInvitation: data.is_invitation,
lotteryConfig: data.lottery_config,
// 映射创建者信息 - 优先使用数据库字段
creator: data.creator_name || data.creator || (data.extended?.creator || '未知用户')
}));
// 从API加载奖品列表
loadPrizeList(data.id);
// 数据加载完成后设置原始数据,用于检测修改
setOriginalData({
activityDetail: { ...data },
prizeList: []
});
// 从API加载奖池列表
loadPrizePoolList(data.id);
// 还原页面配置(与canvas.html保持一致)
if (data.page_config) {
if (data.page_config.pages && data.page_config.pages.length > 0) {
setPages(data.page_config.pages);
console.log('页面配置已加载:', data.page_config.pages);
// 确保在加载页面配置后,selectedPageId 和活动链接能正确更新
const firstPageId = data.page_config.pages[0].id;
setSelectedPageId(firstPageId);
// 生成活动链接
const baseUrl = window.location.origin + window.location.pathname.replace('detail.html', '');
const activityIdentifier = data.activity_id || data.activityId;
const defaultLink = `${baseUrl}page#${activityIdentifier}/${firstPageId}`;
setActivityLink(defaultLink);
}
}
} catch (err) {
console.error('加载活动详情失败:', err);
alert('加载活动详情失败: ' + err.message);
}
};
// 保存活动详情
const saveActivityDetail = async () => {
try {
if (!window.H5CmsAPI) {
alert('API未加载,请刷新页面重试');
return;
}
console.log('正在保存活动详情:', activityDetail);
// 判断是更新还是创建:检查是否有UUID格式的id
const isUpdate = activityDetail.id &&
activityDetail.id.length > 10 &&
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(activityDetail.id);
const { data, error } = isUpdate
? await H5CmsAPI.ActivityAPI.update(activityDetail.id, activityDetail)
: await H5CmsAPI.ActivityAPI.create({
...activityDetail,
activity_id: activityDetail.activity_id || activityDetail.id,
activity_code: generateActivityCode(), // 每次创建新活动都强制生成新的唯一码
invite_code: generateInviteCode(),
status: activityDetail.status === '已发布' ? 1 : 0,
is_deleted: false,
// 确保不传递可能导致问题的空 id
id: undefined
});
if (error) throw error;
alert('保存成功!活动ID: ' + data.id);
// 更新本地ID - 如果data.id有值,直接更新,不管之前有没有
if (data.id) {
setActivityDetail(prev => ({ ...prev, id: data.id }));
// 更新URL保持hash格式
const hash = window.location.hash || `#${data.activity_id}/base`;
window.history.replaceState({}, '', hash);
}
} catch (err) {
console.error('保存失败:', err);
alert('保存失败: ' + err.message);
}
};
// 页面加载时加载活动数据
useEffect(() => {
// 解析活动ID和标签页
const activityId = getActivityIdFromUrl();
// 从hash解析标签页
const hash = window.location.hash.slice(1);
if (hash && hash.length > 0) {
const parts = hash.split('/');
if (parts.length >= 2 && parts[1]) {
setActiveMenu(parts[1]);
}
}
// 首先检查是否有新创建的活动信息
const newActivity = sessionStorage.getItem('newActivity');
if (newActivity && activityId) {
console.log('使用 sessionStorage 中的新活动信息');
const activityData = JSON.parse(newActivity);
// 初始化新活动的详细信息
const newActivityDetail = {
...activityDetail,
activity_id: activityData.id, // 注意这里设置的是 activity_id,不是 id
name: activityData.name,
activityCode: generateActivityCode(), // 创建新活动时随机生成活动码
createTime: new Date().toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' }),
status: '未发布'
};
setActivityDetail(newActivityDetail);
// 为新活动设置原始数据
setOriginalData({
activityDetail: { ...newActivityDetail },
prizeList: []
});
// 清除 sessionStorage 中的数据,避免重复初始化
sessionStorage.removeItem('newActivity');
} else if (activityId) {
// 没有新活动信息,直接加载现有活动
loadActivityDetail(activityId);
}
}, []);
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 [isModified, setIsModified] = useState(false);
// 初始化原始数据,用于检测是否有修改
const [originalData, setOriginalData] = useState({});
// 初始化原始数据(在数据加载完成后设置)
const setOriginalDataFromCurrent = () => {
setOriginalData({
activityDetail: { ...activityDetail },
prizeList: [...prizeList]
});
};
// 计算修改的元素数量
const getModifiedCount = () => {
let count = 0;
// 检查基础信息的修改
if (originalData.activityDetail && activityDetail) {
Object.keys(originalData.activityDetail).forEach(key => {
if (JSON.stringify(originalData.activityDetail[key]) !== JSON.stringify(activityDetail[key])) {
count++;
}
});
}
// 检查奖品列表的修改
const originalPrizes = originalData.prizeList || [];
const currentPrizes = prizeList || [];
// 先检查数量变化
if (originalPrizes.length !== currentPrizes.length) {
count += Math.abs(originalPrizes.length - currentPrizes.length);
}
// 检查每个奖品的属性变化
originalPrizes.forEach((originalPrize, index) => {
if (currentPrizes[index]) {
Object.keys(originalPrize).forEach(key => {
if (JSON.stringify(originalPrize[key]) !== JSON.stringify(currentPrizes[index][key])) {
count++;
}
});
}
});
return count;
};
// 优化:避免使用 JSON.stringify 比较大对象
// 只在实际需要时才比较(用户点击保存时),或者使用更简单的比较方法
// 暂时禁用自动检查,只在用户操作时设置标记
useEffect(() => {
// 仅在页面初始化时设置一次未修改状态
}, []);
const handleSave = async () => {
try {
if (!window.H5CmsAPI) {
alert('API未加载,请刷新页面重试');
return;
}
// 获取当前登录用户信息
const currentUser = window.LoginManager?.getUserInfo();
// 只保存数据库中存在的字段,过滤掉临时字段
// 主键id由数据库自动生成UUID,activity_id存储8位随机唯一标识符用于URL
const dataToSave = {
activity_id: activityDetail.activity_id || activityDetail.activityId, // 页面创建时填写的唯一标识符
activity_code: activityDetail.activityCode,
name: activityDetail.name,
status: activityDetail.status === '已发布' ? 1 : 0,
description: activityDetail.description,
start_time: activityDetail.startTime,
end_time: activityDetail.endTime,
price: activityDetail.price,
maximum_limit: activityDetail.maximumLimit,
physical_inventory: activityDetail.physicalInventory,
share_title: activityDetail.shareTitle,
share_subtitle: activityDetail.shareSubtitle,
share_thumbnail: activityDetail.shareThumbnail,
is_invitation: activityDetail.isInvitation,