-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1229 lines (1054 loc) · 61.3 KB
/
Copy pathscript.js
File metadata and controls
1229 lines (1054 loc) · 61.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// DOM Elements
const mainTitle = document.getElementById('main-title');
const settingsSection = document.getElementById('settings-section');
const lotterySection = document.getElementById('lottery-section');
const sheetUrlInput = document.getElementById('sheet-url');
const sheetNameInput = document.getElementById('sheet-name');
const columnLetterInput = document.getElementById('column-letter');
const csvUrlInput = document.getElementById('csv-url-input');
const csvColumnLetterInput = document.getElementById('csv-column-letter');
const customListInput = document.getElementById('custom-list');
const prizesContainer = document.getElementById('prizes-container');
const addPrizeBtn = document.getElementById('add-prize-btn');
const clearPrizesBtn = document.getElementById('clear-prizes-btn');
const templateNameInput = document.getElementById('template-name-input');
const saveTemplateBtn = document.getElementById('save-template-btn');
const templateButtonsContainer = document.getElementById('template-buttons-container');
const themeSelector = document.getElementById('theme-selector');
const loadButton = document.getElementById('load-button');
const drawButton = document.getElementById('draw-button');
const exportCsvBtn = document.getElementById('export-csv-btn');
const statusMessage = document.getElementById('status-message');
const participantLabel = document.getElementById('participant-label');
const participantCountSpan = document.getElementById('participant-count');
const currentPrizeDisplay = document.getElementById('current-prize-display');
const winnerDisplay = document.getElementById('winner-display');
const winnersListContainer = document.getElementById('winners-list-container');
const mainDrawPanel = document.getElementById('main-draw-panel');
const winnersList = document.getElementById('winners-list');
const soundToggleBtn = document.getElementById('sound-toggle-btn');
const resetBtn = document.getElementById('reset-btn');
const tabCloudBtn = document.getElementById('tab-cloud');
const tabCustomBtn = document.getElementById('tab-custom');
const tabCsvBtn = document.getElementById('tab-csv');
const tabExcludeBtn = document.getElementById('tab-exclude');
const tabContentCloud = document.getElementById('tab-content-cloud');
const tabContentCustom = document.getElementById('tab-content-custom');
const tabContentCsv = document.getElementById('tab-content-csv');
const tabContentExclude = document.getElementById('tab-content-exclude');
// Title Tab Elements
const titleInput = document.getElementById('title-input');
const titleTemplateNameInput = document.getElementById('title-template-name-input');
const saveTitleTemplateBtn = document.getElementById('save-title-template-btn');
const titleTemplateButtonsContainer = document.getElementById('title-template-buttons-container');
// List Tab Elements
const listTemplateNameInput = document.getElementById('list-template-name-input');
const saveListTemplateBtn = document.getElementById('save-list-template-btn');
const listTemplateButtonsContainer = document.getElementById('list-template-buttons-container');
// Exclude Tab Elements
const excludeListInput = document.getElementById('exclude-list');
const excludeTemplateNameInput = document.getElementById('exclude-template-name-input');
const saveExcludeTemplateBtn = document.getElementById('save-exclude-template-btn');
const excludeTemplateButtonsContainer = document.getElementById('exclude-template-buttons-container');
// Environment Tabs
const tabModeBtn = document.getElementById('tab-mode');
const tabTitleBtn = document.getElementById('tab-title');
const tabPrizeBtn = document.getElementById('tab-prize');
const tabThemeBtn = document.getElementById('tab-theme');
const tabVisualBtn = document.getElementById('tab-visual');
const tabSoundBtn = document.getElementById('tab-sound');
const tabEffectBtn = document.getElementById('tab-effect');
const tabContentMode = document.getElementById('tab-content-mode');
const tabContentTitle = document.getElementById('tab-content-title');
const tabContentPrize = document.getElementById('tab-content-prize');
const tabContentTheme = document.getElementById('tab-content-theme');
const tabContentVisual = document.getElementById('tab-content-visual');
const tabContentSound = document.getElementById('tab-content-sound');
const tabContentEffect = document.getElementById('tab-content-effect');
// Visual Customization Elements
const logoImg = document.getElementById('logo-img');
const logoUpload = document.getElementById('logo-upload');
const bgUpload = document.getElementById('bg-upload');
const resetLogoBtn = document.getElementById('reset-logo-btn');
const resetBgBtn = document.getElementById('reset-bg-btn');
const appBgOverlay = document.getElementById('app-bg-overlay');
// Mode Settings Toggle
const simpleDrawToggle = document.getElementById('simple-draw-toggle');
const batchDrawToggle = document.getElementById('batch-draw-toggle');
const filterDuplicatesToggle = document.getElementById('filter-duplicates-toggle');
const sortWinnersToggle = document.getElementById('sort-winners-toggle');
const sortWinnersBtn = document.getElementById('sort-winners-btn');
// Batch Drawing Elements
const batchSizeInput = document.getElementById('batch-size-input');
const batchSettingsContainer = document.getElementById('batch-settings');
const rollingSound = document.getElementById('rolling-sound');
const winnerSound = document.getElementById('winner-sound');
const winnerEffectSelect = document.getElementById('winner-effect-select');
// Duplicates Modal Elements
const duplicatesModal = document.getElementById('duplicates-modal');
const duplicatesList = document.getElementById('duplicates-list');
const dupDeleteAllBtn = document.getElementById('dup-delete-all-btn');
const dupKeepOneBtn = document.getElementById('dup-keep-one-btn');
const dupCancelBtn = document.getElementById('dup-cancel-btn');
// Column Selection Modal Elements
const columnSelectionModal = document.getElementById('column-selection-modal');
const columnSelectionContainer = document.getElementById('column-selection-container');
const confirmColumnSelectionBtn = document.getElementById('confirm-column-selection-btn');
const cancelColumnSelectionBtn = document.getElementById('cancel-column-selection-btn');
// Recovery Modal Elements
const recoveryModal = document.getElementById('recovery-modal');
const resumeSessionBtn = document.getElementById('resume-session-btn');
const downloadSessionBtn = document.getElementById('download-session-btn');
const discardSessionBtn = document.getElementById('discard-session-btn');
// Bonus Prize Elements
const bonusModal = document.getElementById('bonus-modal');
const bonusPrizeName = document.getElementById('bonus-prize-name');
const bonusPrizeQuantity = document.getElementById('bonus-prize-quantity');
const bonusRemainingCount = document.getElementById('bonus-remaining-count');
const confirmBonusBtn = document.getElementById('confirm-bonus-btn');
const cancelBonusBtn = document.getElementById('cancel-bonus-btn');
// State
let participants = [];
let pendingParticipants = [];
let pendingLoadedData = null; // Temp storage for loaded data awaiting column selection
let prizes = [];
let currentPrizeIndex = 0;
let rollingInterval = null;
let activeDataSource = 'custom';
let isSoundOn = true;
const themes = [ { id: 'candy', name: '糖果王國', colors: ['#ff69b4', '#87ceeb'] }, { id: 'forest', name: '森林夥伴', colors: ['#228b22', '#ff7f50'] }, { id: 'izakaya', name: '居酒屋', colors: ['#e53e3e', '#ffab00'] }, { id: 'sakura', name: '櫻花', colors: ['#db2777', '#fdf2f8'] }, { id: 'midnight', name: '午夜', colors: ['#38bdf8', '#0f172a'] } ];
const buttonPhrases = [ '獎落誰家?就是你家!', '帶回就是福氣', '抽中就是緣分', '好運滾滾來', '表單一定要填' ];
function init() {
// Main Actions
loadButton.addEventListener('click', handleLoadData);
drawButton.addEventListener('click', handleDrawWinner);
resetBtn.addEventListener('click', () => {
if (confirm('您確定要重置活動嗎?這將會清除目前的進度與所有名單。')) {
resetApp();
}
});
// Modals & Links
exportCsvBtn.addEventListener('click', exportResultsToCsv);
// List Setup Tabs
tabCustomBtn.addEventListener('click', () => switchTab('custom'));
tabCloudBtn.addEventListener('click', () => switchTab('cloud'));
tabCsvBtn.addEventListener('click', () => switchTab('csv'));
tabExcludeBtn.addEventListener('click', () => switchTab('exclude'));
saveListTemplateBtn.addEventListener('click', saveListTemplate);
saveExcludeTemplateBtn.addEventListener('click', saveExcludeTemplate);
// Environment Tabs
tabModeBtn.addEventListener('click', () => switchEnvTab('mode'));
tabTitleBtn.addEventListener('click', () => switchEnvTab('title'));
tabPrizeBtn.addEventListener('click', () => switchEnvTab('prize'));
tabThemeBtn.addEventListener('click', () => switchEnvTab('theme'));
tabVisualBtn.addEventListener('click', () => switchEnvTab('visual'));
tabSoundBtn.addEventListener('click', () => switchEnvTab('sound'));
tabEffectBtn.addEventListener('click', () => switchEnvTab('effect'));
// Visual Customization Actions
logoUpload.addEventListener('change', (e) => handleImageUpload(e, 'customLogo'));
bgUpload.addEventListener('change', (e) => handleImageUpload(e, 'customBg'));
resetLogoBtn.addEventListener('click', () => {
localStorage.removeItem('customLogo');
logoUpload.value = "";
loadVisuals();
});
resetBgBtn.addEventListener('click', () => {
localStorage.removeItem('customBg');
bgUpload.value = "";
loadVisuals();
});
// Title Setup
titleInput.addEventListener('input', (e) => {
const newTitle = e.target.value.trim();
mainTitle.textContent = newTitle || 'ㄚ亮笑長的抽抽樂';
document.title = newTitle || 'ㄚ亮笑長的抽抽樂';
});
saveTitleTemplateBtn.addEventListener('click', saveTitleTemplate);
// Prize Setup
addPrizeBtn.addEventListener('click', () => addPrizeRow());
saveTemplateBtn.addEventListener('click', savePrizeTemplate);
clearPrizesBtn.addEventListener('click', clearPrizes);
// Bonus Prize Actions (Hidden trigger on participant count)
participantCountSpan.addEventListener('click', () => {
bonusRemainingCount.textContent = participants.length;
bonusPrizeName.value = '';
bonusPrizeQuantity.value = 1;
bonusModal.classList.remove('hidden');
});
cancelBonusBtn.addEventListener('click', () => {
bonusModal.classList.add('hidden');
});
confirmBonusBtn.addEventListener('click', handleAddBonusPrize);
// Other settings
soundToggleBtn.addEventListener('click', toggleSound);
simpleDrawToggle.addEventListener('change', handleSimpleDrawToggle);
// Batch drawing toggle
batchDrawToggle.addEventListener('change', (e) => {
const isEnabled = e.target.checked;
batchSettingsContainer.classList.toggle('hidden', !isEnabled);
localStorage.setItem('batchDrawEnabled', isEnabled);
});
filterDuplicatesToggle.addEventListener('change', (e) => {
localStorage.setItem('filterDuplicates', e.target.checked);
});
// Sort Winners Toggle
sortWinnersToggle.addEventListener('change', (e) => {
localStorage.setItem('sortWinnersEnabled', e.target.checked);
updateWinnersList(true); // Refresh list to show/hide button
});
// Manual Sort Button
sortWinnersBtn.addEventListener('click', () => {
updateWinnersList(true); // Force sort
});
// Duplicate Modal Actions
dupDeleteAllBtn.addEventListener('click', () => handleDuplicateAction('deleteAll'));
dupKeepOneBtn.addEventListener('click', () => handleDuplicateAction('keepOne'));
dupCancelBtn.addEventListener('click', () => {
duplicatesModal.classList.add('hidden');
loadButton.disabled = false;
updateStatus('載入已取消。');
});
// Column Selection Modal Actions
confirmColumnSelectionBtn.addEventListener('click', handleColumnSelectionConfirmed);
cancelColumnSelectionBtn.addEventListener('click', () => {
columnSelectionModal.classList.add('hidden');
loadButton.disabled = false;
updateStatus('載入已取消。');
pendingLoadedData = null;
});
// Recovery Modal Actions
resumeSessionBtn.addEventListener('click', loadSession);
downloadSessionBtn.addEventListener('click', exportCurrentSessionToCsv);
discardSessionBtn.addEventListener('click', clearSession);
// Initial Load
addPrizeRow('三獎', 3);
addPrizeRow('二獎', 2);
addPrizeRow('頭獎', 1);
setupThemes();
loadTheme();
loadVisuals();
renderSavedTemplates();
renderSavedTitleTemplates();
renderSavedListTemplates();
renderSavedExcludeTemplates();
switchTab(activeDataSource);
switchEnvTab('mode');
handleUrlParams();
// Restore mode settings
const savedSimpleMode = localStorage.getItem('simpleDrawMode') === 'true';
simpleDrawToggle.checked = savedSimpleMode;
if (savedSimpleMode) tabPrizeBtn.classList.add('hidden');
const savedBatchEnabled = localStorage.getItem('batchDrawEnabled') === 'true';
batchDrawToggle.checked = savedBatchEnabled;
batchSettingsContainer.classList.toggle('hidden', !savedBatchEnabled);
const savedFilter = localStorage.getItem('filterDuplicates') === 'true';
filterDuplicatesToggle.checked = savedFilter;
const savedSort = localStorage.getItem('sortWinnersEnabled') === 'true';
sortWinnersToggle.checked = savedSort;
// Check for existing session
const savedSession = localStorage.getItem('lottery_session');
if (savedSession) {
recoveryModal.classList.remove('hidden');
}
window.addEventListener('resize', () => { if (document.getElementById('finished-prize-name')) { adjustPrizeNameFontSize(); } });
};
function handleAddBonusPrize() {
const name = bonusPrizeName.value.trim();
const quantity = parseInt(bonusPrizeQuantity.value, 10);
if (!name) {
alert('請輸入獎項名稱!');
return;
}
if (isNaN(quantity) || quantity <= 0) {
alert('請輸入有效的數量!');
return;
}
if (quantity > participants.length) {
alert(`剩餘人數不足!目前僅剩 ${participants.length} 人。`);
return;
}
const newPrize = { name, quantity, winners: [] };
prizes.push(newPrize);
// Check if we need to reset the completed state
// If the button says "Reset" or "Finished", we need to wake it up
// updatePrizeDisplay will handle finding the next available prize (which is this new one)
updatePrizeDisplay();
saveSession();
bonusModal.classList.add('hidden');
// Explicitly update status to show something happened
updateStatus(`已加碼:${name} (${quantity}名)`);
}
// --- VISUAL CUSTOMIZATION FUNCTIONS ---
function handleImageUpload(event, storageKey) {
const file = event.target.files[0];
if (!file) return;
if (file.size > 2 * 1024 * 1024) { alert('圖片太大囉!請上傳小於 2MB 的圖片。'); return; }
const reader = new FileReader();
reader.onload = (e) => {
localStorage.setItem(storageKey, e.target.result);
loadVisuals();
};
reader.readAsDataURL(file);
}
function loadVisuals() {
const customLogo = localStorage.getItem('customLogo');
if (customLogo) {
logoImg.src = customLogo;
logoImg.style.visibility = 'visible';
} else {
logoImg.src = "Logo.png";
}
const customBg = localStorage.getItem('customBg');
if (customBg) {
appBgOverlay.style.backgroundImage = `url(${customBg})`;
appBgOverlay.style.opacity = '1';
} else {
appBgOverlay.style.backgroundImage = 'none';
appBgOverlay.style.opacity = '0';
}
}
// --- SESSION RECOVERY FUNCTIONS ---
function saveSession() {
const sessionData = {
participants,
prizes,
currentPrizeIndex,
simpleDrawMode: simpleDrawToggle.checked,
batchDrawEnabled: batchDrawToggle.checked,
sortWinnersEnabled: sortWinnersToggle.checked,
title: mainTitle.textContent
};
localStorage.setItem('lottery_session', JSON.stringify(sessionData));
}
function loadSession() {
const savedSession = localStorage.getItem('lottery_session');
if (!savedSession) return;
try {
const data = JSON.parse(savedSession);
participants = data.participants;
prizes = data.prizes;
currentPrizeIndex = data.currentPrizeIndex;
simpleDrawToggle.checked = data.simpleDrawMode;
batchDrawToggle.checked = data.batchDrawEnabled || false;
batchSettingsContainer.classList.toggle('hidden', !batchDrawToggle.checked);
// Restore sort setting from session if available, else fallback to localStorage
if (data.sortWinnersEnabled !== undefined) {
sortWinnersToggle.checked = data.sortWinnersEnabled;
} else {
sortWinnersToggle.checked = localStorage.getItem('sortWinnersEnabled') === 'true';
}
mainTitle.textContent = data.title;
document.title = data.title;
recoveryModal.classList.add('hidden');
switchToLotteryView();
// Force sort on session load if enabled to ensure consistent state
updateWinnersList(sortWinnersToggle.checked);
updateStatus('進度已恢復。');
} catch (e) {
console.error("恢復進度失敗:", e);
clearSession();
}
}
function clearSession() {
localStorage.removeItem('lottery_session');
recoveryModal.classList.add('hidden');
}
function exportCurrentSessionToCsv() {
const savedSession = localStorage.getItem('lottery_session');
if (!savedSession) return;
const data = JSON.parse(savedSession);
const sParticipants = data.participants || [];
const sPrizes = data.prizes || [];
const sTitle = data.title || "抽獎活動";
let totalWinnersCount = 0;
sPrizes.forEach(p => totalWinnersCount += (p.winners ? p.winners.length : 0));
const totalPeople = sParticipants.length + totalWinnersCount;
let csvContent = '\uFEFF"抽獎進度報表","' + sTitle + '"\n';
csvContent += '"摸彩總人數",' + totalPeople + '\n';
csvContent += '"已中獎人數",' + totalWinnersCount + '\n';
csvContent += '"未中獎人數",' + sParticipants.length + '\n\n';
csvContent += '"獎項","得獎人姓名","是否已領獎"\n';
sPrizes.forEach(prize => {
if (prize.winners) {
prize.winners.forEach(winner => {
const prizeName = prize.name.replace(/"/g, '""');
const winnerName = winner.name.replace(/"/g, '""');
const claimed = winner.claimed ? "是" : "否";
csvContent += `"${prizeName}","${winnerName}","${claimed}"\n`;
});
}
});
csvContent += '\n"未抽獎人員名單"\n';
sParticipants.forEach(name => {
csvContent += `"${name.replace(/"/g, '""')}"\n`;
});
const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
const link = document.createElement("a");
const url = URL.createObjectURL(blob);
link.setAttribute("href", url);
const today = new Date();
const fileName = `進度備份-${sTitle}-${today.getFullYear()}${String(today.getMonth()+1).padStart(2,'0')}${String(today.getDate()).padStart(2,'0')}.csv`;
link.setAttribute("download", fileName);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
// --- TEMPLATE FUNCTIONS ---
const getListTemplates = () => JSON.parse(localStorage.getItem('listTemplates') || '{}');
const saveListTemplates = (templates) => localStorage.setItem('listTemplates', JSON.stringify(templates));
function saveListTemplate() { const name = listTemplateNameInput.value.trim(); const listContent = customListInput.value.trim(); if (!name || !listContent) { alert('範本名稱和名單內容都不能為空!'); return; } const templates = getListTemplates(); templates[name] = listContent; saveListTemplates(templates); listTemplateNameInput.value = ''; renderSavedListTemplates(); }
function loadListTemplate(name) { const templates = getListTemplates(); const listContent = templates[name]; if (listContent) { customListInput.value = listContent; } }
function deleteListTemplate(name) { const templates = getListTemplates(); delete templates[name]; saveListTemplates(templates); renderSavedListTemplates(); }
function renderSavedListTemplates() { const templates = getListTemplates(); listTemplateButtonsContainer.innerHTML = ''; for (const name in templates) { const container = document.createElement('div'); container.className = 'custom-template flex items-center rounded-lg'; container.style.backgroundColor = 'var(--secondary-color)'; const button = document.createElement('button'); button.textContent = name; button.className = 'px-4 py-2 text-sm'; button.addEventListener('click', () => loadListTemplate(name)); const deleteBtn = document.createElement('button'); deleteBtn.textContent = '✕'; deleteBtn.className = 'px-2 py-2 text-sm'; deleteBtn.style.color = 'var(--danger-color)'; deleteBtn.addEventListener('click', (e) => { e.stopPropagation(); deleteListTemplate(name); }); container.appendChild(button); container.appendChild(deleteBtn); listTemplateButtonsContainer.appendChild(container); } }
const getExcludeTemplates = () => JSON.parse(localStorage.getItem('excludeTemplates') || '{}');
const saveExcludeTemplates = (templates) => localStorage.setItem('excludeTemplates', JSON.stringify(templates));
function saveExcludeTemplate() { const name = excludeTemplateNameInput.value.trim(); const listContent = excludeListInput.value.trim(); if (!name || !listContent) { alert('範本名稱和排除名單都不能為空!'); return; } const templates = getExcludeTemplates(); templates[name] = listContent; saveExcludeTemplates(templates); excludeTemplateNameInput.value = ''; renderSavedExcludeTemplates(); }
function loadExcludeTemplate(name) { const templates = getExcludeTemplates(); const listContent = templates[name]; if (listContent) { excludeListInput.value = listContent; } }
function deleteExcludeTemplate(name) { const templates = getExcludeTemplates(); delete templates[name]; saveExcludeTemplates(templates); renderSavedExcludeTemplates(); }
function renderSavedExcludeTemplates() { const templates = getExcludeTemplates(); excludeTemplateButtonsContainer.innerHTML = ''; for (const name in templates) { const container = document.createElement('div'); container.className = 'custom-template flex items-center rounded-lg'; container.style.backgroundColor = 'var(--secondary-color)'; const button = document.createElement('button'); button.textContent = name; button.className = 'px-4 py-2 text-sm'; button.addEventListener('click', () => loadExcludeTemplate(name)); const deleteBtn = document.createElement('button'); deleteBtn.textContent = '✕'; deleteBtn.className = 'px-2 py-2 text-sm'; deleteBtn.style.color = 'var(--danger-color)'; deleteBtn.addEventListener('click', (e) => { e.stopPropagation(); deleteExcludeTemplate(name); }); container.appendChild(button); container.appendChild(deleteBtn); excludeTemplateButtonsContainer.appendChild(container); } }
const getTitleTemplates = () => JSON.parse(localStorage.getItem('titleTemplates') || '{}');
const saveTitleTemplates = (templates) => localStorage.setItem('titleTemplates', JSON.stringify(templates));
function saveTitleTemplate() { const name = titleTemplateNameInput.value.trim(); const title = titleInput.value.trim(); if (!name || !title) { alert('範本名稱和活動標題都不能為空!'); return; } const templates = getTitleTemplates(); templates[name] = title; saveTitleTemplates(templates); titleTemplateNameInput.value = ''; renderSavedTitleTemplates(); }
function loadTitleTemplate(name) { const templates = getTitleTemplates(); const title = templates[name]; if (title) { titleInput.value = title; titleInput.dispatchEvent(new Event('input')); } }
function deleteTitleTemplate(name) { const templates = getTitleTemplates(); delete templates[name]; saveTitleTemplates(templates); renderSavedTitleTemplates(); }
function renderSavedTitleTemplates() { const templates = getTitleTemplates(); titleTemplateButtonsContainer.innerHTML = ''; for (const name in templates) { const container = document.createElement('div'); container.className = 'custom-template flex items-center rounded-lg'; container.style.backgroundColor = 'var(--secondary-color)'; const button = document.createElement('button'); button.textContent = name; button.className = 'px-4 py-2 text-sm'; button.addEventListener('click', () => loadTitleTemplate(name)); const deleteBtn = document.createElement('button'); deleteBtn.textContent = '✕'; deleteBtn.className = 'px-2 py-2 text-sm'; deleteBtn.style.color = 'var(--danger-color)'; deleteBtn.addEventListener('click', (e) => { e.stopPropagation(); deleteTitleTemplate(name); }); container.appendChild(button); container.appendChild(deleteBtn); titleTemplateButtonsContainer.appendChild(container); } }
const getPrizeTemplates = () => JSON.parse(localStorage.getItem('prizeTemplates') || '{}');
const savePrizeTemplates = (templates) => localStorage.setItem('prizeTemplates', JSON.stringify(templates));
function savePrizeTemplate() { const name = templateNameInput.value.trim(); if (!name) { alert('請為您的獎項範本命名!'); return; } const prizeRows = prizesContainer.querySelectorAll('.prize-row'); const currentPrizes = Array.from(prizeRows).map(row => ({ name: row.querySelector('.prize-name').value, quantity: row.querySelector('.prize-quantity').value })); if (currentPrizes.length === 0) { alert('沒有可儲存的獎項!'); return; } const templates = getPrizeTemplates(); templates[name] = currentPrizes; savePrizeTemplates(templates); templateNameInput.value = ''; renderSavedTemplates(); }
function loadPrizeTemplate(name) { const templates = getPrizeTemplates(); const template = templates[name]; if (template) { clearPrizes(); template.forEach(prize => addPrizeRow(prize.name, prize.quantity)); } }
function deletePrizeTemplate(name) { const templates = getPrizeTemplates(); delete templates[name]; savePrizeTemplates(templates); renderSavedTemplates(); }
function renderSavedTemplates() { const templates = getPrizeTemplates(); templateButtonsContainer.innerHTML = ''; for (const name in templates) { const container = document.createElement('div'); container.className = 'custom-template flex items-center rounded-lg'; container.style.backgroundColor = 'var(--secondary-color)'; const button = document.createElement('button'); button.textContent = name; button.className = 'px-4 py-2 text-sm'; button.addEventListener('click', () => loadPrizeTemplate(name)); const deleteBtn = document.createElement('button'); deleteBtn.textContent = '✕'; deleteBtn.className = 'px-2 py-2 text-sm'; deleteBtn.style.color = 'var(--danger-color)'; deleteBtn.addEventListener('click', (e) => { e.stopPropagation(); deletePrizeTemplate(name); }); container.appendChild(button); container.appendChild(deleteBtn); templateButtonsContainer.appendChild(container); } }
// --- CORE LOGIC FUNCTIONS ---
const playTenseMusic = () => { if (!isSoundOn) return; rollingSound.currentTime = 0; const playPromise = rollingSound.play(); if (playPromise !== undefined) { playPromise.catch(error => console.error("Error playing rolling sound:", error)); } };
const stopTenseMusic = () => { rollingSound.pause(); rollingSound.currentTime = 0; };
const playWinnerSound = () => { if (!isSoundOn) return; winnerSound.currentTime = 0; const playPromise = winnerSound.play(); if (playPromise !== undefined) { playPromise.catch(error => console.error("Error playing winner sound:", error)); } };
const toggleSound = () => { isSoundOn = !isSoundOn; soundToggleBtn.textContent = isSoundOn ? '🔊' : '🔇'; if(!isSoundOn) { stopTenseMusic(); } };
function switchTab(tabName) {
activeDataSource = tabName;
const tabs = {
custom: { btn: tabCustomBtn, content: tabContentCustom },
cloud: { btn: tabCloudBtn, content: tabContentCloud },
csv: { btn: tabCsvBtn, content: tabContentCsv },
exclude: { btn: tabExcludeBtn, content: tabContentExclude }
};
Object.values(tabs).forEach(tab => {
tab.btn.classList.remove('active');
tab.content.classList.add('hidden');
});
tabs[tabName].btn.classList.add('active');
tabs[tabName].content.classList.remove('hidden');
}
function switchEnvTab(tabName) { const tabs = { mode: { btn: tabModeBtn, content: tabContentMode }, title: { btn: tabTitleBtn, content: tabContentTitle }, prize: { btn: tabPrizeBtn, content: tabContentPrize }, theme: { btn: tabThemeBtn, content: tabContentTheme }, visual: { btn: tabVisualBtn, content: tabContentVisual }, sound: { btn: tabSoundBtn, content: tabContentSound }, effect: { btn: tabEffectBtn, content: tabContentEffect } }; Object.values(tabs).forEach(tab => { tab.btn.classList.remove('active'); tab.content.classList.add('hidden'); }); tabs[tabName].btn.classList.add('active'); tabs[tabName].content.classList.remove('hidden'); }
function handleSimpleDrawToggle(e) { const isEnabled = e.target.checked; if (isEnabled) { tabPrizeBtn.classList.add('hidden'); if (tabPrizeBtn.classList.contains('active')) { switchEnvTab('mode'); } } else { tabPrizeBtn.classList.remove('hidden'); } localStorage.setItem('simpleDrawMode', isEnabled); }
function addPrizeRow(name = '', quantity = 1) { const row = document.createElement('div'); row.className = 'prize-row flex items-center gap-2'; row.innerHTML = ` <input type="text" class="prize-name form-input w-full p-2 rounded" value="${name}" placeholder="獎項名稱"> <input type="number" class="prize-quantity form-input w-24 p-2 rounded" value="${quantity}" min="1" placeholder="數量"> <button class="remove-prize-btn btn-secondary px-3 py-2 rounded" style="color: var(--danger-color);">✕</button> `; prizesContainer.appendChild(row); row.querySelector('.remove-prize-btn').addEventListener('click', () => row.remove()); }
const clearPrizes = () => { prizesContainer.innerHTML = ''; };
function handleUrlParams() { const params = new URLSearchParams(window.location.search); if (params.has('sheetUrl') && params.has('sheetName') && params.has('column')) { sheetUrlInput.value = params.get('sheetUrl'); sheetNameInput.value = params.get('sheetName'); columnLetterInput.value = params.get('column'); handleLoadData(); } }
function readAndValidatePrizes() { prizes = []; const isSimpleMode = simpleDrawToggle.checked; if (isSimpleMode) { return true; } const prizeRows = prizesContainer.querySelectorAll('.prize-row'); if (prizeRows.length === 0) { return true; } let totalPrizeQuantity = 0; for (const row of prizeRows) { const name = row.querySelector('.prize-name').value.trim(); const quantity = parseInt(row.querySelector('.prize-quantity').value, 10); if (!name) { updateStatus('獎項名稱不可為空!', true); return false; } if (isNaN(quantity) || quantity < 1) { updateStatus(`獎項「${name}」的數量必須是正整數!`, true); return false; } prizes.push({ name, quantity, winners: [] }); totalPrizeQuantity += quantity; } if (participants.length > 0 && totalPrizeQuantity > participants.length) { updateStatus(`警告:獎項總數 (${totalPrizeQuantity}) 大於參與人數 (${participants.length})!`, true); } return true; }
async function handleLoadData() {
loadButton.disabled = true;
updateStatus('正在處理名單...');
if (activeDataSource === 'cloud') {
await loadFromCloud();
} else if (activeDataSource === 'csv') {
await loadFromPublishedCsv();
} else {
loadFromCustomInput();
}
}
function showColumnSelectionModal(headers, nameColIndex) {
columnSelectionContainer.innerHTML = '';
const checkboxIdPrefix = activeDataSource === 'cloud' ? 'cloud-smart-filter' : 'csv-smart-filter';
const smartFilterEnabled = document.getElementById(checkboxIdPrefix) ? document.getElementById(checkboxIdPrefix).checked : true;
if (!smartFilterEnabled) {
handleColumnSelectionConfirmed([]);
return;
}
const keywords = /phone|mobile|tel|cell|手機|電話|email|mail|信箱|id|編號|學號|工號|身分證|uid/i;
let hasOptions = false;
headers.forEach((header, index) => {
if (index === nameColIndex) return;
hasOptions = true;
const wrapper = document.createElement('div');
wrapper.className = 'flex items-center p-2 rounded hover:bg-white/10';
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.id = `col-select-${index}`;
checkbox.value = index;
checkbox.className = 'form-checkbox h-5 w-5 text-red-500 rounded focus:ring-0';
if (keywords.test(header)) {
checkbox.checked = true;
}
const label = document.createElement('label');
label.htmlFor = `col-select-${index}`;
label.className = 'ml-3 cursor-pointer select-none flex-grow text-lg';
label.textContent = header || `(無標題 - 第${index+1}欄)`;
wrapper.appendChild(checkbox);
wrapper.appendChild(label);
columnSelectionContainer.appendChild(wrapper);
});
if (!hasOptions) {
handleColumnSelectionConfirmed([]);
return;
}
columnSelectionModal.classList.remove('hidden');
}
function handleColumnSelectionConfirmed(preSelectedIndices = null) {
let selectedIndices = [];
if (Array.isArray(preSelectedIndices)) {
selectedIndices = preSelectedIndices;
} else {
const checkboxes = columnSelectionContainer.querySelectorAll('input[type="checkbox"]:checked');
checkboxes.forEach(cb => selectedIndices.push(parseInt(cb.value)));
columnSelectionModal.classList.add('hidden');
}
if (!pendingLoadedData) return;
const { rows, nameColIndex } = pendingLoadedData;
const rawList = rows.map((row, index) => {
if (index === 0) return null; // Skip header
const name = row[nameColIndex];
if (!name) return null;
const smartValues = selectedIndices.map(idx => row[idx] ? row[idx].trim().replace(/\D/g, '') : '').filter(v => v !== '');
return { name, smartValues, originalRow: row };
}).filter(item => item !== null);
finalizeDataLoading(rawList);
pendingLoadedData = null; // Clean up
}
function parseCSV(text) {
const rows = [];
let currentRow = [];
let currentCell = '';
let inQuotes = false;
for (let i = 0; i < text.length; i++) {
const char = text[i];
const nextChar = text[i + 1];
if (inQuotes) {
if (char === '"' && nextChar === '"') { currentCell += '"'; i++; }
else if (char === '"') { inQuotes = false; }
else { currentCell += char; }
} else {
if (char === '"') { inQuotes = true; }
else if (char === ',') { currentRow.push(currentCell.trim()); currentCell = ''; }
else if (char === '\n' || char === '\r') {
if (currentCell || currentRow.length > 0) { currentRow.push(currentCell.trim()); rows.push(currentRow); }
currentRow = []; currentCell = '';
if (char === '\r' && nextChar === '\n') i++;
} else { currentCell += char; }
}
}
if (currentCell || currentRow.length > 0) { currentRow.push(currentCell.trim()); rows.push(currentRow); }
return rows;
}
async function loadFromCloud() {
const sheetUrl = sheetUrlInput.value.trim();
const sheetName = sheetNameInput.value.trim();
const columnLetter = columnLetterInput.value.trim().toUpperCase();
if (!sheetUrl) { updateStatus('請輸入 Google 試算表「共用」網址!', true); loadButton.disabled = false; return; }
const sheetIdMatch = sheetUrl.match(/spreadsheets\/d\/([a-zA-Z0-9-_]+)/);
if (!sheetIdMatch || !sheetIdMatch[1]) { updateStatus('無法從「共用」網址中解析出試算表 ID,請確認網址是否正確。', true); loadButton.disabled = false; return; }
const sheetId = sheetIdMatch[1];
updateStatus('正在從雲端讀取名單...');
try {
const timestamp = new Date().getTime();
const csvUrl = `https://docs.google.com/spreadsheets/d/${sheetId}/gviz/tq?tqx=out:csv&sheet=${encodeURIComponent(sheetName)}&_=${timestamp}`;
const proxyUrl = `https://api.allorigins.win/raw?url=${encodeURIComponent(csvUrl)}`;
const response = await fetch(proxyUrl);
if (!response.ok) throw new Error(`網路回應錯誤: ${response.statusText}`);
const csvText = await response.text();
const rows = parseCSV(csvText);
if (rows.length === 0) throw new Error("CSV 資料為空");
const headers = rows[0];
const nameColIndex = columnLetter.charCodeAt(0) - 'A'.charCodeAt(0);
pendingLoadedData = { rows, nameColIndex };
showColumnSelectionModal(headers, nameColIndex);
} catch (error) {
console.error('讀取共用連結時發生錯誤:', error);
updateStatus('讀取失敗!請檢查網址是否正確,以及網路連線。', true);
loadButton.disabled = false;
}
}
async function loadFromPublishedCsv() {
const url = csvUrlInput.value.trim();
if (!url) { updateStatus('請輸入「發布到網路」的 CSV 網址!', true); loadButton.disabled = false; return; }
if (!url.includes('/pub?gid=') || !url.includes('output=csv')) { updateStatus('網址格式錯誤!請確認是「發布到網路」並選擇 CSV 格式的網址。', true); loadButton.disabled = false; return; }
const columnLetter = csvColumnLetterInput.value.trim().toUpperCase();
const nameColIndex = columnLetter.charCodeAt(0) - 'A'.charCodeAt(0);
updateStatus(`正在從發布的連結讀取名單 (${columnLetter}欄)...`);
try {
const response = await fetch(url);
if (!response.ok) throw new Error(`網路回應錯誤: ${response.statusText}`);
const csvText = await response.text();
const rows = parseCSV(csvText);
if (rows.length === 0) throw new Error("CSV 資料為空");
const headers = rows[0];
pendingLoadedData = { rows, nameColIndex };
showColumnSelectionModal(headers, nameColIndex);
} catch (error) {
console.error('讀取發布的 CSV 時發生錯誤:', error);
updateStatus('讀取失敗!請檢查網址是否正確,以及網路連線。', true);
loadButton.disabled = false;
}
}
function finalizeDataLoading(rawList) {
const excludeRaw = excludeListInput.value;
const excludeNamesArr = excludeRaw.split(/[,,\n]+/ ).map(name => name.trim()).filter(name => name.length > 0);
const excludeNames = new Set(excludeNamesArr);
let activeList = rawList.filter(item => !excludeNames.has(item.name));
const nameGroups = {};
activeList.forEach(item => {
if (!nameGroups[item.name]) nameGroups[item.name] = [];
nameGroups[item.name].push(item);
});
const processedList = [];
Object.keys(nameGroups).forEach(name => {
const group = nameGroups[name];
const clusters = [];
group.forEach(item => {
let matchedClusterIndex = -1;
for (let i = 0; i < clusters.length; i++) {
const cluster = clusters[i];
const representative = cluster[0];
const hasIntersection = item.smartValues.some(v => v && representative.smartValues.includes(v));
const bothEmpty = item.smartValues.length === 0 && representative.smartValues.length === 0;
if (hasIntersection || bothEmpty) {
matchedClusterIndex = i;
break;
}
}
if (matchedClusterIndex !== -1) {
clusters[matchedClusterIndex].push(item);
} else {
clusters.push([item]);
}
});
clusters.forEach((cluster, index) => {
const uniqueKey = `${name}_${index}`;
let bestSuffix = '';
const allValues = new Set(cluster.flatMap(i => i.smartValues));
for (const v of allValues) {
if (v.includes('@')) { bestSuffix = v.split('@')[0]; break; }
}
if (!bestSuffix) {
for (const v of allValues) {
if (/\d{4,}/.test(v)) { bestSuffix = v.slice(-4); break; }
}
}
if (!bestSuffix && allValues.size > 0) bestSuffix = [...allValues][0];
cluster.forEach(item => {
item.uniqueKey = uniqueKey;
item.displaySuffix = bestSuffix;
processedList.push(item);
});
});
});
pendingParticipants = processedList;
if (filterDuplicatesToggle.checked) {
const counts = {};
pendingParticipants.forEach(item => { counts[item.uniqueKey] = (counts[item.uniqueKey] || 0) + 1; });
const duplicateKeys = new Set(Object.entries(counts).filter(([k, v]) => v > 1).map(([k]) => k));
if (duplicateKeys.size > 0) {
const duplicatesToDisplay = [];
duplicateKeys.forEach(key => {
const item = pendingParticipants.find(i => i.uniqueKey === key);
const displayName = item.displaySuffix ? `${item.name} (${item.displaySuffix})` : item.name;
duplicatesToDisplay.push([displayName, counts[key]]);
});
showDuplicatesModal(duplicatesToDisplay);
return;
}
}
resolveNameCollisionsAndSetParticipants(pendingParticipants);
}
function resolveNameCollisionsAndSetParticipants(objList) {
const nameGroups = {};
objList.forEach(item => {
if (!nameGroups[item.name]) nameGroups[item.name] = [];
if (!nameGroups[item.name].some(existing => existing.uniqueKey === item.uniqueKey)) {
nameGroups[item.name].push(item);
}
});
const finalNames = [];
Object.values(nameGroups).forEach(group => {
if (group.length === 1) {
finalNames.push(group[0].name);
} else {
group.forEach((item, index) => {
let newName = item.name;
if (item.displaySuffix) {
newName = `${item.name} (${item.displaySuffix})`;
} else {
newName = `${item.name} (${index + 1})`;
}
finalNames.push(newName);
});
}
});
participants = finalNames;
const excludeRaw = excludeListInput.value;
const excludeNamesArr = excludeRaw.split(/[,,\n]+/ ).map(name => name.trim()).filter(name => name.length > 0);
if (participants.length > 0 && readAndValidatePrizes()) {
updateStatus(`成功載入 ${participants.length} 位參與者!` + (excludeNamesArr.length ? ` (已排除名單上的 ${excludeNamesArr.length} 人)` : ''), false);
switchToLotteryView();
} else {
if (participants.length === 0) updateStatus(`載入的名單中沒有有效的名字。`, true);
loadButton.disabled = false;
}
}
function loadFromCustomInput() {
const rawStrings = customListInput.value.split(/[,,\n]+/ ).map(name => name.trim()).filter(name => name.length > 0);
// 如果「過濾重複姓名」開關是關閉的,則允許名單內有重複人名(視作多個抽獎機會)
if (!filterDuplicatesToggle.checked) {
const excludeRaw = excludeListInput.value;
const excludeNames = new Set(excludeRaw.split(/[,,\n]+/ ).map(name => name.trim()).filter(name => name.length > 0));
participants = rawStrings.filter(name => !excludeNames.has(name));
if (participants.length > 0 && readAndValidatePrizes()) {
updateStatus(`成功載入 ${participants.length} 個抽獎名標!`, false);
switchToLotteryView();
} else {
if (participants.length === 0) updateStatus(`載入的名單中沒有有效的名字。`, true);
loadButton.disabled = false;
}
return;
}
const rawList = rawStrings.map(name => ({ name, uniqueKey: name, smartValues: [] }));
finalizeDataLoading(rawList);
}
function showDuplicatesModal(duplicates) {
duplicatesList.innerHTML = '';
duplicates.forEach(([name, count]) => {
const item = document.createElement('div');
item.className = 'duplicate-item';
item.innerHTML = `<span>${name}</span><span class="duplicate-count">${count} 次</span>`;
duplicatesList.appendChild(item);
});
duplicatesModal.classList.remove('hidden');
}
function handleDuplicateAction(action) {
const counts = {};
pendingParticipants.forEach(item => { counts[item.uniqueKey] = (counts[item.uniqueKey] || 0) + 1; });
let finalObjList = [];
if (action === 'deleteAll') {
finalObjList = pendingParticipants.filter(item => counts[item.uniqueKey] === 1);
} else if (action === 'keepOne') {
const seenKeys = new Set();
pendingParticipants.forEach(item => {
if (!seenKeys.has(item.uniqueKey)) {
seenKeys.add(item.uniqueKey);
finalObjList.push(item);
}
});
}
duplicatesModal.classList.add('hidden');
resolveNameCollisionsAndSetParticipants(finalObjList);
}
function handleDrawWinner() {
if (drawButton.textContent === '重置' || drawButton.textContent === '結束') {
if (confirm('您確定要結束本次活動並重置嗎?')) { resetApp(); }
return;
}
if (drawButton.textContent === '抽獎結束') {
winnerDisplay.textContent = '再接再厲';
currentPrizeDisplay.textContent = '感謝參與!';
drawButton.textContent = '重置';
return;
}
const currentPrize = prizes[currentPrizeIndex];
if (!currentPrize) return;
let batchSize = batchDrawToggle.checked ? (parseInt(batchSizeInput.value, 10) || 1) : 1;
const remainingInPrize = currentPrize.quantity - currentPrize.winners.length;
if (batchSize > remainingInPrize) batchSize = remainingInPrize;
if (batchSize > participants.length) batchSize = participants.length;
if (batchSize <= 0) {
currentPrizeIndex++;
updatePrizeDisplay();
if (currentPrizeIndex < prizes.length) {
setTimeout(() => {
winnerDisplay.textContent = '準備開始!';
winnerDisplay.style.fontSize = "4rem";
}, 2000);
}
return;
}
drawButton.disabled = true;
playTenseMusic();
rollingInterval = setInterval(() => {
winnerDisplay.textContent = participants[Math.floor(Math.random() * participants.length)];
}, 80);
setTimeout(() => {
clearInterval(rollingInterval);
stopTenseMusic();
const winnersThisBatch = [];
for (let i = 0; i < batchSize; i++) {
const winnerIndex = Math.floor(Math.random() * participants.length);
const winnerName = participants.splice(winnerIndex, 1)[0];
winnersThisBatch.push(winnerName);
currentPrize.winners.push({ name: winnerName, claimed: false });
}
const selectedEffect = winnerEffectSelect.value;
const revealWinners = () => {
if (batchSize === 1) {
winnerDisplay.textContent = winnersThisBatch[0];
winnerDisplay.style.fontSize = "4rem";
} else {
winnerDisplay.innerHTML = `<div class="text-2xl mb-2">恭喜得獎者:</div><div class="flex flex-wrap justify-center gap-2 text-xl">${winnersThisBatch.map(name => `<span class="px-3 py-1 rounded bg-white/20">${name}</span>`).join('')}</div>`;
winnerDisplay.style.fontSize = "1.5rem";
}
if (selectedEffect === 'spotlight') { winnerDisplay.classList.add('effect-spotlight'); }
else { winnerDisplay.classList.add('winner-reveal'); }
playWinnerSound();
launchConfetti();
updateParticipantCount();
updateWinnersList(true);
updatePrizeDisplay();
drawButton.disabled = false;
saveSession();
};
if (selectedEffect === 'marquee') {
winnerDisplay.textContent = winnersThisBatch.join(', ');
winnerDisplay.classList.add('effect-marquee');
setTimeout(revealWinners, 1200);
} else {
revealWinners();
}
}, 4000);
}
function setupThemes() {
themeSelector.innerHTML = '';
themes.forEach(theme => {
const button = document.createElement('button');
button.className = 'theme-button';
button.title = theme.name;
button.dataset.theme = theme.id;
button.style.background = `linear-gradient(45deg, ${theme.colors[0]}, ${theme.colors[1]})`;
button.addEventListener('click', () => { applyTheme(theme.id); });
themeSelector.appendChild(button);
});
}
function applyTheme(themeId) {
document.body.className = document.body.className.replace(/theme-\w+/g, '');
if (themeId !== 'izakaya') { document.body.classList.add(`theme-${themeId}`); }
localStorage.setItem('lotteryTheme', themeId);
document.querySelectorAll('.theme-button').forEach(btn => { btn.classList.toggle('active', btn.dataset.theme === themeId); });
}
function loadTheme() { const savedTheme = localStorage.getItem('lotteryTheme') || 'candy'; applyTheme(savedTheme); }
function updateStatus(message, isError = false) { statusMessage.textContent = message; statusMessage.style.color = isError ? 'var(--danger-color)' : 'var(--accent-color)'; }
function switchToLotteryView() {
settingsSection.classList.add('hidden');
lotterySection.classList.remove('hidden');
resetBtn.classList.remove('hidden');
const isSimpleMode = simpleDrawToggle.checked;
if (isSimpleMode) {
if (prizes.length === 0) { prizes = [{ name: '抽出名單', quantity: participants.length, winners: [] }]; }
participantLabel.textContent = '未中籤人數';
} else {
participantLabel.textContent = '剩餘摸彩人數';
}
updateParticipantCount(); updatePrizeDisplay(); saveSession();
}
function adjustPrizeNameFontSize() {
const nameElement = document.getElementById('finished-prize-name');
if (!nameElement) return;
const container = winnerDisplay;
let fontSize = 4;
const minFontSize = 1;
const step = 0.2;
nameElement.style.fontSize = `${fontSize}rem`;