Files
bowlingManager/mobile/lib/screens/club/event_details_screen.dart
T

2479 lines
93 KiB
Dart

import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:intl/intl.dart';
import 'package:share_plus/share_plus.dart';
import '../../widgets/dialog_actions.dart';
import '../../models/club_model.dart';
import '../../models/event_model.dart';
import '../../models/member_model.dart';
import '../../models/participant_model.dart';
import '../../models/score_model.dart';
import '../../models/team_model.dart';
import '../../models/tie_breaker_option.dart';
import '../../services/club_service.dart';
import '../../services/event_service.dart';
import '../../services/member_service.dart';
import '../../services/notification_service.dart';
import '../../utils/tie_breaker_util.dart';
import '../../utils/url_utils.dart';
import '../../widgets/loading_indicator.dart';
import '../../utils/enum_mappings.dart';
import 'participant_form_screen.dart';
import 'score_form_screen.dart';
import 'team_generator_screen.dart';
import '../../theme/badges.dart';
class EventDetailsScreen extends StatefulWidget {
final Event event;
const EventDetailsScreen({
Key? key,
required this.event,
}) : super(key: key);
@override
State<EventDetailsScreen> createState() => _EventDetailsScreenState();
}
class _EventDetailsScreenState extends State<EventDetailsScreen> with SingleTickerProviderStateMixin {
late TabController _tabController;
List<Participant> _participants = [];
List<Score> _scores = [];
List<Team> _teams = [];
List<Member> _members = [];
// 클럽 전체 회원 목록 (빠른추가 드롭다운에 사용)
List<Member> _clubMembers = [];
Club? _club;
bool _isLoading = true;
int _teamGenerationMethod = 1; // 1: 팀 인원수로 나누기, 2: 팀 개수로 나누기
final TextEditingController _teamSizeController = TextEditingController(text: '4');
final TextEditingController _teamCountController = TextEditingController(text: '2');
bool _showTeamTab = false;
bool _includeHandicap = true; // 핸디캡 포함 여부
// 참가자 필터/검색 상태
String? _participantFilterMemberType; // null: 전체
String? _participantFilterStatus; // null: 전체
bool? _participantFilterPaid; // null: 전체, true: 결제완료, false: 미결제
final TextEditingController _participantSearchController = TextEditingController();
// 참가자 빠른추가 상태
String? _quickAddSelectedMemberId;
bool _quickAddLoading = false;
bool _clubMembersLoading = false;
String? _clubMembersError;
VoidCallback? _memberServiceListener;
MemberService? _memberServiceRef;
@override
void initState() {
super.initState();
// 테스트를 위해 팀 탭 항상 표시
_showTeamTab = true;
// 탭 컨트롤러 길이 동적 설정
_tabController = TabController(length: _showTeamTab ? 4 : 3, vsync: this);
// 탭 전환 시 FAB 등 상단 Scaffold 요소가 즉시 갱신되도록 리스너 추가
_tabController.addListener(() {
if (!mounted) return;
// index 변화 시 재빌드하여 floatingActionButton을 갱신
setState(() {});
});
// 프레임 이후 Provider 접근 및 MemberService 구독 설정
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
final memberService = Provider.of<MemberService>(context, listen: false);
_memberServiceRef = memberService;
// 초기 동기화
setState(() {
_clubMembers = memberService.members;
_clubMembersLoading = memberService.isLoading;
_clubMembersError = memberService.lastError;
});
// 리스너 등록: 회원 목록/로딩 상태 변화 시 동기화
_memberServiceListener = () {
if (!mounted) return;
setState(() {
_clubMembers = memberService.members;
_clubMembersLoading = memberService.isLoading;
_clubMembersError = memberService.lastError;
});
};
memberService.addListener(_memberServiceListener!);
// 이벤트 상세 로드
_loadEventDetails();
});
}
Future<void> _duplicateEvent() async {
final messenger = ScaffoldMessenger.of(context);
try {
final eventService = Provider.of<EventService>(context, listen: false);
// cloneEvent에 필요한 clubId 보장
eventService.setClubId(widget.event.clubId);
await eventService.cloneEvent(widget.event.id);
if (!mounted) return;
messenger.showSnackBar(const SnackBar(content: Text('이벤트가 복제되었습니다')));
// 목록 화면에서 새로고침할 수 있도록 결과 전달
Navigator.of(context).pop(true);
} catch (e) {
messenger.showSnackBar(SnackBar(content: Text('이벤트 복제에 실패했습니다: $e')));
}
}
@override
void dispose() {
// MemberService 리스너 해제: dispose 시점의 BuildContext 사용을 피하기 위해 보관한 ref 사용
if (_memberServiceListener != null && _memberServiceRef != null) {
try {
_memberServiceRef!.removeListener(_memberServiceListener!);
} catch (_) {}
_memberServiceListener = null;
}
_tabController.dispose();
_teamSizeController.dispose();
_teamCountController.dispose();
_participantSearchController.dispose();
super.dispose();
}
// 게스트 사전입력 모달 열기
Future<void> _openGuestModal() async {
// await 이전에 필요한 의존성/서비스를 캡처
final messenger = ScaffoldMessenger.of(context);
final eventService = Provider.of<EventService>(context, listen: false);
final memberService = Provider.of<MemberService>(context, listen: false);
final nameController = TextEditingController();
String gender = 'male';
final phoneController = TextEditingController();
final emailController = TextEditingController();
final handicapController = TextEditingController();
String participantStatus = 'pending';
String paymentStatus = 'unpaid';
final commentController = TextEditingController();
final result = await showModalBottomSheet<bool>(
context: context,
isScrollControlled: true,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
),
builder: (ctx) {
return Padding(
padding: EdgeInsets.only(
bottom: MediaQuery.of(ctx).viewInsets.bottom,
left: 16,
right: 16,
top: 16,
),
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
const Text('게스트 정보 입력', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16)),
const SizedBox(height: 12),
TextField(
controller: nameController,
decoration: const InputDecoration(labelText: '이름(선택)', border: OutlineInputBorder(), prefixIcon: Icon(Icons.person)),
),
const SizedBox(height: 8),
Row(
children: [
Expanded(
child: DropdownButtonFormField<String>(
key: const Key('event_details_guest_gender_dropdown'),
value: gender,
decoration: const InputDecoration(labelText: '성별', border: OutlineInputBorder(), prefixIcon: Icon(Icons.wc)),
isExpanded: true,
items: [
DropdownMenuItem<String>(value: 'male', child: Text('남', maxLines: 1, overflow: TextOverflow.ellipsis)),
DropdownMenuItem<String>(value: 'female', child: Text('여', maxLines: 1, overflow: TextOverflow.ellipsis)),
],
onChanged: (v) => gender = v ?? 'male',
),
),
const SizedBox(width: 8),
Expanded(
child: TextField(
controller: handicapController,
decoration: const InputDecoration(labelText: '핸디캡(선택)', border: OutlineInputBorder(), prefixIcon: Icon(Icons.calculate)),
keyboardType: TextInputType.number,
inputFormatters: [FilteringTextInputFormatter.digitsOnly],
),
),
],
),
const SizedBox(height: 8),
Row(
children: [
Expanded(
child: TextField(
controller: phoneController,
decoration: const InputDecoration(labelText: '전화(선택)', border: OutlineInputBorder(), prefixIcon: Icon(Icons.phone)),
keyboardType: TextInputType.phone,
),
),
const SizedBox(width: 8),
Expanded(
child: TextField(
controller: emailController,
decoration: const InputDecoration(labelText: '이메일(선택)', border: OutlineInputBorder(), prefixIcon: Icon(Icons.email)),
keyboardType: TextInputType.emailAddress,
),
),
],
),
const SizedBox(height: 12),
const Text('참가 정보', style: TextStyle(fontWeight: FontWeight.bold)),
const SizedBox(height: 8),
Row(
children: [
Expanded(
child: DropdownButtonFormField<String>(
key: const Key('event_details_participant_status_dropdown'),
value: (participantStatusOptions.keys.contains(participantStatus)) ? participantStatus : null,
decoration: const InputDecoration(labelText: '상태', border: OutlineInputBorder(), prefixIcon: Icon(Icons.verified_user)),
isExpanded: true,
items: participantStatusOptions.entries.map((e) => DropdownMenuItem<String>(
value: e.key,
child: Text(e.value, maxLines: 1, overflow: TextOverflow.ellipsis),
)).toList(),
onChanged: (v) => participantStatus = v ?? 'pending',
),
),
const SizedBox(width: 8),
Expanded(
child: DropdownButtonFormField<String>(
key: const Key('event_details_payment_status_dropdown'),
value: (paymentStatusOptions.keys.contains(paymentStatus)) ? paymentStatus : null,
decoration: const InputDecoration(labelText: '결제', border: OutlineInputBorder(), prefixIcon: Icon(Icons.payment)),
isExpanded: true,
items: paymentStatusOptions.entries.map((e) => DropdownMenuItem<String>(
value: e.key,
child: Text(e.value, maxLines: 1, overflow: TextOverflow.ellipsis),
)).toList(),
onChanged: (v) => paymentStatus = v ?? 'unpaid',
),
),
],
),
const SizedBox(height: 8),
TextField(
controller: commentController,
decoration: const InputDecoration(labelText: '비고(선택)', border: OutlineInputBorder(), prefixIcon: Icon(Icons.notes)),
maxLines: 2,
),
const SizedBox(height: 12),
Row(
children: [
Expanded(
child: OutlinedButton(
onPressed: () => Navigator.of(ctx).pop(false),
child: const Text('취소'),
),
),
const SizedBox(width: 8),
Expanded(
child: ElevatedButton.icon(
icon: const Icon(Icons.save),
onPressed: () => Navigator.of(ctx).pop(true),
label: const Text('저장 후 추가'),
),
),
],
),
const SizedBox(height: 8),
],
),
),
);
},
);
if (result != true) return;
// 저장 처리: 입력값 기반으로 회원 생성 후 참가자 추가
setState(() => _quickAddLoading = true);
try {
final Map<String, dynamic> memberPayload = {
'name': (nameController.text.trim().isEmpty) ? '게스트' : nameController.text.trim(),
'gender': gender, // 백엔드 필수
'memberType': 'guest',
'status': 'active',
};
if (phoneController.text.trim().isNotEmpty) memberPayload['phone'] = phoneController.text.trim();
if (emailController.text.trim().isNotEmpty) memberPayload['email'] = emailController.text.trim();
if (handicapController.text.trim().isNotEmpty) {
final parsed = int.tryParse(handicapController.text.trim());
if (parsed != null) memberPayload['handicap'] = parsed;
}
final guestMember = await memberService.addMember(memberPayload);
final Map<String, dynamic> participantPayload = {
'memberId': guestMember.id,
// 드롭다운과 백엔드 허용값 정합성: enum 키 사용 (pending/confirmed/canceled)
'status': participantStatus,
'paymentStatus': paymentStatus,
};
if (commentController.text.trim().isNotEmpty) participantPayload['comment'] = commentController.text.trim();
final newParticipant = await eventService.addParticipant(widget.event.id, participantPayload);
if (!mounted) return;
setState(() {
_participants.add(newParticipant);
});
messenger.showSnackBar(const SnackBar(content: Text('게스트를 추가했습니다.')));
} catch (e) {
messenger.showSnackBar(SnackBar(content: Text('게스트 추가 실패: $e')));
} finally {
if (mounted) {
setState(() => _quickAddLoading = false);
}
}
}
Future<void> _loadEventDetails() async {
setState(() {
_isLoading = true;
});
try {
final eventService = Provider.of<EventService>(context, listen: false);
final clubService = Provider.of<ClubService>(context, listen: false);
final memberService = Provider.of<MemberService>(context, listen: false);
// EventService가 clubId 없을 경우 참가자/점수/참가자 추가 등에서 인증/클럽 정보 오류가 발생하므로
// 화면 진입 시점의 이벤트 clubId를 주입하여 안정화한다.
eventService.setClubId(widget.event.clubId);
// MemberService도 clubId가 필요하므로 함께 주입한다.
await memberService.setClubId(widget.event.clubId);
// 참가자 목록 로드
final participants = await eventService.fetchEventParticipants(widget.event.id);
// 점수 목록 로드
final scores = await eventService.fetchEventScores(widget.event.id);
// 클럽 정보 로드
final club = await clubService.fetchClub(widget.event.clubId);
// 회원 정보 로드 (동점자 처리 시 생년월일 사용)
final memberIds = participants.map((p) => p.memberId).toList();
final members = await memberService.fetchMembersByIds(widget.event.clubId, memberIds);
// 빠른추가용 클럽 전체 회원 목록 로드 (MemberService 리스너로 동기화되므로 별도 setState 없이 호출만)
await memberService.fetchClubMembers();
// 팀 목록 로드 (선택적)
List<Team> teams = [];
try {
teams = await eventService.fetchEventTeams(widget.event.id);
} catch (e) {
// 팀 기능이 없거나 오류 발생 시 무시
if (kDebugMode) {
debugPrint('팀 로드 실패: $e');
}
}
if (mounted) {
setState(() {
_participants = participants;
_scores = scores;
_teams = teams;
_club = club;
_members = members;
_showTeamTab = true; // 테스트를 위해 팀 탭 항상 표시
_isLoading = false;
});
}
} catch (e) {
if (mounted) {
setState(() {
_isLoading = false;
});
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('이벤트 정보를 불러오는데 실패했습니다: $e')),
);
}
}
}
Future<void> _reloadClubMembers() async {
try {
setState(() => _clubMembersLoading = true);
final memberService = Provider.of<MemberService>(context, listen: false);
await memberService.fetchClubMembers();
if (!mounted) return;
setState(() {
_clubMembers = memberService.members;
_clubMembersLoading = false;
_clubMembersError = memberService.lastError;
});
} catch (e) {
if (!mounted) return;
setState(() {
_clubMembersLoading = false;
_clubMembersError = e.toString();
});
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('회원 목록을 불러오지 못했습니다: $e')),
);
}
}
// 이벤트 공유 기능
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 = UrlUtils.getEventPublicUrl(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는 deprecated)
SharePlus.instance.share(
ShareParams(
text: shareText,
subject: '볼링 이벤트: $eventTitle',
),
);
}
// 공통 배지 위젯 빌더
Widget _buildBadge({
required String text,
required Color color,
required IconData icon,
}) {
return Chip(
avatar: Icon(
icon,
color: Theme.of(context).colorScheme.onPrimary,
size: 18,
),
label: Text(
text,
style: TextStyle(
color: Theme.of(context).colorScheme.onPrimary,
fontWeight: FontWeight.w600,
),
),
backgroundColor: color,
padding: const EdgeInsets.symmetric(horizontal: 8),
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
visualDensity: VisualDensity.compact,
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
widget.event.title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
actions: [
IconButton(
icon: const Icon(Icons.copy),
tooltip: '복제',
onPressed: _duplicateEvent,
),
],
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: [
Expanded(
child: Wrap(
spacing: 8,
runSpacing: 4,
children: [
_buildBadge(
text: widget.event.type ?? '기타',
color: _getTypeColor(widget.event.type ?? '기타'),
icon: _getTypeIcon(widget.event.type ?? '기타'),
),
if (widget.event.status != null)
BadgeStyles.eventStatus(widget.event.status!),
],
),
),
// 공유 버튼 추가
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,
UrlUtils.getEventPublicUrl(widget.event.publicHash!),
isSelectable: true,
),
),
IconButton(
icon: const Icon(Icons.copy),
onPressed: () {
final publicUrl = UrlUtils.getEventPublicUrl(widget.event.publicHash!);
UrlUtils.copyUrlToClipboard(context, publicUrl);
},
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}명',
),
// 알림 설정 버튼
const SizedBox(height: 24),
ElevatedButton.icon(
onPressed: _setEventReminders,
icon: const Icon(Icons.notifications_active),
label: const Text('알림 설정'),
style: ElevatedButton.styleFrom(
foregroundColor: Colors.white,
backgroundColor: Colors.green,
minimumSize: const Size(double.infinity, 48),
),
),
],
),
);
}
String _buildParticipantFilterSummary() {
final List<String> parts = [];
// 상태(선택된 경우에만 표시)
if (_participantFilterStatus != null && _participantFilterStatus!.isNotEmpty) {
parts.add('상태: ${_participantFilterStatus!}');
}
// 회원 유형(선택된 경우에만 표시)
if (_participantFilterMemberType != null && _participantFilterMemberType!.isNotEmpty) {
parts.add('유형: ${_participantFilterMemberType!}');
}
// 결제 상태(선택된 경우에만 표시)
if (_participantFilterPaid != null) {
parts.add('결제: ${_participantFilterPaid! ? '완료' : '미결제'}');
}
// 검색어(입력된 경우에만 표시)
final q = _participantSearchController.text.trim();
if (q.isNotEmpty) {
parts.add("검색: '$q'");
}
if (parts.isEmpty) {
return '필터 없음';
}
return parts.join(' · ');
}
bool _hasActiveParticipantFilters() {
return (_participantFilterStatus != null && _participantFilterStatus!.isNotEmpty) ||
(_participantFilterMemberType != null && _participantFilterMemberType!.isNotEmpty) ||
(_participantFilterPaid != null) ||
(_participantSearchController.text.trim().isNotEmpty);
}
// 참가자 탭
Widget _buildParticipantsTab() {
// 빠른추가용 드롭다운 후보: 아직 참가자가 아닌 회원만
final existingMemberIds = _participants.map((p) => p.memberId).whereType<String>().toSet();
final quickAddCandidates = _clubMembers
.where((m) => !existingMemberIds.contains(m.id))
.toList()
..sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()));
final candidateIds = quickAddCandidates.map((m) => m.id).toSet();
final String? safeSelectedMemberId =
(_quickAddSelectedMemberId != null && candidateIds.contains(_quickAddSelectedMemberId))
? _quickAddSelectedMemberId
: null;
// 필터 옵션 집계
final Set<String> memberTypeOptions = _participants
.where((p) => (p.memberType ?? '').isNotEmpty)
.map((p) => p.memberType!)
.toSet();
final Set<String> statusOptions = _participants
.where((p) => (p.status ?? '').isNotEmpty)
.map((p) => p.status!)
.toSet();
// 필터/검색 적용된 목록
final List<Participant> filtered = _participants.where((p) {
final matchesType = _participantFilterMemberType == null || (_participantFilterMemberType!.isEmpty) || p.memberType == _participantFilterMemberType;
final matchesStatus = _participantFilterStatus == null || (_participantFilterStatus!.isEmpty) || p.status == _participantFilterStatus;
final matchesPaid = _participantFilterPaid == null || p.isPaid == _participantFilterPaid;
final query = _participantSearchController.text.trim().toLowerCase();
final matchesQuery = query.isEmpty || (p.name ?? '').toLowerCase().contains(query);
return matchesType && matchesStatus && matchesPaid && matchesQuery;
}).toList();
return ListView.builder(
itemCount: filtered.length + 1,
itemBuilder: (context, index) {
if (index == 0) {
// 필터/검색 바 UI
return Padding(
padding: const EdgeInsets.fromLTRB(12, 8, 12, 4),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// 참가자 빠른추가 영역
Card(
color: Colors.orange.shade50,
child: Padding(
padding: const EdgeInsets.all(12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text('참가자 빠른추가', style: TextStyle(fontWeight: FontWeight.bold)),
const SizedBox(height: 8),
if (_clubMembersLoading) ...[
Row(
key: const Key('club_members_loading_row'),
children: const [
SizedBox(
key: Key('club_members_loading_spinner'),
width: 18,
height: 18,
child: CircularProgressIndicator(strokeWidth: 2)),
SizedBox(width: 8),
Text('회원 목록을 불러오는 중...', key: Key('club_members_loading_text')),
],
),
const SizedBox(height: 8),
] else if (_clubMembersError != null && _clubMembersError!.isNotEmpty) ...[
Row(
key: const Key('club_members_error_row'),
children: [
const Icon(Icons.error_outline, color: Colors.red),
const SizedBox(width: 8),
Expanded(child: Text('회원 목록 오류: ${_clubMembersError!}', key: const Key('club_members_error_text'))),
TextButton.icon(
key: const Key('club_members_retry_button'),
onPressed: _reloadClubMembers,
icon: const Icon(Icons.refresh),
label: const Text('재시도'),
)
],
),
const SizedBox(height: 8),
] else if (quickAddCandidates.isEmpty) ...[
Row(
key: const Key('club_members_empty_row'),
children: const [
Icon(Icons.info_outline, color: Colors.grey),
SizedBox(width: 8),
Expanded(child: Text('추가 가능한 회원이 없습니다.', key: Key('club_members_empty_text'))),
],
),
const SizedBox(height: 8),
],
Row(
children: [
// 회원 선택 드롭다운
Expanded(
child: DropdownButtonFormField<String>(
value: safeSelectedMemberId,
isExpanded: true,
decoration: const InputDecoration(
labelText: '회원 선택',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.person_search),
),
items: quickAddCandidates.map((m) {
return DropdownMenuItem<String>(
value: m.id,
child: Text(
m.name,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
);
}).toList(),
onChanged: _clubMembersLoading ? null : (val) => setState(() => _quickAddSelectedMemberId = val),
),
),
const SizedBox(width: 8),
// 재조회 버튼
IconButton(
tooltip: '회원 목록 새로고침',
onPressed: _clubMembersLoading ? null : _reloadClubMembers,
icon: _clubMembersLoading
? const SizedBox(width: 18, height: 18, child: CircularProgressIndicator(strokeWidth: 2))
: const Icon(Icons.refresh),
),
const SizedBox(width: 4),
ElevatedButton.icon(
onPressed: (_quickAddLoading || _quickAddSelectedMemberId == null)
? null
: _quickAddMember,
icon: _quickAddLoading
? const SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2))
: const Icon(Icons.person_add),
label: const Text('추가'),
style: ElevatedButton.styleFrom(minimumSize: const Size(90, 48)),
),
],
),
const SizedBox(height: 8),
Align(
alignment: Alignment.centerRight,
child: OutlinedButton.icon(
key: const Key('guest_preinput_button'),
onPressed: _quickAddLoading ? null : _openGuestModal,
icon: const Icon(Icons.group_add),
label: const Text('게스트 추가'),
),
)
],
),
),
),
ExpansionTile(
initiallyExpanded: false,
leading: Icon(
Icons.filter_list,
color: _hasActiveParticipantFilters() ? Theme.of(context).colorScheme.primary : null,
),
title: Text(
'필터/검색',
style: TextStyle(
color: _hasActiveParticipantFilters() ? Theme.of(context).colorScheme.primary : null,
fontWeight: _hasActiveParticipantFilters() ? FontWeight.w600 : FontWeight.w500,
),
),
subtitle: Text(
_buildParticipantFilterSummary(),
style: TextStyle(color: _hasActiveParticipantFilters() ? Colors.black87 : Colors.black54),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
childrenPadding: const EdgeInsets.only(bottom: 8, left: 8, right: 8),
children: [
// 검색 필드
TextField(
controller: _participantSearchController,
decoration: InputDecoration(
hintText: '이름 검색',
prefixIcon: const Icon(Icons.search),
suffixIcon: _participantSearchController.text.isNotEmpty
? IconButton(
icon: const Icon(Icons.clear),
onPressed: () {
setState(() {
_participantSearchController.clear();
});
},
tooltip: '검색 지우기',
)
: null,
border: const OutlineInputBorder(),
),
onChanged: (_) => setState(() {}),
),
const SizedBox(height: 8),
// 상태/유형/결제 필터
Wrap(
spacing: 8,
runSpacing: 4,
children: [
// 참가 상태 필터
FilterChip(
selected: _participantFilterStatus == null,
label: const Text('상태: 전체'),
onSelected: (_) {
setState(() => _participantFilterStatus = null);
},
),
...statusOptions.map((s) => FilterChip(
selected: _participantFilterStatus == s,
label: Text('상태: $s'),
onSelected: (_) {
setState(() => _participantFilterStatus = s);
},
)),
// 회원 유형 필터
FilterChip(
selected: _participantFilterMemberType == null,
label: const Text('유형: 전체'),
onSelected: (_) {
setState(() => _participantFilterMemberType = null);
},
),
...memberTypeOptions.map((t) => FilterChip(
selected: _participantFilterMemberType == t,
label: Text('유형: $t'),
onSelected: (_) {
setState(() => _participantFilterMemberType = t);
},
)),
// 결제 필터
FilterChip(
selected: _participantFilterPaid == null,
label: const Text('결제: 전체'),
onSelected: (_) {
setState(() => _participantFilterPaid = null);
},
),
FilterChip(
selected: _participantFilterPaid == true,
label: const Text('결제: 완료'),
onSelected: (_) {
setState(() => _participantFilterPaid = true);
},
),
FilterChip(
selected: _participantFilterPaid == false,
label: const Text('결제: 미결제'),
onSelected: (_) {
setState(() => _participantFilterPaid = false);
},
),
// 초기화
ActionChip(
label: const Text('필터 초기화'),
avatar: const Icon(Icons.refresh, size: 16),
onPressed: () {
setState(() {
_participantFilterMemberType = null;
_participantFilterStatus = null;
_participantFilterPaid = null;
_participantSearchController.clear();
});
},
),
],
),
],
),
const SizedBox(height: 8),
Text('표시: ${filtered.length} / 전체 ${_participants.length}명', style: const TextStyle(fontSize: 12, color: Colors.black54)),
const Divider(height: 16),
],
),
);
}
final participant = filtered[index - 1];
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),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
subtitle: Wrap(
spacing: 4,
runSpacing: 4,
children: [
// 회원 유형 뱃지
if (participant.memberType != null && participant.memberType!.isNotEmpty)
Container(
margin: const EdgeInsets.only(right: 4),
child: BadgeStyles.memberType(participant.memberType!),
),
// 참가 상태 뱃지
if (participant.status != null)
Container(
margin: const EdgeInsets.only(right: 4),
child: BadgeStyles.participantStatus(participant.status!),
),
// 결제 상태 뱃지
Container(
margin: const EdgeInsets.only(right: 0),
child: BadgeStyles.payment(participant.isPaid),
),
],
),
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),
),
);
},
);
}
// 회원 선택 빠른추가 처리
Future<void> _quickAddMember() async {
if (_quickAddSelectedMemberId == null) return;
setState(() => _quickAddLoading = true);
try {
final eventService = Provider.of<EventService>(context, listen: false);
// 서버에는 상태를 영문 표준값으로 전송
final newParticipant = await eventService.addParticipant(
widget.event.id,
{
'memberId': _quickAddSelectedMemberId,
'status': 'confirmed',
// 백엔드 모델 ENUM은 'unpaid'|'paid' 이므로 기본 미납을 명시
'paymentStatus': 'unpaid',
},
);
if (!mounted) return;
setState(() {
_participants.add(newParticipant);
_quickAddSelectedMemberId = null;
});
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('참가자를 추가했습니다.')),
);
} catch (e) {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('참가자 추가 실패: $e')),
);
} finally {
if (mounted) {
setState(() => _quickAddLoading = false);
}
}
}
// 점수 탭
Widget _buildScoresTab() {
if (_scores.isEmpty) {
return const Center(
child: Text('등록된 점수가 없습니다.'),
);
}
// 동점자 처리 옵션 가져오기
List<TieBreakerOption>? tieBreakerOptions;
if (_club != null && _club!.tieBreakerOptions != null && _club!.tieBreakerOptions!.isNotEmpty) {
tieBreakerOptions = _club!.tieBreakerOptions;
}
// TieBreakerUtil을 사용하여 점수 정렬 및 순위 계산
final sortedScores = TieBreakerUtil.sortScoresByOptions(
_scores,
tieBreakerOptions,
_members,
_includeHandicap
);
// 순위 계산
final ranks = TieBreakerUtil.calculateRanks(sortedScores, _includeHandicap);
// 평균 점수 계산
final totalScoreSum = sortedScores.fold<int>(0, (sum, score) =>
sum + ((_includeHandicap) ? score.totalScore + (score.handicap ?? 0) : score.totalScore));
final averageScore = sortedScores.isNotEmpty ? totalScoreSum / sortedScores.length : 0;
// 최고/최저 점수 계산
final int? maxScore = sortedScores.isNotEmpty
? sortedScores.map((s) => (_includeHandicap ? s.totalScore + (s.handicap ?? 0) : s.totalScore)).reduce((a, b) => a > b ? a : b)
: null;
final int? minScore = sortedScores.isNotEmpty
? sortedScores.map((s) => (_includeHandicap ? s.totalScore + (s.handicap ?? 0) : s.totalScore)).reduce((a, b) => a < b ? a : b)
: null;
return Column(
children: [
// 요약 카드
Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 0),
child: Row(
children: [
Expanded(
child: Card(
color: Colors.blue.shade50,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
child: Row(
children: [
const Icon(Icons.analytics, color: Colors.blue),
const SizedBox(width: 8),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text('평균', style: TextStyle(fontSize: 12, color: Colors.black54)),
Text(averageScore.toStringAsFixed(1), style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
],
),
],
),
),
),
),
const SizedBox(width: 8),
Expanded(
child: Card(
color: Colors.green.shade50,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
child: Row(
children: [
const Icon(Icons.trending_up, color: Colors.green),
const SizedBox(width: 8),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text('최고', style: TextStyle(fontSize: 12, color: Colors.black54)),
Text(maxScore?.toString() ?? '-', style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
],
),
],
),
),
),
),
const SizedBox(width: 8),
Expanded(
child: Card(
color: Colors.red.shade50,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
child: Row(
children: [
const Icon(Icons.trending_down, color: Colors.red),
const SizedBox(width: 8),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text('최저', style: TextStyle(fontSize: 12, color: Colors.black54)),
Text(minScore?.toString() ?? '-', style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
],
),
],
),
),
),
),
],
),
),
const SizedBox(height: 8),
// 핸디캡 포함 여부 토글
Container(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text('핸디캡 포함:', style: TextStyle(fontWeight: FontWeight.bold)),
Switch(
value: _includeHandicap,
onChanged: (value) {
setState(() {
_includeHandicap = value;
});
},
activeColor: Colors.blue,
),
],
),
),
// 평균 점수 표시
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),
),
],
),
),
// 동점자 처리 옵션 표시
if (tieBreakerOptions != null && tieBreakerOptions.isNotEmpty)
Container(
padding: const EdgeInsets.all(8),
margin: const EdgeInsets.symmetric(horizontal: 8),
decoration: BoxDecoration(
color: Colors.green.shade50,
borderRadius: BorderRadius.circular(8),
border: Border.all(color: Colors.green.shade200),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'동점자 처리 우선순위:',
style: TextStyle(fontWeight: FontWeight.bold),
),
const SizedBox(height: 4),
Wrap(
spacing: 8,
children: tieBreakerOptions.map((option) {
String optionText = '';
switch (option) {
case TieBreakerOption.lowerHandicap:
optionText = '핸디캡 낮은 순';
break;
case TieBreakerOption.lowerScoreGap:
optionText = '점수 격차 작은 순';
break;
case TieBreakerOption.olderAge:
optionText = '연장자 우선';
break;
case TieBreakerOption.none:
optionText = '없음';
break;
}
return Chip(
label: Text(optionText),
backgroundColor: Colors.green.shade100,
);
}).toList(),
),
],
),
),
// 점수 목록
Expanded(
child: ListView.builder(
itemCount: sortedScores.length,
itemBuilder: (context, index) {
final score = sortedScores[index];
final rank = ranks[score.id] ?? (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: Stack(
children: [
// 배경 원
Container(
width: 40,
height: 40,
decoration: BoxDecoration(
color: _getRankColor(rank),
shape: BoxShape.circle,
),
),
// 순위 텍스트
Container(
width: 40,
height: 40,
alignment: Alignment.center,
child: Text(
rank.toString(),
key: Key('rank_${rank}_text'),
style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
),
),
// 테스트를 위한 추가 텍스트 (투명)
Positioned(
left: 0,
right: 0,
top: 0,
child: Text(
rank.toString(),
textAlign: TextAlign.center,
style: const TextStyle(color: Colors.transparent),
),
),
],
),
title: Row(
children: [
Expanded(
child: Text(
participant.name ?? '알 수 없음',
style: const TextStyle(fontWeight: FontWeight.bold),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
decoration: BoxDecoration(
color: Colors.blue.shade100,
borderRadius: BorderRadius.circular(12),
),
child: Text(
_includeHandicap
? '총점: ${score.totalScore + (score.handicap ?? 0)} (${score.totalScore}+${score.handicap ?? 0})'
: '총점: ${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(
// 스트라이크는 'X'로, 스페어는 '/'로 표시
_getFrameDisplay(entry.key, entry.value, score.frames),
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),
),
);
},
),
),
],
);
}
// 점수 추가
Future<void> _addScore() async {
final result = await Navigator.of(context).push<bool>(
MaterialPageRoute(
builder: (_) => ScoreFormScreen(
eventId: widget.event.id,
participants: _participants,
),
),
);
if (result == true) {
_loadEventDetails();
if (_tabController.index != 2) {
_tabController.animateTo(2);
}
}
}
// 점수 수정
Future<void> _editScore(Score score) async {
final result = await Navigator.of(context).push<bool>(
MaterialPageRoute(
builder: (_) => ScoreFormScreen(
eventId: widget.event.id,
score: score,
participants: _participants,
),
),
);
if (result == true) {
_loadEventDetails();
if (_tabController.index != 2) {
_tabController.animateTo(2);
}
}
}
// 참가자 상세 정보 다이얼로그
void _showParticipantDetails(Participant participant) {
showDialog(
context: context,
builder: (dialogContext) => AlertDialog(
title: Text(participant.name ?? '이름 없음'),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (participant.memberType != null)
Text('유형: ${participant.memberType}')
else
const SizedBox.shrink(),
if (participant.status != null)
Text('상태: ${participant.status}')
else
const SizedBox.shrink(),
Text('결제: ${participant.isPaid ? '결제완료' : '미결제'}'),
if (participant.notes != null && participant.notes!.isNotEmpty) ...[
const SizedBox(height: 8),
Text('메모: ${participant.notes!}')
],
],
),
actions: DialogActions.confirm(
onCancel: () => Navigator.of(dialogContext).pop(),
onConfirm: () => Navigator.of(dialogContext).pop(),
confirmText: '확인',
),
),
);
}
// 팀 탭
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<int>(
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<int>(
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: _isLoading ? null : _generateTeams,
icon: _isLoading
? const SizedBox(
width: 16,
height: 16,
child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white),
)
: const Icon(Icons.group_add),
label: Text(_isLoading ? '생성 중...' : '팀 생성하기'),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.blue,
foregroundColor: Colors.white,
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
),
),
],
),
],
),
),
),
],
),
),
);
}
// 미배정 참가자 목록 조회
final List<Participant> unassignedParticipants = _getUnassignedParticipants();
return Column(
children: [
// 팀 관리 버튼
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
ElevatedButton.icon(
onPressed: _isLoading ? null : _generateTeams,
icon: _isLoading
? const SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white))
: const Icon(Icons.refresh),
label: Text(_isLoading ? '재생성 중...' : '팀 재생성'),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.blue,
foregroundColor: Colors.white,
),
),
ElevatedButton.icon(
onPressed: _isLoading ? null : _saveTeams,
icon: _isLoading
? const SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white))
: const Icon(Icons.save),
label: Text(_isLoading ? '저장 중...' : '팀 저장'),
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: ElevatedButton.icon(
onPressed: _shareEvent,
icon: const Icon(Icons.share),
label: const Text('이벤트 공유'),
style: ElevatedButton.styleFrom(
foregroundColor: Colors.white,
backgroundColor: Colors.blue,
),
),
),
// 미배정 참가자 섹션
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: Wrap(
spacing: 4,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
const Icon(Icons.bar_chart, size: 16, color: Colors.blue),
Text('팀 에버리지: ${teamAverage.toStringAsFixed(1)}'),
],
),
children: [
...teamMembers.map((participant) {
// 참가자의 평균 점수 계산
final participantScores = _scores.where((s) => s.memberId == participant.memberId).toList();
final participantAverage = participantScores.isNotEmpty
? participantScores.fold<int>(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 ?? '알 수 없음',
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
subtitle: Text('평균: ${participantAverage.toStringAsFixed(1)}'),
trailing: IconButton(
icon: const Icon(Icons.remove_circle, color: Colors.red),
tooltip: '팀에서 제외',
onPressed: () => _removeFromTeam(team, participant),
),
);
}),
// 팀원 추가 버튼
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),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
],
),
);
}
// 이벤트 유형에 따른 색상 반환
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;
}
}
// 이벤트 유형 아이콘
IconData _getTypeIcon(String type) {
switch (type.toLowerCase()) {
case '개인전':
case 'individual':
return Icons.person;
case '팀전':
case 'team':
return Icons.groups;
case '리그':
case 'league':
return Icons.leaderboard;
case '토너먼트':
case 'tournament':
return Icons.emoji_events;
default:
return Icons.event;
}
}
// 순위에 따른 색상 반환
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 == 10) {
return Colors.green; // 스트라이크
} else if (score == 0) {
return Colors.red; // 미스
} else {
return Colors.blue; // 일반
}
}
// 프레임 표시 문자열 반환
String _getFrameDisplay(int frameIndex, int score, List<int> frames) {
// 스트라이크 표시
if (score == 10) {
return 'X';
}
// 스페어 표시 (이전 프레임과 합쳐서 10점이면 스페어)
if (frameIndex > 0 && frames[frameIndex - 1] + score == 10) {
return '/';
}
// 일반 점수 표시
return score.toString();
}
// 미배정 참가자 목록 가져오기
List<Participant> _getUnassignedParticipants() {
// 현재 팀에 배정된 모든 참가자 ID 목록
final List<String> assignedMemberIds = [];
for (final team in _teams) {
assignedMemberIds.addAll(team.memberIds);
}
// 배정되지 않은 참가자 목록 반환
return _participants.where((p) => !assignedMemberIds.contains(p.memberId)).toList();
}
// 팀원 목록 가져오기
List<Participant> _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<int>(0, (sum, score) => sum + score.totalScore);
totalAverage += memberTotal / memberScores.length;
memberCount++;
}
}
return memberCount > 0 ? totalAverage / memberCount : 0.0;
}
// 팀 생성/편집 화면으로 이동
void _generateTeams() {
Navigator.of(context)
.push<bool>(
MaterialPageRoute(
builder: (_) => TeamGeneratorScreen(
eventId: widget.event.id,
participants: _participants,
existingTeams: _teams,
),
),
)
.then((result) async {
if (result == true) {
await _loadEventDetails();
if (_showTeamTab && _tabController.index != 3) {
_tabController.animateTo(3);
}
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('팀 구성이 업데이트되었습니다')),
);
}
}
});
}
// 팀 저장
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: DialogActions.confirm(
onCancel: () => Navigator.of(context).pop(),
onConfirm: () => Navigator.of(context).pop(),
confirmText: '닫기',
),
),
);
}
// 참가자를 추가할 팀 선택 다이얼로그 표시
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: DialogActions.confirm(
onCancel: () => Navigator.of(context).pop(),
onConfirm: () => Navigator.of(context).pop(),
confirmText: '닫기',
),
),
);
}
// 이벤트 수정
void _editEvent() {
// 이벤트 수정 다이얼로그 또는 화면으로 이동
Navigator.of(context).pop(true); // 수정을 위해 이전 화면으로 돌아가기
}
// 참가자 추가
void _addParticipant() {
Navigator.of(context)
.push<bool>(
MaterialPageRoute(
builder: (_) => ParticipantFormScreen(
eventId: widget.event.id,
),
),
)
.then((result) {
if (result == true) {
_loadEventDetails();
// 참가자 탭으로 이동 유지
if (_tabController.index != 1) {
_tabController.animateTo(1);
}
}
});
}
// 참가자 수정
void _editParticipant(Participant participant) {
Navigator.of(context)
.push<bool>(
MaterialPageRoute(
builder: (_) => ParticipantFormScreen(
eventId: widget.event.id,
participant: participant,
),
),
)
.then((result) {
if (result == true) {
_loadEventDetails();
if (_tabController.index != 1) {
_tabController.animateTo(1);
}
}
});
}
// 참가자 삭제
void _removeParticipant(Participant participant) {
// 참가자 삭제 확인 다이얼로그
showDialog(
context: context,
builder: (dialogContext) => AlertDialog(
title: const Text('참가자 삭제'),
content: Text('${participant.name} 참가자를 정말 삭제하시겠습니까?'),
actions: DialogActions.confirm(
onCancel: () => Navigator.of(dialogContext).pop(),
onConfirm: () async {
final navigator = Navigator.of(dialogContext);
final messenger = ScaffoldMessenger.of(dialogContext);
final eventService = Provider.of<EventService>(dialogContext, listen: false);
navigator.pop();
setState(() {
_isLoading = true;
});
try {
await eventService.removeParticipant(widget.event.id, participant.id);
if (mounted) {
setState(() {
_participants.removeWhere((p) => p.id == participant.id);
_isLoading = false;
});
messenger.showSnackBar(
const SnackBar(content: Text('참가자가 삭제되었습니다')),
);
}
} catch (e) {
if (mounted) {
setState(() {
_isLoading = false;
});
messenger.showSnackBar(
SnackBar(content: Text('참가자 삭제에 실패했습니다: $e')),
);
}
}
},
destructive: true,
confirmText: '삭제',
),
),
);
}
// 점수 삭제
void _deleteScore(Score score) {
showDialog(
context: context,
builder: (dialogContext) => AlertDialog(
title: const Text('점수 삭제'),
content: const Text('이 점수를 정말 삭제하시겠습니까?'),
actions: DialogActions.confirm(
onCancel: () => Navigator.of(dialogContext).pop(),
onConfirm: () async {
final navigator = Navigator.of(dialogContext);
final messenger = ScaffoldMessenger.of(dialogContext);
final eventService = Provider.of<EventService>(dialogContext, listen: false);
navigator.pop();
setState(() {
_isLoading = true;
});
try {
await eventService.deleteScore(widget.event.id, score.id);
if (mounted) {
setState(() {
_scores.removeWhere((s) => s.id == score.id);
_isLoading = false;
});
messenger.showSnackBar(
const SnackBar(content: Text('점수가 삭제되었습니다')),
);
}
} catch (e) {
if (mounted) {
setState(() {
_isLoading = false;
});
messenger.showSnackBar(
SnackBar(content: Text('점수 삭제에 실패했습니다: $e')),
);
}
}
},
destructive: true,
confirmText: '삭제',
),
),
);
}
// 점수 상세 정보 표시
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('닫기'),
),
],
),
);
}
// 이벤트 알림 설정 기능
Future<void> _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;
// await 이후 컨텍스트 사용 최소화를 위해 messenger 캡처
final messenger = ScaffoldMessenger.of(context);
showDialog(
context: context,
builder: (dialogContext) => 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 {
final navigator = Navigator.of(dialogContext);
navigator.pop();
await notificationService.scheduleEventStartReminder(widget.event);
messenger.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 {
final navigator = Navigator.of(dialogContext);
navigator.pop();
await notificationService.scheduleRegistrationDeadlineReminder(widget.event);
messenger.showSnackBar(
const SnackBar(content: Text('등록 마감 알림이 설정되었습니다')),
);
},
),
ListTile(
leading: const Icon(Icons.notifications_off),
title: const Text('알림 취소'),
subtitle: const Text('이 이벤트에 대한 모든 알림 취소'),
onTap: () async {
final navigator = Navigator.of(dialogContext);
navigator.pop();
await notificationService.cancelEventNotifications(widget.event.id);
messenger.showSnackBar(
const SnackBar(content: Text('이벤트 알림이 취소되었습니다')),
);
},
),
],
),
actions: [
TextButton(
onPressed: () => Navigator.of(dialogContext).pop(),
child: const Text('닫기'),
),
],
),
);
}
}