File size: 37,989 Bytes
902108d
2a06b2a
9efb272
05b779c
90d34ea
c65e601
dd7cb5f
1335c94
05b779c
4671b30
 
 
 
05b779c
 
c65e601
 
 
f3937f7
 
 
c65e601
ef1f31f
 
19595ec
ef1f31f
19595ec
e876179
 
 
 
 
 
 
ef1f31f
19595ec
ef1f31f
19595ec
ef1f31f
e876179
f22f614
 
9841510
05b779c
 
2a06b2a
 
 
 
a377724
2a06b2a
813fe6a
 
 
 
 
47dc8a7
813fe6a
47dc8a7
 
 
 
 
 
 
 
 
 
813fe6a
2a06b2a
 
 
813fe6a
2a06b2a
813fe6a
 
4661923
813fe6a
4661923
813fe6a
4661923
 
4307a66
 
 
 
 
 
 
813fe6a
4307a66
 
4661923
 
 
 
4307a66
2a06b2a
ef1f31f
 
 
 
19595ec
ef1f31f
19595ec
71e734b
 
 
f3205c7
 
 
 
71e734b
f3205c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47dc8a7
f3205c7
 
 
 
47dc8a7
f3205c7
 
 
3c45ae0
 
 
 
749655f
3c45ae0
 
 
f3205c7
 
3c45ae0
 
 
 
 
 
 
 
 
 
 
47dc8a7
3c45ae0
47dc8a7
3c45ae0
47dc8a7
 
 
3c45ae0
 
 
 
47dc8a7
3c45ae0
47dc8a7
 
 
 
 
 
 
 
 
 
 
 
3c45ae0
47dc8a7
 
 
 
 
f3205c7
47dc8a7
f3205c7
71e734b
 
f3205c7
 
 
71e734b
 
3c45ae0
71e734b
 
 
 
ef1f31f
71e734b
ef1f31f
71e734b
ef1f31f
45e08b1
 
 
8261b7f
b2c849d
 
 
45e08b1
4f4e7f8
800c927
4f4e7f8
56698c2
e876179
 
 
 
445d61d
 
e876179
445d61d
 
e876179
445d61d
 
 
 
 
 
 
 
 
e876179
445d61d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e876179
445d61d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e876179
 
8261b7f
45e08b1
b2c849d
2a06b2a
c65e601
 
 
 
 
 
 
 
 
dd7cb5f
 
 
 
 
f3937f7
fe8f9dd
 
dd7cb5f
 
fe8f9dd
f3937f7
dd7cb5f
 
 
fe8f9dd
 
 
 
 
 
 
 
 
 
 
 
 
dd7cb5f
fe8f9dd
 
dd7cb5f
65ec15e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3deafeb
65ec15e
3deafeb
65ec15e
 
 
 
 
3deafeb
 
65ec15e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a06b2a
 
 
 
c65e601
 
 
 
 
 
 
 
 
 
 
 
f3937f7
c65e601
90d34ea
 
c65e601
e876179
c65e601
cf0186c
e876179
 
 
4953451
e876179
 
 
cf0186c
4953451
 
e876179
 
 
cf0186c
4953451
 
 
c65e601
4953451
 
 
 
 
 
 
 
 
f3205c7
4953451
 
 
 
cf0186c
4953451
e876179
 
cf0186c
e876179
4953451
 
 
 
 
 
 
 
e876179
a377724
 
 
 
4953451
 
 
 
 
 
 
 
 
 
 
 
e876179
4953451
 
 
 
 
 
 
 
 
 
e876179
fe8f9dd
e876179
 
c65e601
dd7cb5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bf2d715
4661923
 
 
dd7cb5f
 
 
 
 
 
 
 
 
9efb272
dd7cb5f
1d76828
3deafeb
f3937f7
3deafeb
3978799
 
 
c46b415
 
 
 
1d76828
 
c46b415
3deafeb
c46b415
3deafeb
 
 
 
 
 
 
 
 
 
 
 
 
dd7cb5f
9efb272
3adb25c
 
 
3978799
3deafeb
c46b415
3978799
e2df47d
 
 
8eeb102
3978799
 
 
 
 
 
 
 
3deafeb
3978799
3deafeb
3978799
 
 
3deafeb
3978799
c46b415
 
3978799
3adb25c
 
3deafeb
1d76828
dd7cb5f
 
 
c46b415
dd7cb5f
 
56698c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c65e601
 
6ef229f
 
 
 
 
c65e601
 
 
 
4307a66
 
 
 
e4ce5de
4661923
 
 
6ef229f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1d202c
 
 
3deafeb
a1d202c
 
 
 
6ef229f
 
 
 
 
 
 
 
 
c65e601
6ef229f
 
 
c65e601
 
 
 
 
 
 
 
 
a1d202c
 
 
3deafeb
a1d202c
 
 
 
 
c65e601
 
 
 
 
 
47dc8a7
2a06b2a
7672900
e2df47d
47dc8a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7672900
e2df47d
b2c849d
47dc8a7
93359ec
47dc8a7
93359ec
b2c849d
e2df47d
b2c849d
47dc8a7
7672900
e2df47d
7672900
2a06b2a
 
 
9841510
cf0186c
2a06b2a
cf0186c
 
 
 
 
 
9841510
cf0186c
9841510
cf0186c
9841510
cf0186c
 
 
9841510
 
 
cf0186c
 
 
4307a66
9841510
 
2a06b2a
 
cf0186c
08794f7
cf0186c
3deafeb
cf0186c
 
08794f7
 
cf0186c
 
 
65ec15e
 
 
 
 
 
cf0186c
65ec15e
2a06b2a
08794f7
2a06b2a
3ee554d
 
 
9efb272
3ee554d
 
9efb272
 
 
 
 
 
 
 
 
 
 
 
 
 
3ee554d
 
 
 
 
813fe6a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
08794f7
 
3deafeb
08794f7
 
 
 
813fe6a
 
 
 
 
08794f7
813fe6a
 
4661923
 
 
 
08794f7
 
 
 
4661923
 
 
08794f7
4661923
3deafeb
4661923
08794f7
 
4661923
 
08794f7
 
4661923
 
08794f7
4661923
 
 
 
89b794e
4661923
 
08794f7
89b794e
08794f7
 
 
 
 
4661923
 
08794f7
a734e11
3deafeb
a734e11
 
08794f7
a734e11
08794f7
 
 
 
4661923
08794f7
4661923
 
2a06b2a
 
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
from flask import Flask, render_template, request, jsonify, session, redirect, url_for, current_app
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime, timedelta
import os
import time
from functools import wraps
import requests
import shutil

# 添加新的環境變數
SETTINGS_SCRIPT_URL = os.environ.get('SETTINGS_SCRIPT_URL', '')
ADMIN_PASSWORD = os.environ.get('ADMIN_PASSWORD', 'admin')

app = Flask(__name__, instance_relative_config=True)

# 設置 session secret key
app.secret_key = os.urandom(24)

# 設置管理者密碼和 Google Apps Script URL
app.config['ADMIN_PASSWORD'] = ADMIN_PASSWORD
app.config['SETTINGS_SCRIPT_URL'] = SETTINGS_SCRIPT_URL

# 設置資料庫路徑 - 使用持久化存儲
if os.environ.get('SPACE_ID'):  # 在 Hugging Face Spaces 環境中
    # 確保資料目錄存在
    os.makedirs('/data', exist_ok=True)
    db_path = '/data/event.db'
    
    # 檢查資料庫文件是否存在
    if not os.path.exists(db_path):
        print(f"資料庫文件不存在:{db_path}")
        # 如果資料庫不存在,將創建一個新的
        open(db_path, 'a').close()
        print("創建了新的資料庫文件")
else:  # 在本地開發環境中
    # 確保 instance 目錄存在
    os.makedirs(app.instance_path, exist_ok=True)
    db_path = os.path.join(app.instance_path, 'event.db')

print(f"使用資料庫路徑: {db_path}")

# 設置資料庫
app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{db_path}'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)

class Table(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100))  # 新增桌次名稱欄位
    capacity = db.Column(db.Integer, nullable=False)
    participants = db.relationship('Participant', backref='table', lazy=True)

    def to_dict(self):
        return {
            'id': self.id,
            'name': self.name or '',  # 確保 name 不會是 None
            'capacity': self.capacity,
            'participants': [{
                'id': p.id,
                'nickname': p.nickname,
                'fb_link': p.fb_link,
                'introduction': p.introduction,
                'is_table_leader': p.is_table_leader,
                'created_at': p.created_at,
                'has_paid': p.has_paid,
                'note': p.note
            } for p in sorted(self.participants, key=lambda x: (not x.is_table_leader, x.created_at))]
        }

class Participant(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    nickname = db.Column(db.String(100), nullable=False)
    email = db.Column(db.String(120), nullable=False)
    fb_link = db.Column(db.String(200))
    introduction = db.Column(db.Text)
    table_id = db.Column(db.Integer, db.ForeignKey('table.id'))  
    seat_number = db.Column(db.Integer)
    is_table_leader = db.Column(db.Boolean, default=False)  
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    has_paid = db.Column(db.Boolean, default=False)  
    note = db.Column(db.Text)  

    def to_dict(self):
        return {
            'id': self.id,
            'nickname': self.nickname,
            'email': self.email,
            'fb_link': self.fb_link,
            'introduction': self.introduction,
            'table_id': self.table_id,
            'seat_number': self.seat_number,
            'is_table_leader': self.is_table_leader,  
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S'),
            'has_paid': self.has_paid,
            'note': self.note
        }

# 初始化資料庫和創建預設桌子
def init_db():
    with app.app_context():
        try:
            # 只創建不存在的表格
            db.create_all()
            
            # 從 Google Sheets 獲取設定
            print("正在從 Google Sheets 獲取設定...")
            try:
                if not app.config.get('SETTINGS_SCRIPT_URL'):
                    print("未設定 SETTINGS_SCRIPT_URL,使用預設值")
                    raise Exception("未設定 SETTINGS_SCRIPT_URL")
                
                response = requests.get(app.config['SETTINGS_SCRIPT_URL'])
                if response.status_code != 200:
                    print(f"Google Sheets API 返回錯誤狀態碼: {response.status_code}")
                    raise Exception(f"Google Sheets API 返回錯誤狀態碼: {response.status_code}")
                
                try:
                    data = response.json()
                except ValueError as e:
                    print("JSON 解析錯誤:", str(e))
                    print("原始回應內容:", response.text)
                    raise
                
                if not data.get('success'):
                    error_msg = data.get('error', '從 Google Sheets 獲取資料失敗')
                    print("Google Sheets 返回錯誤:", error_msg)
                    raise Exception(error_msg)
                
                # 獲取設定
                settings = data.get('settings', {})
                total_tables = settings.get('total_tables', 10)
                seats_per_table = settings.get('seats_per_table', 10)
                
                print(f"從 Google Sheets 獲取到的設定:")
                print(f"- 總桌數: {total_tables}")
                print(f"- 每桌人數: {seats_per_table}")
                
                # 清空現有的桌次和參與者資料
                print("清空現有資料...")
                Participant.query.delete()
                Table.query.delete()
                
                # 創建桌次
                tables_data = data.get('tables', [])
                print(f"從 Google Sheets 讀取 {len(tables_data)} 張桌子")
                
                for i in range(1, total_tables + 1):
                    # 從 tables_data 中找到對應的桌次資料
                    table_data = next((t for t in tables_data if t['id'] == i), None)
                    table_name = table_data['name'].strip() if table_data and table_data.get('name') else f'第{i}桌'
                    
                    table = Table(
                        id=i,
                        name=table_name,
                        capacity=seats_per_table
                    )
                    db.session.add(table)
                    print(f"創建第 {i} 桌,名稱為: {table_name}")
                
                # 創建參與者
                participants_data = data.get('participants', [])
                print(f"從 Google Sheets 讀取 {len(participants_data)} 位參與者")
                
                for p_data in participants_data:
                    try:
                        # 處理 ISO 格式的時間
                        created_at_str = p_data['created_at'].replace('T', ' ').replace('.000Z', '')
                        created_at = datetime.strptime(created_at_str, '%Y-%m-%d %H:%M:%S')
                        
                        participant = Participant(
                            id=int(p_data['id']),
                            nickname=p_data['nickname'],
                            email=p_data['email'],
                            fb_link=p_data.get('fb_link', ''),
                            introduction=p_data.get('introduction', ''),
                            table_id=int(p_data['table_id']),
                            seat_number=int(p_data['seat_number']),
                            is_table_leader=bool(p_data.get('is_table_leader', False)),
                            created_at=created_at,
                            has_paid=bool(p_data.get('has_paid', False)),
                            note=p_data.get('note', '')
                        )
                        db.session.add(participant)
                        print(f"創建參與者: {participant.nickname}")
                    except Exception as e:
                        print(f"處理參與者資料時出錯: {str(e)}")
                        print(f"問題資料: {p_data}")
                        continue
                
                db.session.commit()
                print("資料庫初始化完成")
                
            except Exception as e:
                print(f"從 Google Sheets 獲取設定時出錯: {str(e)}")
                print("使用預設值")
                
                # 如果沒有任何桌次,創建預設桌次
                if Table.query.count() == 0:
                    for i in range(1, 11):  # 預設 10 張桌子
                        table = Table(id=i, name=f'第{i}桌', capacity=10)  # 預設每桌 10 人
                        db.session.add(table)
                    db.session.commit()
                    print("已創建預設桌次")
            
        except Exception as e:
            print(f"初始化資料庫時出錯: {str(e)}")
            db.session.rollback()
            raise

# 在應用啟動時初始化資料庫
with app.app_context():
    try:
        # 創建資料庫表格(如果不存在)
        db.create_all()
        print("資料庫表格創建成功")
        
        # 檢查資料庫連接
        db.session.execute('SELECT 1')
        print("資料庫初始化成功")
        
        # 從 Google Sheets 同步資料
        print("從 Google Sheets 同步資料...")
        try:
            response = requests.get(app.config['SETTINGS_SCRIPT_URL'])
            print(f"Google Sheets 回應狀態碼: {response.status_code}")
            print(f"Google Sheets 回應內容: {response.text}")
            
            data = response.json()
            if not data.get('success'):
                raise Exception(f"同步失敗: {data.get('error', '未知錯誤')}")
            
            # 清空現有資料
            Participant.query.delete()
            Table.query.delete()
            db.session.commit()
            
            # 從 Google Sheets 讀取設定
            settings = data.get('settings', {})
            if not settings:
                raise Exception("無法從 Google Sheets 讀取設定")
                
            total_tables = int(settings.get('total_tables', 10))
            seats_per_table = int(settings.get('seats_per_table', 10))
            print(f"從 Google Sheets 讀取設定:總桌數={total_tables}, 每桌人數={seats_per_table}")
            
            # 創建桌子
            for i in range(1, total_tables + 1):
                table = Table(
                    name=f'第{i}桌',
                    capacity=seats_per_table
                )
                db.session.add(table)
            db.session.commit()
            print("桌次設定更新完成")
            
            # 恢復參與者資料
            participants_data = data.get('participants', [])
            print(f"從 Google Sheets 讀取 {len(participants_data)} 位參與者資料")
            
            for participant_data in participants_data:
                created_at_str = participant_data['created_at'].replace('T', ' ').replace('.000Z', '')
                created_at = datetime.strptime(created_at_str, '%Y-%m-%d %H:%M:%S')
                
                participant = Participant(
                    nickname=participant_data['nickname'],
                    email=participant_data['email'],
                    fb_link=participant_data.get('fb_link', ''),
                    introduction=participant_data.get('introduction', ''),
                    table_id=participant_data['table_id'],
                    seat_number=participant_data['seat_number'],
                    is_table_leader=participant_data.get('is_table_leader', False),
                    created_at=created_at,
                    has_paid=participant_data.get('has_paid', False),
                    note=participant_data.get('note', '')
                )
                db.session.add(participant)
                print(f"已更新參與者: {participant.nickname}")
            
            db.session.commit()
            print("參與者資料更新完成")
        except Exception as e:
            print(f"同步資料時出錯: {str(e)}")
            
    except Exception as e:
        print(f"初始化資料庫時出錯: {str(e)}")

# 管理者認證裝飾器
def admin_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if not session.get('admin_logged_in'):
            return redirect(url_for('admin_login'))
        return f(*args, **kwargs)
    return decorated_function

# 添加新的環境變數
SETTINGS_SCRIPT_URL = os.environ.get('SETTINGS_SCRIPT_URL', '')

def sync_settings_to_sheets(action, data):
    """同步設定到 Google Sheets"""
    if not app.config['SETTINGS_SCRIPT_URL']:
        print("未設定 SETTINGS_SCRIPT_URL")
        return {'success': False, 'error': '未設定 Google Sheets URL'}
        
    try:
        print(f"正在同步到 Google Sheets: action={action}, data={data}")
        response = requests.post(app.config['SETTINGS_SCRIPT_URL'], json={
            'action': action,
            **data
        })
        print(f"Google Sheets 回應狀態碼: {response.status_code}")
        print(f"Google Sheets 回應內容: {response.text}")
        
        if response.status_code != 200:
            return {'success': False, 'error': f'Google Sheets 回應錯誤: {response.status_code}'}
            
        try:
            result = response.json()
            return result
        except ValueError as e:
            print(f"JSON 解析錯誤: {str(e)}")
            return {'success': False, 'error': '無效的 JSON 回應'}
            
    except Exception as e:
        print(f"同步到 Google Sheets 時出錯: {str(e)}")
        return {'success': False, 'error': str(e)}

def _backup_data_internal():
    """內部函數:同步參與者資料到 Google Sheets"""
    try:
        all_participants = Participant.query.all()
        participants_data = []
        
        for p in all_participants:
            local_time = p.created_at + timedelta(hours=8)  # 轉換為台灣時間
            participants_data.append({
                'id': p.id,
                'nickname': p.nickname,
                'email': p.email,
                'fb_link': p.fb_link,
                'introduction': p.introduction,
                'table_id': p.table_id,
                'seat_number': p.seat_number,
                'is_table_leader': p.is_table_leader,  
                'created_at': local_time.strftime('%Y-%m-%d %H:%M:%S'),
                'has_paid': p.has_paid,  
                'note': p.note or ''
            })
            
        # 同步到 Google Sheets
        response = requests.post(SETTINGS_SCRIPT_URL, json={
            'action': 'backupParticipants',  
            'participants': participants_data  
        })
        
        if response.status_code != 200:
            raise Exception(f"同步到 Google Sheets 失敗: {response.text}")
            
        return True
    except Exception as e:
        print(f"備份資料時出錯: {str(e)}")
        raise e

@app.route('/api/admin/backup', methods=['POST'])
@admin_required
def backup_data():
    """API 路由:備份參與者資料(需要管理員權限)"""
    try:
        _backup_data_internal()
        return jsonify({'message': '備份成功'})
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/admin/login')
def admin_login():
    return render_template('admin_login.html')

@app.route('/admin')
@admin_required
def admin():
    return render_template('admin.html')

@app.route('/api/admin/login', methods=['POST'])
def admin_login_api():
    data = request.json
    if data.get('password') == app.config['ADMIN_PASSWORD']:
        session['admin_logged_in'] = True
        return jsonify({'success': True, 'message': 'Login successful'}), 200
    return jsonify({'success': False, 'error': 'Invalid password'}), 401

@app.route('/api/admin/settings/update', methods=['POST'])
@admin_required
def update_settings():
    try:
        data = request.get_json()
        action = data.get('action')

        if action == 'update_tables':
            total_tables = int(data.get('total_tables', 10))
            seats_per_table = int(data.get('seats_per_table', 10))
            
            # 更新 Google Sheets
            sync_settings_to_sheets('updateSettings', {
                'total_tables': total_tables,
                'seats_per_table': seats_per_table
            })
            
            # 更新資料庫中的桌次
            current_tables = Table.query.order_by(Table.id).all()
            current_count = len(current_tables)
            
            if total_tables > current_count:
                # 需要添加新桌次
                for i in range(current_count + 1, total_tables + 1):
                    new_table = Table(id=i, capacity=seats_per_table)
                    db.session.add(new_table)
            elif total_tables < current_count:
                # 需要刪除多餘的桌次
                # 檢查要刪除的桌次是否有參與者
                for table in current_tables[total_tables:]:
                    if len(table.participants) > 0:  # 只刪除沒有參與者的桌次
                        return jsonify({
                            'error': f'無法刪除第 {table.id} 桌,因為還有參與者在該桌'
                        }), 400
                    db.session.delete(table)
            
            # 更新所有桌次的容量
            for table in Table.query.all():
                table.capacity = seats_per_table
            
            db.session.commit()
            
            return jsonify({
                'message': '設定已更新',
                'settings': {
                    'total_tables': total_tables,
                    'seats_per_table': seats_per_table
                }
            })
            
        elif action == 'update_table_name':
            table_id = data.get('table_id')
            name = data.get('name', '')
            
            table = Table.query.get(table_id)
            if not table:
                return jsonify({'error': '找不到該桌次'}), 404
                
            table.name = name
            db.session.commit()
            
            # 同步到 Google Sheets
            sync_settings_to_sheets('update_table_name', {
                'table_id': table_id,
                'name': name
            })
            
            return jsonify({
                'message': '桌次名稱已更新',
                'table': {
                    'id': table.id,
                    'name': table.name
                }
            })
            
        return jsonify({'error': '未知的操作'}), 400
        
    except Exception as e:
        print(f"更新設定時出錯: {str(e)}")
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

@app.route('/api/admin/settings/backup', methods=['POST'])
@admin_required
def backup_settings():
    try:
        # 獲取當前所有桌子設定
        tables = Table.query.all()
        total_tables = len(tables)
        seats_per_table = tables[0].capacity if tables else 0
        
        # 同步設定到 Sheets
        sync_settings_to_sheets('saveSettings', {
            'totalTables': total_tables,
            'seatsPerTable': seats_per_table
        })
        
        # 備份參與者資料
        participants = Participant.query.all()
        sync_settings_to_sheets('backupParticipants', {
            'participants': [{
                'id': p.id,
                'nickname': p.nickname,
                'email': p.email,
                'fb_link': p.fb_link,
                'introduction': p.introduction,
                'table_id': p.table_id,
                'seat_number': p.seat_number,
                'is_table_leader': p.is_table_leader,
                'created_at': p.created_at.strftime('%Y-%m-%d %H:%M:%S'),
                'has_paid': p.has_paid,
                'note': p.note
            } for p in participants]
        })
        
        return jsonify({'message': '備份成功'})
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/admin/settings/restore', methods=['POST'])
@admin_required
def restore_data():
    try:
        # 從 Google Apps Script 獲取數據
        print("正在從 Google Sheets 同步資料...")
        response = requests.get(app.config['SETTINGS_SCRIPT_URL'])
        print("Google Sheets 回應狀態碼:", response.status_code)
        
        try:
            data = response.json()
        except ValueError as e:
            print("JSON 解析錯誤:", str(e))
            print("原始回應內容:", response.text)
            return jsonify({'error': '從 Google Sheets 獲取資料失敗:無效的 JSON 格式'}), 500
        
        if not data.get('success'):
            error_msg = data.get('error', '從 Google Sheets 恢復資料失敗')
            print("Google Sheets 返回錯誤:", error_msg)
            return jsonify({'error': error_msg}), 400
            
        # 更新桌次設定
        settings = data.get('settings', {})
        print(f"從 Google Sheets 讀取設定:總桌數={settings.get('total_tables')}, 每桌人數={settings.get('seats_per_table')}")
        
        # 更新桌次名稱
        tables_data = data.get('tables', [])
        for table_data in tables_data:
            table = Table.query.get(table_data.get('id'))
            if table and 'name' in table_data:
                table.name = table_data['name']
        db.session.commit()
        print("桌次設定更新完成")
        
        # 清空現有的參與者資料
        Participant.query.delete()
        
        # 恢復參與者資料
        participants_data = data.get('participants', [])
        print(f"從 Google Sheets 讀取 {len(participants_data)} 位參與者資料")
        
        for participant_data in participants_data:
            # 處理 ISO 格式的時間
            created_at_str = participant_data['created_at'].replace('T', ' ').replace('.000Z', '')
            created_at = datetime.strptime(created_at_str, '%Y-%m-%d %H:%M:%S')
            
            try:
                participant = Participant(
                    nickname=participant_data['nickname'],
                    email=participant_data['email'],
                    fb_link=participant_data.get('fb_link', ''),
                    introduction=participant_data.get('introduction', ''),
                    table_id=int(participant_data['table_id']),
                    seat_number=int(participant_data['seat_number']),
                    is_table_leader=participant_data.get('is_table_leader') == True or participant_data.get('is_table_leader') == 'TRUE',  
                    created_at=created_at,
                    has_paid=participant_data.get('has_paid') == True or participant_data.get('has_paid') == 'TRUE',  
                    note=participant_data.get('note', '')
                )
                db.session.add(participant)
                print(f"已更新參與者: {participant.nickname}")
            except (KeyError, ValueError) as e:
                print(f"處理參與者資料時出錯: {str(e)}")
                print(f"問題資料: {participant_data}")
                continue
        
        db.session.commit()
        print("參與者資料更新完成")
        return jsonify({'message': '資料已成功恢復'})
        
    except Exception as e:
        db.session.rollback()
        print('恢復資料時出錯:', str(e))
        return jsonify({'error': str(e)}), 500

@app.route('/api/admin/settings', methods=['GET'])
@admin_required
def get_settings():
    try:
        # 從 Google Sheets 獲取最新設定
        response = requests.get(app.config['SETTINGS_SCRIPT_URL'])
        if response.status_code == 200:
            data = response.json()
            if data.get('success'):
                settings = data.get('settings', {})
                return jsonify({
                    'total_tables': settings.get('total_tables', 10),
                    'seats_per_table': settings.get('seats_per_table', 10)
                })
        
        # 如果無法從 Google Sheets 獲取,使用資料庫中的設定
        total_tables = Table.query.count()
        first_table = Table.query.first()
        seats_per_table = first_table.capacity if first_table else 10
        
        return jsonify({
            'total_tables': total_tables,
            'seats_per_table': seats_per_table
        })
    except Exception as e:
        print(f"獲取設定時出錯: {str(e)}")
        return jsonify({'error': str(e)}), 500

@app.route('/api/admin/participants', methods=['GET'])
@admin_required
def get_all_participants():
    try:
        participants = Participant.query.all()
        tables = Table.query.all()
        return jsonify({
            'participants': [{
                'id': p.id,
                'nickname': p.nickname,
                'email': p.email,
                'fb_link': p.fb_link,
                'introduction': p.introduction,
                'table_id': p.table_id,
                'seat_number': p.seat_number,
                'is_table_leader': p.is_table_leader,
                'created_at': p.created_at.strftime('%Y-%m-%d %H:%M:%S'),
                'has_paid': p.has_paid,
                'note': p.note
            } for p in participants],
            'tables': [{
                'id': t.id,
                'name': t.name,
                'capacity': t.capacity,
                'current_seats': len(Participant.query.filter_by(table_id=t.id).all())
            } for t in tables]
        })
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/admin/participant/<int:participant_id>/move', methods=['POST'])
@admin_required
def move_participant(participant_id):
    try:
        data = request.get_json()
        new_table_id = data.get('new_table_id')
        
        if not new_table_id:
            return jsonify({'error': '請提供新的桌號'}), 400
            
        participant = Participant.query.get(participant_id)
        if not participant:
            return jsonify({'error': '找不到該參與者'}), 404
            
        new_table = Table.query.get(new_table_id)
        if not new_table:
            return jsonify({'error': '找不到該桌子'}), 404
            
        # 檢查新桌子是否已滿
        current_seats = len(Participant.query.filter_by(table_id=new_table_id).all())
        if current_seats >= new_table.capacity:
            return jsonify({'error': '該桌已滿'}), 400
            
        # 更新座位號碼
        participant.table_id = new_table_id
        participant.seat_number = current_seats + 1
        
        db.session.commit()

        # 同步到 Google Sheets
        try:
            _backup_data_internal()  
            print("成功備份參與者資料到 Google Sheets")
        except Exception as e:
            print(f"同步到 Google Sheets 時出錯: {str(e)}")
            # 不中斷操作,只記錄錯誤
        
        return jsonify({
            'message': '成功移動座位',
            'participant': {
                'id': participant.id,
                'nickname': participant.nickname,
                'table_id': participant.table_id,
                'seat_number': participant.seat_number
            }
        })
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

@app.route('/api/admin/participants/<int:participant_id>', methods=['DELETE'])
@admin_required
def delete_participant(participant_id):
    try:
        participant = Participant.query.get(participant_id)
        if participant:
            db.session.delete(participant)
            db.session.commit()
            
            # 同步到 Google Sheets
            try:
                _backup_data_internal()  
                print("成功備份參與者資料到 Google Sheets")
            except Exception as e:
                print(f"同步到 Google Sheets 時出錯: {str(e)}")
                # 不中斷操作,只記錄錯誤
            
            return jsonify({'message': 'Participant deleted successfully'})
        return jsonify({'error': 'Participant not found'}), 404
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 400

@app.route('/api/tables', methods=['GET'])
def get_tables():
    try:
        print("正在獲取桌次資料...")
        
        # 如果是從管理後台呼叫,先從 Google Sheets 同步資料
        if request.referrer and '/admin' in request.referrer:
            print("從管理後台呼叫,同步 Google Sheets 資料...")
            try:
                response = requests.get(app.config['SETTINGS_SCRIPT_URL'])
                if response.status_code == 200:
                    data = response.json()
                    if data.get('success'):
                        # 更新桌次名稱
                        tables_data = data.get('tables', [])
                        table_names = {table['id']: table['name'] for table in tables_data}
                        for table in Table.query.all():
                            if table.id in table_names:
                                table.name = table_names[table.id]
                        
                        # 更新參與者資料
                        participants_data = data.get('participants', [])
                        for p_data in participants_data:
                            participant = Participant.query.get(p_data['id'])
                            if participant:
                                participant.nickname = p_data['nickname']
                                participant.email = p_data['email']
                                participant.fb_link = p_data.get('fb_link', '')
                                participant.introduction = p_data.get('introduction', '')
                                participant.table_id = int(p_data['table_id'])
                                participant.seat_number = int(p_data['seat_number'])
                                participant.is_table_leader = bool(p_data.get('is_table_leader', False))
                                participant.has_paid = bool(p_data.get('has_paid', False))
                                participant.note = p_data.get('note', '')
                        
                        db.session.commit()
                        print("資料已從 Google Sheets 更新")
                    else:
                        print("從 Google Sheets 獲取資料失敗")
                else:
                    print(f"Google Sheets API 返回錯誤狀態碼: {response.status_code}")
            except Exception as e:
                print(f"同步 Google Sheets 資料時出錯: {str(e)}")
        
        # 從資料庫獲取桌次資料
        tables = Table.query.order_by(Table.id).all()
        print(f"找到 {len(tables)} 張桌子")
        
        # 轉換成 JSON 格式
        result = {
            'tables': [table.to_dict() for table in tables]
        }
        
        print("桌次資料獲取成功")
        return jsonify(result)
        
    except Exception as e:
        print(f"獲取桌次資料時出錯: {str(e)}")
        return jsonify({'error': str(e)}), 500

@app.route('/api/register', methods=['POST'])
def register():
    try:
        data = request.get_json()
        
        # 驗證必填欄位
        if not all(key in data for key in ['nickname', 'email', 'table_id']):
            return jsonify({'error': '缺少必要欄位'}), 400
            
        # 檢查桌子是否存在且有空位
        table = Table.query.get(data['table_id'])
        if not table:
            return jsonify({'error': '找不到該桌子'}), 404
            
        current_seats = len(Participant.query.filter_by(table_id=data['table_id']).all())
        if current_seats >= table.capacity:
            return jsonify({'error': '該桌已滿'}), 400
            
        # 創建新參與者
        participant = Participant(
            nickname=data['nickname'],
            email=data['email'],
            fb_link=data.get('fb_link', ''),
            introduction=data.get('introduction', ''),
            table_id=data['table_id'],
            seat_number=current_seats + 1
        )
        
        db.session.add(participant)
        db.session.commit()
        
        # 同步到 Google Sheets
        try:
            _backup_data_internal()  
            print("成功備份參與者資料到 Google Sheets")
        except Exception as e:
            print(f"同步到 Google Sheets 時出錯: {str(e)}")
            # 不中斷操作,只記錄錯誤
        
        return jsonify({
            'message': '報名成功',
            'participant': {
                'id': participant.id,
                'nickname': participant.nickname,
                'table_id': participant.table_id,
                'seat_number': participant.seat_number
            }
        })
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/participants/export', methods=['GET'])
def export_participants():
    try:
        participants = Participant.query.all()
        export_data = []
        
        for participant in participants:
            local_time = participant.created_at + timedelta(hours=8)  # 轉換為台灣時間
            export_data.append({
                'nickname': participant.nickname,
                'email': participant.email,
                'fb_link': participant.fb_link,
                'introduction': participant.introduction,
                'table_id': participant.table_id,
                'seat_number': participant.seat_number,
                'is_table_leader': '是' if participant.is_table_leader else '否',
                'registration_time': local_time.strftime('%Y-%m-%d %H:%M:%S'),
                'has_paid': '是' if participant.has_paid else '否',
                'note': participant.note or ''
            })
        
        return jsonify(export_data)
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/admin/participant/<int:participant_id>/toggle-leader', methods=['POST'])
@admin_required
def toggle_leader(participant_id):
    try:
        participant = Participant.query.get(participant_id)
        if not participant:
            return jsonify({'error': '找不到該參與者'}), 404
            
        # 如果要設為桌長,先確認該桌是否已有桌長
        if not participant.is_table_leader:
            existing_leader = Participant.query.filter_by(
                table_id=participant.table_id, 
                is_table_leader=True
            ).first()
            
            if existing_leader:
                return jsonify({
                    'error': f'該桌已有桌長:{existing_leader.nickname}'
                }), 400
        
        # 切換桌長狀態
        participant.is_table_leader = not participant.is_table_leader
        db.session.commit()
        
        # 同步到 Google Sheets
        try:
            _backup_data_internal()  
        except Exception as e:
            print(f"同步到 Google Sheets 時出錯: {str(e)}")
            # 不中斷操作,只記錄錯誤
        
        return jsonify({
            'message': f'已{participant.is_table_leader and "設為" or "取消"}桌長',
            'participant': participant.to_dict()
        })
    except Exception as e:
        print("更新桌長狀態時出錯:", str(e))
        return jsonify({'error': str(e)}), 500

@app.route('/api/admin/participant/<int:participant_id>/payment', methods=['POST'])
@admin_required
def toggle_payment(participant_id):
    try:
        participant = Participant.query.get(participant_id)
        if not participant:
            return jsonify({'error': '找不到該參與者'}), 404
            
        participant.has_paid = not participant.has_paid
        db.session.commit()
        
        # 同步到 Google Sheets
        try:
            _backup_data_internal()  
        except Exception as e:
            print(f"同步到 Google Sheets 時出錯: {str(e)}")
            # 不中斷操作,只記錄錯誤
        
        return jsonify({
            'message': f'已更新付款狀態為{"已" if participant.has_paid else "未"}付款',
            'participant': participant.to_dict()
        })
    except Exception as e:
        print("更新付款狀態時出錯:", str(e))
        return jsonify({'error': str(e)}), 500

@app.route('/api/admin/participant/<int:participant_id>/note', methods=['POST'])
@admin_required
def update_participant_note(participant_id):
    try:
        data = request.get_json()
        note = data.get('note', '')
        
        participant = Participant.query.get(participant_id)
        if not participant:
            return jsonify({'error': '找不到該參與者'}), 404
            
        participant.note = note
        db.session.commit()
        
        # 同步到 Google Sheets
        try:
            _backup_data_internal()  
        except Exception as e:
            print(f"同步到 Google Sheets 時出錯: {str(e)}")
            # 不中斷操作,只記錄錯誤
        
        return jsonify({
            'message': '備註已更新',
            'participant': participant.to_dict()
        })
    except Exception as e:
        print("更新備註時出錯:", str(e))
        return jsonify({'error': str(e)}), 500

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=7860)