import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:provider/provider.dart'; import 'package:intl/intl.dart'; import 'package:share_plus/share_plus.dart'; import '../../models/event_model.dart'; import '../../models/participant_model.dart'; import '../../models/score_model.dart'; import '../../models/team_model.dart'; // import '../../services/auth_service.dart'; // 사용하지 않는 import 제거 import '../../services/event_service.dart'; import '../../services/notification_service.dart'; import '../../widgets/loading_indicator.dart'; class EventDetailsScreen extends StatefulWidget { final Event event; const EventDetailsScreen({ Key? key, required this.event, }) : super(key: key); @override State createState() => _EventDetailsScreenState(); } class _EventDetailsScreenState extends State with SingleTickerProviderStateMixin { late TabController _tabController; List _participants = []; List _scores = []; List _teams = []; bool _isLoading = true; int _teamGenerationMethod = 1; // 1: 팀 인원수로 나누기, 2: 팀 개수로 나누기 final TextEditingController _teamSizeController = TextEditingController(text: '4'); final TextEditingController _teamCountController = TextEditingController(text: '2'); bool _showTeamTab = false; @override void initState() { super.initState(); _tabController = TabController(length: 4, vsync: this); _loadEventDetails(); } @override void dispose() { _tabController.dispose(); super.dispose(); } Future _loadEventDetails() async { setState(() { _isLoading = true; }); try { final eventService = Provider.of(context, listen: false); // 참가자 목록 로드 final participants = await eventService.fetchEventParticipants(widget.event.id); // 점수 목록 로드 final scores = await eventService.fetchEventScores(widget.event.id); // 팀 목록 로드 (선택적) List teams = []; try { teams = await eventService.fetchEventTeams(widget.event.id); } catch (e) { // 팀 기능이 없거나 오류 발생 시 무시 print('팀 로드 실패: $e'); } if (mounted) { setState(() { _participants = participants; _scores = scores; _teams = teams; _showTeamTab = teams.isNotEmpty || widget.event.type == '팀전'; _isLoading = false; }); } } catch (e) { if (mounted) { setState(() { _isLoading = false; }); ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text('이벤트 정보를 불러오는데 실패했습니다: $e')), ); } } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.event.title), bottom: TabBar( controller: _tabController, tabs: [ const Tab(text: '기본 정보'), const Tab(text: '참가자'), const Tab(text: '점수'), if (_showTeamTab) const Tab(text: '팀'), ], ), ), body: _isLoading ? const LoadingIndicator() : TabBarView( controller: _tabController, children: [ _buildBasicInfoTab(), _buildParticipantsTab(), _buildScoresTab(), if (_showTeamTab) _buildTeamsTab(), ], ), floatingActionButton: _buildFloatingActionButton(), ); } Widget _buildFloatingActionButton() { final currentTab = _tabController.index; switch (currentTab) { case 0: // 기본 정보 탭 return FloatingActionButton( onPressed: _editEvent, child: const Icon(Icons.edit), ); case 1: // 참가자 탭 return FloatingActionButton( onPressed: _addParticipant, child: const Icon(Icons.person_add), ); case 2: // 점수 탭 return FloatingActionButton( onPressed: _addScore, child: const Icon(Icons.add_chart), ); case 3: // 팀 탭 (표시되는 경우) if (_showTeamTab) { return FloatingActionButton( onPressed: _generateTeams, child: const Icon(Icons.group_add), ); } return Container(); default: return Container(); } } // 기본 정보 탭 Widget _buildBasicInfoTab() { return SingleChildScrollView( padding: const EdgeInsets.all(16), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ // 이벤트 유형 및 상태 뱃지 Row( children: [ Container( padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6), decoration: BoxDecoration( color: _getTypeColor(widget.event.type ?? '기타'), borderRadius: BorderRadius.circular(16), ), child: Text( widget.event.type ?? '기타', style: const TextStyle( color: Colors.white, fontWeight: FontWeight.bold, ), ), ), const SizedBox(width: 8), Container( padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6), decoration: BoxDecoration( color: _getStatusColor(widget.event.status ?? '준비중'), borderRadius: BorderRadius.circular(16), ), child: Text( widget.event.status ?? '준비중', style: const TextStyle( color: Colors.white, fontWeight: FontWeight.bold, ), ), ), const Spacer(), // 공유 버튼 추가 IconButton( icon: const Icon(Icons.share), onPressed: _shareEvent, tooltip: '이벤트 공유', ), ], ), const SizedBox(height: 16), // 이벤트 설명 if (widget.event.description != null && widget.event.description!.isNotEmpty) ...[ const Text( '설명', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold), ), const SizedBox(height: 8), Container( width: double.infinity, padding: const EdgeInsets.all(12), decoration: BoxDecoration( color: Colors.grey[100], borderRadius: BorderRadius.circular(8), ), child: Text(widget.event.description ?? ''), ), const SizedBox(height: 16), ], // 이벤트 정보 const Text( '이벤트 정보', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold), ), const SizedBox(height: 8), _buildInfoRow( Icons.calendar_today, '시작: ${DateFormat('yyyy-MM-dd HH:mm').format(widget.event.startDate)}', ), if (widget.event.endDate != null) _buildInfoRow( Icons.calendar_today, '종료: ${DateFormat('yyyy-MM-dd HH:mm').format(widget.event.endDate!)}', ), if (widget.event.location != null && widget.event.location!.isNotEmpty) _buildInfoRow(Icons.location_on, '장소: ${widget.event.location}'), if (widget.event.maxParticipants != null) _buildInfoRow( Icons.people, '최대 참가자: ${widget.event.maxParticipants}명', ), if (widget.event.gameCount != null) _buildInfoRow( Icons.sports, '게임 수: ${widget.event.gameCount}게임', ), if (widget.event.participantFee != null) _buildInfoRow( Icons.attach_money, '참가비: ${NumberFormat.currency(locale: 'ko_KR', symbol: '₩', decimalDigits: 0).format(widget.event.participantFee)}', ), if (widget.event.registrationDeadline != null) _buildInfoRow( Icons.timer, '신청마감: ${DateFormat('yyyy-MM-dd HH:mm').format(widget.event.registrationDeadline!)}', ), const SizedBox(height: 16), // 공개 접근 정보 const Text( '공개 접근', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold), ), const SizedBox(height: 8), if (widget.event.publicHash != null && widget.event.publicHash!.isNotEmpty) ...[ Row( children: [ Expanded( child: _buildInfoRow( Icons.link, 'https://bowling.example.com/events/${widget.event.publicHash}', isSelectable: true, ), ), IconButton( icon: const Icon(Icons.copy), onPressed: () { final publicUrl = 'https://bowling.example.com/events/${widget.event.publicHash}'; Clipboard.setData(ClipboardData(text: publicUrl)); ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('공개 URL이 클립보드에 복사되었습니다')), ); }, tooltip: 'URL 복사', ), ], ), ], if (widget.event.accessPassword != null && widget.event.accessPassword!.isNotEmpty) _buildInfoRow( Icons.lock, '접근 비밀번호: ${widget.event.accessPassword}', ), // 참가자 정보 const SizedBox(height: 16), const Text( '참가자 정보', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold), ), const SizedBox(height: 8), _buildInfoRow( Icons.people, '현재 참가자: ${_participants.length}명', ), ], ), ); } // 참가자 탭 Widget _buildParticipantsTab() { if (_participants.isEmpty) { return const Center( child: Text('참가자가 없습니다.'), ); } return ListView.builder( itemCount: _participants.length, itemBuilder: (context, index) { final participant = _participants[index]; return Card( margin: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), child: ListTile( leading: CircleAvatar( backgroundColor: Colors.blue.shade100, child: Text( participant.name?.substring(0, 1) ?? '?', style: const TextStyle(color: Colors.blue), ), ), title: Text( participant.name ?? '이름 없음', style: const TextStyle(fontWeight: FontWeight.bold), ), subtitle: Row( children: [ // 참가 상태 뱃지 if (participant.status != null) Container( margin: const EdgeInsets.only(right: 8), padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2), decoration: BoxDecoration( color: _getParticipantStatusColor(participant.status!).withOpacity(0.2), borderRadius: BorderRadius.circular(12), border: Border.all(color: _getParticipantStatusColor(participant.status!)), ), child: Text( participant.status!, style: TextStyle( fontSize: 12, color: _getParticipantStatusColor(participant.status!), ), ), ), // 결제 상태 뱃지 Container( padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2), decoration: BoxDecoration( color: participant.isPaid ? Colors.green.withOpacity(0.2) : Colors.red.withOpacity(0.2), borderRadius: BorderRadius.circular(12), border: Border.all(color: participant.isPaid ? Colors.green : Colors.red), ), child: Text( participant.isPaid ? '결제완료' : '미결제', style: TextStyle( fontSize: 12, color: participant.isPaid ? Colors.green : Colors.red, ), ), ), ], ), trailing: Row( mainAxisSize: MainAxisSize.min, children: [ IconButton( icon: const Icon(Icons.edit, size: 20), tooltip: '참가자 정보 수정', onPressed: () => _editParticipant(participant), ), IconButton( icon: const Icon(Icons.delete, size: 20), tooltip: '참가자 삭제', onPressed: () => _removeParticipant(participant), ), ], ), onTap: () => _showParticipantDetails(participant), ), ); }, ); } // 점수 탭 Widget _buildScoresTab() { if (_scores.isEmpty) { return const Center( child: Text('등록된 점수가 없습니다.'), ); } // 점수를 내림차순으로 정렬하여 순위 계산 final sortedScores = List.from(_scores); sortedScores.sort((a, b) => b.totalScore.compareTo(a.totalScore)); // 평균 점수 계산 final totalScoreSum = sortedScores.fold(0, (sum, score) => sum + score.totalScore); final averageScore = sortedScores.isNotEmpty ? totalScoreSum / sortedScores.length : 0; return Column( children: [ // 평균 점수 표시 Container( padding: const EdgeInsets.all(8), margin: const EdgeInsets.all(8), decoration: BoxDecoration( color: Colors.blue.shade50, borderRadius: BorderRadius.circular(8), border: Border.all(color: Colors.blue.shade200), ), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ const Icon(Icons.score, color: Colors.blue), const SizedBox(width: 8), Text( '평균 점수: ${averageScore.toStringAsFixed(1)}', style: const TextStyle(fontWeight: FontWeight.bold), ), ], ), ), // 점수 목록 Expanded( child: ListView.builder( itemCount: sortedScores.length, itemBuilder: (context, index) { final score = sortedScores[index]; final rank = index + 1; // 순위 // 참가자 이름 찾기 final participant = _participants.firstWhere( (p) => p.memberId == score.memberId, orElse: () => Participant( id: '', eventId: '', memberId: score.memberId, name: '알 수 없음', ), ); return Card( margin: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), child: ListTile( leading: CircleAvatar( backgroundColor: _getRankColor(rank), child: Text( rank.toString(), style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold), ), ), title: Row( children: [ Expanded( child: Text( participant.name ?? '알 수 없음', style: const TextStyle(fontWeight: FontWeight.bold), ), ), Container( padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2), decoration: BoxDecoration( color: Colors.blue.shade100, borderRadius: BorderRadius.circular(12), ), child: Text( '총점: ${score.totalScore}', style: const TextStyle(fontWeight: FontWeight.bold), ), ), ], ), subtitle: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const SizedBox(height: 4), Text( '날짜: ${DateFormat('yyyy-MM-dd').format(score.date)}', ), const SizedBox(height: 4), SingleChildScrollView( scrollDirection: Axis.horizontal, child: Row( children: score.frames.asMap().entries.map((entry) { return Container( width: 30, height: 30, margin: const EdgeInsets.only(right: 4), decoration: BoxDecoration( color: _getScoreColor(entry.value), borderRadius: BorderRadius.circular(4), ), child: Center( child: Text( entry.value.toString(), style: const TextStyle( color: Colors.white, fontWeight: FontWeight.bold, ), ), ), ); }).toList(), ), ), ], ), trailing: Row( mainAxisSize: MainAxisSize.min, children: [ IconButton( icon: const Icon(Icons.edit, size: 20), tooltip: '점수 수정', onPressed: () => _editScore(score), ), IconButton( icon: const Icon(Icons.delete, size: 20), tooltip: '점수 삭제', onPressed: () => _deleteScore(score), ), ], ), onTap: () => _showScoreDetails(score), ), ); }, ), ), ], ); } // 팀 탭 Widget _buildTeamsTab() { if (_teams.isEmpty) { return Center( child: Padding( padding: const EdgeInsets.all(16.0), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ const Icon(Icons.groups, size: 64, color: Colors.blue), const SizedBox(height: 16), const Text('생성된 팀이 없습니다.', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)), const SizedBox(height: 24), // 팀 생성 옵션 Card( child: Padding( padding: const EdgeInsets.all(16.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const Text('팀 생성 옵션', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)), const SizedBox(height: 16), // 팀 생성 방법 선택 Row( children: [ Radio( value: 1, groupValue: _teamGenerationMethod, onChanged: (value) { setState(() { _teamGenerationMethod = value!; }); }, ), const Text('팀 인원수로 나누기'), ], ), if (_teamGenerationMethod == 1) Padding( padding: const EdgeInsets.only(left: 32.0), child: Row( children: [ SizedBox( width: 80, child: TextFormField( controller: _teamSizeController, decoration: const InputDecoration( labelText: '인원수', suffixText: '명', ), keyboardType: TextInputType.number, inputFormatters: [FilteringTextInputFormatter.digitsOnly], ), ), const SizedBox(width: 16), Text('총 ${_participants.length}명 참가자'), ], ), ), const SizedBox(height: 8), Row( children: [ Radio( value: 2, groupValue: _teamGenerationMethod, onChanged: (value) { setState(() { _teamGenerationMethod = value!; }); }, ), const Text('팀 개수로 나누기'), ], ), if (_teamGenerationMethod == 2) Padding( padding: const EdgeInsets.only(left: 32.0), child: Row( children: [ SizedBox( width: 80, child: TextFormField( controller: _teamCountController, decoration: const InputDecoration( labelText: '팀 수', suffixText: '개', ), keyboardType: TextInputType.number, inputFormatters: [FilteringTextInputFormatter.digitsOnly], ), ), const SizedBox(width: 16), Text('총 ${_participants.length}명 참가자'), ], ), ), const SizedBox(height: 16), // 팀 생성 버튼 Row( mainAxisAlignment: MainAxisAlignment.center, children: [ ElevatedButton.icon( onPressed: _generateTeams, icon: const Icon(Icons.group_add), label: const Text('팀 생성하기'), style: ElevatedButton.styleFrom( backgroundColor: Colors.blue, foregroundColor: Colors.white, padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12), ), ), ], ), ], ), ), ), ], ), ), ); } // 미배정 참가자 목록 조회 final List unassignedParticipants = _getUnassignedParticipants(); return Column( children: [ // 팀 관리 버튼 Padding( padding: const EdgeInsets.all(8.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ ElevatedButton.icon( onPressed: _generateTeams, icon: const Icon(Icons.refresh), label: const Text('팀 재생성'), style: ElevatedButton.styleFrom( backgroundColor: Colors.blue, foregroundColor: Colors.white, ), ), ElevatedButton.icon( onPressed: _saveTeams, icon: const Icon(Icons.save), label: const Text('팀 저장'), style: ElevatedButton.styleFrom( backgroundColor: Colors.green, foregroundColor: Colors.white, ), ), ], ), ), // 이벤트 설명 if (widget.event.description != null && widget.event.description!.isNotEmpty) Padding( padding: const EdgeInsets.symmetric(vertical: 16.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const Text( '이벤트 설명', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold), ), const SizedBox(height: 8), Text(widget.event.description!), ], ), ), // 버튼 그룹 (공유 및 알림) Padding( padding: const EdgeInsets.symmetric(vertical: 16.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ // 공유 버튼 Expanded( child: ElevatedButton.icon( onPressed: _shareEvent, icon: const Icon(Icons.share), label: const Text('이벤트 공유'), style: ElevatedButton.styleFrom( foregroundColor: Colors.white, backgroundColor: Colors.blue, ), ), ), const SizedBox(width: 8), // 알림 설정 버튼 Expanded( child: ElevatedButton.icon( onPressed: _setEventReminders, icon: const Icon(Icons.notifications_active), label: const Text('알림 설정'), style: ElevatedButton.styleFrom( foregroundColor: Colors.white, backgroundColor: Colors.green, ), ), ), ], ), ), // 미배정 참가자 섹션 if (unassignedParticipants.isNotEmpty) Card( margin: const EdgeInsets.all(8), color: Colors.amber.shade50, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: const EdgeInsets.all(8.0), child: Row( children: [ const Icon(Icons.person_off, color: Colors.amber), const SizedBox(width: 8), Text('미배정 참가자 (${unassignedParticipants.length}명)', style: const TextStyle(fontWeight: FontWeight.bold), ), ], ), ), const Divider(height: 1), Wrap( children: unassignedParticipants.map((participant) { return Padding( padding: const EdgeInsets.all(4.0), child: Chip( avatar: const CircleAvatar( child: Icon(Icons.person, size: 16), ), label: Text(participant.name ?? '알 수 없음'), deleteIcon: const Icon(Icons.add_circle, size: 18), onDeleted: () => _showTeamSelectionDialog(participant), ), ); }).toList(), ), ], ), ), // 팀 목록 Expanded( child: ListView.builder( itemCount: _teams.length, itemBuilder: (context, index) { final team = _teams[index]; final teamMembers = _getTeamMembers(team); final teamAverage = _calculateTeamAverage(team); return Card( margin: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), child: ExpansionTile( leading: CircleAvatar( backgroundColor: Colors.blue.shade700, child: Text('${index + 1}', style: const TextStyle(color: Colors.white)), ), title: Row( children: [ Text('팀 ${team.name}', style: const TextStyle(fontWeight: FontWeight.bold)), const SizedBox(width: 8), Container( padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2), decoration: BoxDecoration( color: Colors.blue.shade100, borderRadius: BorderRadius.circular(12), ), child: Text('${team.memberIds.length}명'), ), ], ), subtitle: Row( children: [ const Icon(Icons.bar_chart, size: 16, color: Colors.blue), const SizedBox(width: 4), Text('팀 에버리지: ${teamAverage.toStringAsFixed(1)}'), ], ), children: [ ...teamMembers.map((participant) { // 참가자의 평균 점수 계산 final participantScores = _scores.where((s) => s.memberId == participant.memberId).toList(); final participantAverage = participantScores.isNotEmpty ? participantScores.fold(0, (sum, s) => sum + s.totalScore) / participantScores.length : 0.0; return ListTile( leading: const CircleAvatar( child: Icon(Icons.person, size: 16), ), title: Text(participant.name ?? '알 수 없음'), subtitle: Text('평균: ${participantAverage.toStringAsFixed(1)}'), trailing: IconButton( icon: const Icon(Icons.remove_circle, color: Colors.red), tooltip: '팀에서 제외', onPressed: () => _removeFromTeam(team, participant), ), ); }).toList(), // 팀원 추가 버튼 if (unassignedParticipants.isNotEmpty) ListTile( leading: const Icon(Icons.add_circle, color: Colors.green), title: const Text('팀원 추가하기'), onTap: () => _showParticipantSelectionDialog(team), ), ], ), ); }, ), ), ], ); } // 정보 행 위젯 Widget _buildInfoRow(IconData icon, String text, {bool isSelectable = false}) { return Padding( padding: const EdgeInsets.symmetric(vertical: 8.0), child: Row( children: [ Icon(icon, color: Colors.blue), const SizedBox(width: 8), isSelectable ? Expanded( child: SelectableText( text, style: const TextStyle(fontSize: 16), ), ) : Expanded( child: Text( text, style: const TextStyle(fontSize: 16), ), ), ], ), ); } // 이벤트 유형에 따른 색상 반환 Color _getTypeColor(String type) { switch (type.toLowerCase()) { case '개인전': case 'individual': return Colors.blue; case '팀전': case 'team': return Colors.purple; case '리그': case 'league': return Colors.green; case '토너먼트': case 'tournament': return Colors.orange; default: return Colors.grey; } } // 이벤트 상태에 따른 색상 반환 Color _getStatusColor(String status) { switch (status.toLowerCase()) { case '활성': case 'active': return Colors.green; case '대기': case 'pending': return Colors.orange; case '취소': case 'cancelled': return Colors.red; case '완료': case 'completed': return Colors.blue; default: return Colors.grey; } } // 참가자 상태에 따른 색상 반환 Color _getParticipantStatusColor(String status) { switch (status.toLowerCase()) { case 'registered': case '등록됨': return Colors.blue; case 'confirmed': case '확인됨': return Colors.green; case 'cancelled': case '취소됨': return Colors.red; case 'attended': case '참석함': return Colors.purple; default: return Colors.grey; } } // 순위에 따른 색상 반환 Color _getRankColor(int rank) { switch (rank) { case 1: return Colors.amber.shade700; // 금메달 case 2: return Colors.blueGrey.shade400; // 은메달 case 3: return Colors.brown.shade400; // 동메달 default: return Colors.blue.shade700; // 기본 색상 } } // 점수에 따른 색상 반환 Color _getScoreColor(int score) { if (score >= 9) { return Colors.red.shade700; // 스트라이크 } else if (score >= 7) { return Colors.orange.shade700; // 좋은 점수 } else if (score >= 5) { return Colors.green.shade700; // 평균 점수 } else { return Colors.blue.shade700; // 낮은 점수 } } // 미배정 참가자 목록 가져오기 List _getUnassignedParticipants() { // 현재 팀에 배정된 모든 참가자 ID 목록 final List assignedMemberIds = []; for (final team in _teams) { assignedMemberIds.addAll(team.memberIds); } // 배정되지 않은 참가자 목록 반환 return _participants.where((p) => !assignedMemberIds.contains(p.memberId)).toList(); } // 팀원 목록 가져오기 List _getTeamMembers(Team team) { return _participants .where((p) => team.memberIds.contains(p.memberId)) .toList(); } // 팀 평균 점수 계산 double _calculateTeamAverage(Team team) { if (team.memberIds.isEmpty) return 0.0; double totalAverage = 0.0; int memberCount = 0; for (final memberId in team.memberIds) { final memberScores = _scores.where((s) => s.memberId == memberId).toList(); if (memberScores.isNotEmpty) { final memberTotal = memberScores.fold(0, (sum, score) => sum + score.totalScore); totalAverage += memberTotal / memberScores.length; memberCount++; } } return memberCount > 0 ? totalAverage / memberCount : 0.0; } // 팀 생성 방법 void _generateTeams() { if (_participants.isEmpty) { ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('참가자가 없습니다.')), ); return; } // 기존 팀 삭제 setState(() { _teams.clear(); }); // 참가자 셔플 final shuffledParticipants = List.from(_participants); shuffledParticipants.shuffle(); int teamCount; int teamSize; // 팀 생성 방법에 따른 팀 개수 계산 if (_teamGenerationMethod == 1) { // 팀 인원수로 나누기 teamSize = int.tryParse(_teamSizeController.text) ?? 4; if (teamSize <= 0) teamSize = 4; teamCount = (_participants.length / teamSize).ceil(); } else { // 팀 개수로 나누기 teamCount = int.tryParse(_teamCountController.text) ?? 2; if (teamCount <= 0) teamCount = 2; teamSize = (_participants.length / teamCount).ceil(); } // 팀 생성 final List newTeams = []; for (int i = 0; i < teamCount; i++) { final teamName = String.fromCharCode(65 + i); // A, B, C, ... final team = Team( id: 'temp_${DateTime.now().millisecondsSinceEpoch}_$i', eventId: widget.event.id, name: teamName, memberIds: [], ); newTeams.add(team); } // 참가자 배정 for (int i = 0; i < shuffledParticipants.length; i++) { final teamIndex = i % teamCount; final memberId = shuffledParticipants[i].memberId; if (memberId != null) { newTeams[teamIndex].memberIds.add(memberId); } } setState(() { _teams = newTeams; }); ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text('팀이 생성되었습니다. ($teamCount개 팀)')), ); } // 팀 저장 void _saveTeams() async { if (_teams.isEmpty) { ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('저장할 팀이 없습니다.')), ); return; } setState(() { _isLoading = true; }); try { // 기존 팀 삭제 및 새 팀 저장 로직 구현 // TODO: API 연동 구현 ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('팀이 저장되었습니다.')), ); } catch (e) { ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text('팀 저장 중 오류가 발생했습니다: $e')), ); } finally { setState(() { _isLoading = false; }); } } // 팀에서 참가자 제거 void _removeFromTeam(Team team, Participant participant) { setState(() { team.memberIds.remove(participant.memberId); }); ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text('${participant.name}님이 팀에서 제외되었습니다.')), ); } // 참가자 선택 다이얼로그 표시 void _showParticipantSelectionDialog(Team team) { final unassignedParticipants = _getUnassignedParticipants(); if (unassignedParticipants.isEmpty) { ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('추가할 참가자가 없습니다.')), ); return; } showDialog( context: context, builder: (context) => AlertDialog( title: Text('팀 ${team.name}에 참가자 추가'), content: SizedBox( width: double.maxFinite, child: ListView.builder( shrinkWrap: true, itemCount: unassignedParticipants.length, itemBuilder: (context, index) { final participant = unassignedParticipants[index]; return ListTile( leading: const CircleAvatar( child: Icon(Icons.person, size: 16), ), title: Text(participant.name ?? '알 수 없음'), onTap: () { Navigator.of(context).pop(); setState(() { team.memberIds.add(participant.memberId!); }); ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text('${participant.name}님이 팀 ${team.name}에 추가되었습니다.')), ); }, ); }, ), ), actions: [ TextButton( onPressed: () => Navigator.of(context).pop(), child: const Text('취소'), ), ], ), ); } // 참가자를 추가할 팀 선택 다이얼로그 표시 void _showTeamSelectionDialog(Participant participant) { if (_teams.isEmpty) { ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('추가할 팀이 없습니다.')), ); return; } showDialog( context: context, builder: (context) => AlertDialog( title: Text('${participant.name}님을 추가할 팀 선택'), content: SizedBox( width: double.maxFinite, child: ListView.builder( shrinkWrap: true, itemCount: _teams.length, itemBuilder: (context, index) { final team = _teams[index]; return ListTile( leading: CircleAvatar( backgroundColor: Colors.blue.shade700, child: Text('${index + 1}', style: const TextStyle(color: Colors.white)), ), title: Text('팀 ${team.name} (${team.memberIds.length}명)'), onTap: () { Navigator.of(context).pop(); setState(() { team.memberIds.add(participant.memberId!); }); ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text('${participant.name}님이 팀 ${team.name}에 추가되었습니다.')), ); }, ); }, ), ), actions: [ TextButton( onPressed: () => Navigator.of(context).pop(), child: const Text('취소'), ), ], ), ); } // 이벤트 수정 void _editEvent() { // 이벤트 수정 다이얼로그 또는 화면으로 이동 Navigator.of(context).pop(true); // 수정을 위해 이전 화면으로 돌아가기 } // 참가자 추가 void _addParticipant() { // 참가자 추가 다이얼로그 표시 showDialog( context: context, builder: (context) => AlertDialog( title: const Text('참가자 추가'), content: const Text('참가자 추가 기능은 아직 구현 중입니다.'), actions: [ TextButton( onPressed: () => Navigator.of(context).pop(), child: const Text('확인'), ), ], ), ); } // 참가자 수정 void _editParticipant(Participant participant) { // 참가자 수정 다이얼로그 표시 showDialog( context: context, builder: (context) => AlertDialog( title: const Text('참가자 수정'), content: Text('${participant.name} 참가자 수정 기능은 아직 구현 중입니다.'), actions: [ TextButton( onPressed: () => Navigator.of(context).pop(), child: const Text('확인'), ), ], ), ); } // 참가자 삭제 void _removeParticipant(Participant participant) { // 참가자 삭제 확인 다이얼로그 showDialog( context: context, builder: (context) => AlertDialog( title: const Text('참가자 삭제'), content: Text('${participant.name} 참가자를 정말 삭제하시겠습니까?'), actions: [ TextButton( onPressed: () => Navigator.of(context).pop(), child: const Text('취소'), ), TextButton( onPressed: () async { Navigator.of(context).pop(); setState(() { _isLoading = true; }); try { final eventService = Provider.of(context, listen: false); await eventService.removeParticipant(widget.event.id, participant.id); if (mounted) { setState(() { _participants.removeWhere((p) => p.id == participant.id); _isLoading = false; }); ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('참가자가 삭제되었습니다')), ); } } catch (e) { if (mounted) { setState(() { _isLoading = false; }); ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text('참가자 삭제에 실패했습니다: $e')), ); } } }, style: TextButton.styleFrom(foregroundColor: Colors.red), child: const Text('삭제'), ), ], ), ); } // 참가자 상세 정보 표시 void _showParticipantDetails(Participant participant) { // 참가자 상세 정보 다이얼로그 showDialog( context: context, builder: (context) => AlertDialog( title: Text(participant.name ?? '이름 없음'), content: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ if (participant.email != null) _buildInfoRow(Icons.email, participant.email!), if (participant.phoneNumber != null) _buildInfoRow(Icons.phone, participant.phoneNumber!), _buildInfoRow(Icons.info, '상태: ${participant.status ?? "없음"}'), _buildInfoRow( Icons.payment, '결제: ${participant.isPaid ? "완료" : "미완료"}${participant.paidAmount != null ? " (${participant.paidAmount}원)" : ""}', ), if (participant.notes != null) ...[ const Divider(), const Text('메모:', style: TextStyle(fontWeight: FontWeight.bold)), Text(participant.notes!), ], ], ), actions: [ TextButton( onPressed: () => Navigator.of(context).pop(), child: const Text('닫기'), ), ], ), ); } // 점수 추가 void _addScore() { // 점수 추가 다이얼로그 표시 showDialog( context: context, builder: (context) => AlertDialog( title: const Text('점수 추가'), content: const Text('점수 추가 기능은 아직 구현 중입니다.'), actions: [ TextButton( onPressed: () => Navigator.of(context).pop(), child: const Text('확인'), ), ], ), ); } // 점수 수정 void _editScore(Score score) { // 점수 수정 다이얼로그 표시 showDialog( context: context, builder: (context) => AlertDialog( title: const Text('점수 수정'), content: Text('점수 ID: ${score.id} 수정 기능은 아직 구현 중입니다.'), actions: [ TextButton( onPressed: () => Navigator.of(context).pop(), child: const Text('확인'), ), ], ), ); } // 점수 삭제 void _deleteScore(Score score) { // 점수 삭제 확인 다이얼로그 showDialog( context: context, builder: (context) => AlertDialog( title: const Text('점수 삭제'), content: const Text('이 점수를 정말 삭제하시겠습니까?'), actions: [ TextButton( onPressed: () => Navigator.of(context).pop(), child: const Text('취소'), ), TextButton( onPressed: () async { Navigator.of(context).pop(); setState(() { _isLoading = true; }); try { final eventService = Provider.of(context, listen: false); await eventService.deleteScore(widget.event.id, score.id); if (mounted) { setState(() { _scores.removeWhere((s) => s.id == score.id); _isLoading = false; }); ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('점수가 삭제되었습니다')), ); } } catch (e) { if (mounted) { setState(() { _isLoading = false; }); ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text('점수 삭제에 실패했습니다: $e')), ); } } }, style: TextButton.styleFrom(foregroundColor: Colors.red), child: const Text('삭제'), ), ], ), ); } // 점수 상세 정보 표시 void _showScoreDetails(Score score) { // 참가자 이름 찾기 final participant = _participants.firstWhere( (p) => p.memberId == score.memberId, orElse: () => Participant( id: '', eventId: '', memberId: score.memberId, name: '알 수 없음', ), ); // 점수 상세 정보 다이얼로그 showDialog( context: context, builder: (context) => AlertDialog( title: Text('${participant.name} 점수'), content: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ _buildInfoRow(Icons.score, '총점: ${score.totalScore}'), _buildInfoRow( Icons.calendar_today, '날짜: ${DateFormat('yyyy-MM-dd').format(score.date)}', ), const Divider(), const Text('프레임별 점수:', style: TextStyle(fontWeight: FontWeight.bold)), const SizedBox(height: 8), Wrap( spacing: 8, runSpacing: 8, children: score.frames.asMap().entries.map((entry) { return Container( width: 40, height: 40, decoration: BoxDecoration( border: Border.all(color: Colors.blue), borderRadius: BorderRadius.circular(4), ), child: Center( child: Text( entry.value.toString(), style: const TextStyle( fontSize: 16, fontWeight: FontWeight.bold, ), ), ), ); }).toList(), ), if (score.notes != null) ...[ const Divider(), const Text('메모:', style: TextStyle(fontWeight: FontWeight.bold)), Text(score.notes ?? ''), ], ], ), actions: [ TextButton( onPressed: () => Navigator.of(context).pop(), child: const Text('닫기'), ), ], ), ); } // 이벤트 공유 기능 void _shareEvent() { // 공유할 내용 구성 final String eventTitle = widget.event.title; final String eventType = widget.event.type ?? '기타'; final String eventDate = DateFormat('yyyy-MM-dd HH:mm').format(widget.event.startDate); final String eventLocation = widget.event.location ?? '장소 미정'; // 공개 URL 생성 String shareUrl = ''; if (widget.event.publicHash != null && widget.event.publicHash!.isNotEmpty) { shareUrl = 'https://bowling.example.com/events/${widget.event.publicHash}'; } // 공유 메시지 구성 final String shareText = ''' [볼링 이벤트 초대] $eventTitle 유형: $eventType 일시: $eventDate 장소: $eventLocation 참가자: ${_participants.length}명 ${shareUrl.isNotEmpty ? '참가 링크: $shareUrl' : ''} ${widget.event.accessPassword != null && widget.event.accessPassword!.isNotEmpty ? '비밀번호: ${widget.event.accessPassword}' : ''} '''; // 공유 다이얼로그 표시 Share.share(shareText, subject: '볼링 이벤트: $eventTitle'); } // 이벤트 알림 설정 기능 Future _setEventReminders() async { final notificationService = NotificationService(); // 알림 권한 확인 final hasPermission = await notificationService.requestPermission(); if (!hasPermission) { if (mounted) { ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('알림 권한이 없습니다. 설정에서 권한을 허용해주세요.')), ); } return; } // 알림 설정 다이얼로그 표시 if (!mounted) return; showDialog( context: context, builder: (context) => AlertDialog( title: const Text('이벤트 알림 설정'), content: Column( mainAxisSize: MainAxisSize.min, children: [ ListTile( leading: const Icon(Icons.notifications_active), title: const Text('이벤트 시작 알림'), subtitle: Text('${DateFormat('yyyy-MM-dd HH:mm').format(widget.event.startDate)} 1시간 전'), onTap: () async { Navigator.of(context).pop(); await notificationService.scheduleEventStartReminder(widget.event); if (mounted) { ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('이벤트 시작 알림이 설정되었습니다')), ); } }, ), if (widget.event.registrationDeadline != null) ListTile( leading: const Icon(Icons.timer), title: const Text('등록 마감 알림'), subtitle: Text('${DateFormat('yyyy-MM-dd HH:mm').format(widget.event.registrationDeadline!)} 1일 전'), onTap: () async { Navigator.of(context).pop(); await notificationService.scheduleRegistrationDeadlineReminder(widget.event); if (mounted) { ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('등록 마감 알림이 설정되었습니다')), ); } }, ), ListTile( leading: const Icon(Icons.notifications_off), title: const Text('알림 취소'), subtitle: const Text('이 이벤트에 대한 모든 알림 취소'), onTap: () async { Navigator.of(context).pop(); await notificationService.cancelEventNotifications(widget.event.id); if (mounted) { ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('이벤트 알림이 취소되었습니다')), ); } }, ), ], ), actions: [ TextButton( onPressed: () => Navigator.of(context).pop(), child: const Text('닫기'), ), ], ), ); } }