import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:superport/models/license_model.dart'; import 'package:superport/screens/common/theme_shadcn.dart'; import 'package:superport/screens/common/components/shadcn_components.dart'; import 'package:superport/screens/common/widgets/pagination.dart'; import 'package:superport/screens/license/controllers/license_list_controller.dart'; import 'package:superport/utils/constants.dart'; import 'package:superport/services/mock_data_service.dart'; import 'package:superport/core/config/environment.dart' as env; import 'package:intl/intl.dart'; /// shadcn/ui 스타일로 재설계된 유지보수 라이선스 관리 화면 class LicenseListRedesign extends StatefulWidget { const LicenseListRedesign({super.key}); @override State createState() => _LicenseListRedesignState(); } class _LicenseListRedesignState extends State { late final LicenseListController _controller; final MockDataService _dataService = MockDataService(); final TextEditingController _searchController = TextEditingController(); final ScrollController _horizontalScrollController = ScrollController(); int _currentPage = 1; final int _pageSize = 10; // 날짜 포맷터 final DateFormat _dateFormat = DateFormat('yyyy-MM-dd'); @override void initState() { super.initState(); // API 모드 확인 및 로깅 debugPrint('\n========== 라이센스 화면 초기화 =========='); debugPrint('📌 USE_API 설정값: ${env.Environment.useApi}'); debugPrint('📌 API Base URL: ${env.Environment.apiBaseUrl}'); // 실제 API 사용 여부에 따라 컨트롤러 초기화 final useApi = env.Environment.useApi; _controller = LicenseListController( useApi: useApi, mockDataService: useApi ? null : _dataService, ); debugPrint('📌 Controller 모드: ${useApi ? "Real API" : "Mock Data"}'); debugPrint('==========================================\n'); _controller.addListener(_handleControllerUpdate); // 초기 데이터 로드 WidgetsBinding.instance.addPostFrameCallback((_) { _controller.loadData(); }); } @override void dispose() { // 리스너 제거 _controller.removeListener(_handleControllerUpdate); // 컨트롤러 dispose _searchController.dispose(); _horizontalScrollController.dispose(); _controller.dispose(); super.dispose(); } /// 페이지네이션용 라이선스 가져오기 List _getPagedLicenses() { final licenses = _controller.licenses; final int startIndex = (_currentPage - 1) * _pageSize; final int endIndex = startIndex + _pageSize; return licenses.sublist( startIndex, endIndex > licenses.length ? licenses.length : endIndex, ); } /// 검색 실행 void _onSearch() { _controller.search(_searchController.text); } /// 라이선스 추가 폼으로 이동 void _navigateToAdd() async { final result = await Navigator.pushNamed(context, Routes.licenseAdd); if (result == true && mounted) { _controller.refresh(); } } /// 라이선스 수정 폼으로 이동 void _navigateToEdit(int licenseId) async { final result = await Navigator.pushNamed( context, Routes.licenseEdit, arguments: licenseId, ); if (result == true && mounted) { _controller.refresh(); } } /// 라이선스 삭제 다이얼로그 void _showDeleteDialog(int licenseId) { showDialog( context: context, builder: (context) => AlertDialog( title: const Text('라이선스 삭제'), content: const Text('정말로 삭제하시겠습니까?'), actions: [ TextButton( onPressed: () => Navigator.of(context).pop(), child: const Text('취소'), ), TextButton( onPressed: () { Navigator.of(context).pop(); _controller.deleteLicense(licenseId).then((_) { if (mounted) { ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('라이선스가 삭제되었습니다.')), ); } }); }, child: const Text('삭제', style: TextStyle(color: Colors.red)), ), ], ), ); } /// 선택된 라이선스 일괄 삭제 void _showBulkDeleteDialog() { final selectedCount = _controller.selectedCount; if (selectedCount == 0) { ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('삭제할 라이선스를 선택해주세요.')), ); return; } showDialog( context: context, builder: (context) => AlertDialog( title: Text('$selectedCount개 라이선스 삭제'), content: Text('선택한 $selectedCount개의 라이선스를 삭제하시겠습니까?'), actions: [ TextButton( onPressed: () => Navigator.of(context).pop(), child: const Text('취소'), ), TextButton( onPressed: () { Navigator.of(context).pop(); _controller.deleteSelectedLicenses().then((_) { if (mounted) { ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text('$selectedCount개 라이선스가 삭제되었습니다.')), ); } }); }, child: const Text('삭제', style: TextStyle(color: Colors.red)), ), ], ), ); } /// 엑셀 내보내기 안내 void _showExportInfo() { ScaffoldMessenger.of(context).showSnackBar( const SnackBar( content: Text('엑셀 내보내기 기능은 준비 중입니다.'), duration: Duration(seconds: 2), ), ); } /// 엑셀 가져오기 안내 void _showImportInfo() { ScaffoldMessenger.of(context).showSnackBar( const SnackBar( content: Text('엑셀 가져오기 기능은 준비 중입니다.'), duration: Duration(seconds: 2), ), ); } /// 만료일까지 남은 일수에 따른 색상 Color _getDaysRemainingColor(int? days) { if (days == null) return ShadcnTheme.mutedForeground; if (days <= 0) return ShadcnTheme.destructive; if (days <= 7) return Colors.red; if (days <= 30) return Colors.orange; return ShadcnTheme.foreground; } /// 만료일까지 남은 일수 텍스트 String _getDaysRemainingText(int? days) { if (days == null) return '-'; if (days <= 0) return '만료됨'; if (days == 1) return '1일'; return '$days일'; } /// 컨트롤러 업데이트 핸들러 void _handleControllerUpdate() { if (mounted) { setState(() {}); } } @override Widget build(BuildContext context) { return ChangeNotifierProvider.value( value: _controller, child: Consumer( builder: (context, controller, child) { return Container( color: ShadcnTheme.background, child: Column( children: [ // 상단 통계 카드 _buildStatisticsCards(), // 필터 및 액션 바 _buildFilterBar(), // 라이선스 테이블 Expanded( child: controller.isLoading && controller.licenses.isEmpty ? _buildLoadingState() : controller.error != null ? _buildErrorState() : _buildLicenseTable(), ), ], ), ); }, ), ); } /// 상단 통계 카드 섹션 Widget _buildStatisticsCards() { return Container( padding: const EdgeInsets.all(24), child: Row( children: [ Expanded( child: _buildStatCard( '전체 라이선스', '${_controller.statistics['total'] ?? 0}', Icons.description, ShadcnTheme.primary, ), ), const SizedBox(width: 16), Expanded( child: _buildStatCard( '활성 라이선스', '${_controller.statistics['active'] ?? 0}', Icons.check_circle, ShadcnTheme.success, ), ), const SizedBox(width: 16), Expanded( child: _buildStatCard( '30일 내 만료', '${_controller.statistics['expiringSoon'] ?? 0}', Icons.warning, Colors.orange, ), ), const SizedBox(width: 16), Expanded( child: _buildStatCard( '만료됨', '${_controller.statistics['expired'] ?? 0}', Icons.cancel, ShadcnTheme.destructive, ), ), ], ), ); } /// 통계 카드 위젯 Widget _buildStatCard(String title, String value, IconData icon, Color color) { return Container( padding: const EdgeInsets.all(16), decoration: BoxDecoration( color: ShadcnTheme.card, borderRadius: BorderRadius.circular(ShadcnTheme.radiusMd), border: Border.all(color: Colors.black), ), child: Row( children: [ Container( padding: const EdgeInsets.all(8), decoration: BoxDecoration( color: color.withValues(alpha: 0.1), borderRadius: BorderRadius.circular(8), ), child: Icon(icon, size: 16, color: color), ), const SizedBox(width: 12), Text(title, style: ShadcnTheme.bodySmall), const Spacer(), Text( value, style: TextStyle( fontSize: 20, fontWeight: FontWeight.bold, color: color, ), ), ], ), ); } /// 필터 바 Widget _buildFilterBar() { return Container( padding: const EdgeInsets.all(24), child: Column( children: [ // 검색 및 필터 섹션 Row( children: [ // 검색 입력 Expanded( flex: 2, child: Container( height: 40, decoration: BoxDecoration( color: ShadcnTheme.card, borderRadius: BorderRadius.circular(ShadcnTheme.radiusMd), border: Border.all(color: Colors.black), ), child: TextField( controller: _searchController, onSubmitted: (_) => _onSearch(), decoration: InputDecoration( hintText: '제품명, 라이선스 키, 벤더명, 회사명 검색...', hintStyle: TextStyle(color: ShadcnTheme.mutedForeground.withValues(alpha: 0.8), fontSize: 14), prefixIcon: Icon(Icons.search, color: ShadcnTheme.muted, size: 20), border: InputBorder.none, contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), ), style: ShadcnTheme.bodyMedium, ), ), ), const SizedBox(width: 16), // 검색 버튼 SizedBox( height: 40, child: ShadcnButton( text: '검색', onPressed: _onSearch, variant: ShadcnButtonVariant.primary, textColor: Colors.white, icon: const Icon(Icons.search, size: 16), ), ), const SizedBox(width: 16), // 상태 필터 드롭다운 Container( height: 40, padding: const EdgeInsets.symmetric(horizontal: 12), decoration: BoxDecoration( color: ShadcnTheme.card, border: Border.all(color: Colors.black), borderRadius: BorderRadius.circular(ShadcnTheme.radiusMd), ), child: DropdownButtonHideUnderline( child: DropdownButton( value: _controller.statusFilter, onChanged: (value) { if (value != null) { _controller.changeStatusFilter(value); } }, style: TextStyle(fontSize: 14, color: ShadcnTheme.foreground), icon: const Icon(Icons.arrow_drop_down, size: 20), items: const [ DropdownMenuItem( value: LicenseStatusFilter.all, child: Text('전체'), ), DropdownMenuItem( value: LicenseStatusFilter.active, child: Text('활성'), ), DropdownMenuItem( value: LicenseStatusFilter.inactive, child: Text('비활성'), ), DropdownMenuItem( value: LicenseStatusFilter.expiringSoon, child: Text('만료예정'), ), DropdownMenuItem( value: LicenseStatusFilter.expired, child: Text('만료됨'), ), ], ), ), ), ], ), const SizedBox(height: 16), // 액션 버튼들 및 상태 표시 Row( children: [ // 액션 버튼들 ShadcnButton( text: '라이선스 추가', onPressed: _navigateToAdd, variant: ShadcnButtonVariant.primary, textColor: Colors.white, icon: const Icon(Icons.add, size: 16), ), const SizedBox(width: 8), ShadcnButton( text: '삭제', onPressed: _controller.selectedCount > 0 ? _showBulkDeleteDialog : null, variant: _controller.selectedCount > 0 ? ShadcnButtonVariant.destructive : ShadcnButtonVariant.secondary, icon: const Icon(Icons.delete, size: 16), ), const SizedBox(width: 8), ShadcnButton( text: '엑셀 내보내기', onPressed: _showExportInfo, variant: ShadcnButtonVariant.secondary, icon: const Icon(Icons.download, size: 16), ), const SizedBox(width: 8), ShadcnButton( text: '엑셀 가져오기', onPressed: _showImportInfo, variant: ShadcnButtonVariant.secondary, icon: const Icon(Icons.upload, size: 16), ), const Spacer(), // 선택 및 총 개수 표시 if (_controller.selectedCount > 0) Container( padding: const EdgeInsets.symmetric( vertical: 8, horizontal: 16, ), decoration: BoxDecoration( color: ShadcnTheme.muted.withValues(alpha: 0.3), borderRadius: BorderRadius.circular(ShadcnTheme.radiusSm), ), child: Text( '${_controller.selectedCount}개 선택됨', style: const TextStyle(fontWeight: FontWeight.bold), ), ), if (_controller.selectedCount > 0) const SizedBox(width: 12), Text( '총 ${_controller.licenses.length}개', style: ShadcnTheme.bodyMuted, ), const SizedBox(width: 12), // 새로고침 버튼 IconButton( icon: const Icon(Icons.refresh), onPressed: () => _controller.refresh(), tooltip: '새로고침', ), ], ), ], ), ); } /// 로딩 상태 Widget _buildLoadingState() { return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ CircularProgressIndicator(color: ShadcnTheme.primary), const SizedBox(height: 16), Text('라이선스 데이터를 불러오는 중...', style: ShadcnTheme.bodyMuted), ], ), ); } /// 에러 상태 Widget _buildErrorState() { return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Icon(Icons.error_outline, size: 48, color: ShadcnTheme.destructive), const SizedBox(height: 16), Text('데이터를 불러오는 중 오류가 발생했습니다.', style: ShadcnTheme.bodyMuted), const SizedBox(height: 8), Text(_controller.error ?? '', style: ShadcnTheme.bodySmall), const SizedBox(height: 16), ShadcnButton( text: '다시 시도', onPressed: () => _controller.refresh(), variant: ShadcnButtonVariant.primary, textColor: Colors.white, ), ], ), ); } /// 라이선스 테이블 Widget _buildLicenseTable() { final licenses = _controller.licenses; if (licenses.isEmpty) { return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Icon( Icons.description_outlined, size: 48, color: ShadcnTheme.mutedForeground, ), const SizedBox(height: 16), Text('등록된 라이선스가 없습니다.', style: ShadcnTheme.bodyMuted), const SizedBox(height: 16), ShadcnButton( text: '라이선스 추가', onPressed: _navigateToAdd, variant: ShadcnButtonVariant.primary, textColor: Colors.white, icon: const Icon(Icons.add, size: 16), ), ], ), ); } final pagedLicenses = _getPagedLicenses(); return SingleChildScrollView( padding: const EdgeInsets.all(24), child: Column( children: [ // 테이블 컨테이너 (가로 스크롤 지원) SingleChildScrollView( scrollDirection: Axis.horizontal, controller: _horizontalScrollController, child: Container( constraints: BoxConstraints( minWidth: MediaQuery.of(context).size.width - 48, // padding 고려 ), decoration: BoxDecoration( border: Border.all(color: Colors.black), borderRadius: BorderRadius.circular(ShadcnTheme.radiusMd), ), child: SizedBox( width: 1360, // 모든 컬럼 너비의 합 child: Column( children: [ // 테이블 헤더 Container( padding: const EdgeInsets.symmetric( horizontal: ShadcnTheme.spacing4, vertical: 10, ), decoration: BoxDecoration( color: ShadcnTheme.muted.withValues(alpha: 0.3), border: Border( bottom: BorderSide(color: Colors.black), ), ), child: Row( children: [ // 체크박스 SizedBox( width: 40, child: Checkbox( value: _controller.isAllSelected, onChanged: (value) => _controller.selectAll(value), tristate: false, ), ), // 번호 const SizedBox( width: 60, child: Text('번호', style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500)), ), // 제품명 const SizedBox( width: 200, child: Text('제품명', style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500)), ), // 라이선스 키 const SizedBox( width: 150, child: Text('라이선스 키', style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500)), ), // 벤더 const SizedBox( width: 120, child: Text('벤더', style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500)), ), // 회사명 const SizedBox( width: 150, child: Text('회사명', style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500)), ), // 할당 사용자 const SizedBox( width: 100, child: Text('할당 사용자', style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500)), ), // 상태 const SizedBox( width: 80, child: Text('상태', style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500)), ), // 구매일 const SizedBox( width: 100, child: Text('구매일', style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500)), ), // 만료일 const SizedBox( width: 100, child: Text('만료일', style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500)), ), // 남은 일수 const SizedBox( width: 80, child: Text('남은 일수', style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500)), ), // 관리 const SizedBox( width: 100, child: Text('관리', style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500)), ), ], ), ), // 테이블 데이터 ...pagedLicenses.asMap().entries.map((entry) { final displayIndex = entry.key; final license = entry.value; final index = (_currentPage - 1) * _pageSize + displayIndex; final daysRemaining = _controller.getDaysUntilExpiry(license); return Container( padding: const EdgeInsets.symmetric( horizontal: ShadcnTheme.spacing4, vertical: 4, ), decoration: BoxDecoration( border: Border( bottom: BorderSide(color: Colors.black), ), ), child: Row( children: [ // 체크박스 SizedBox( width: 40, child: Checkbox( value: license.id != null && _controller.selectedLicenseIds.contains(license.id), onChanged: license.id != null ? (value) => _controller.selectLicense(license.id, value) : null, tristate: false, ), ), // 번호 SizedBox( width: 60, child: Text('${index + 1}', style: ShadcnTheme.bodySmall), ), // 제품명 SizedBox( width: 200, child: Text( license.productName ?? '-', style: ShadcnTheme.bodySmall, overflow: TextOverflow.ellipsis, ), ), // 라이선스 키 SizedBox( width: 150, child: Text( license.licenseKey, style: ShadcnTheme.bodySmall, overflow: TextOverflow.ellipsis, ), ), // 벤더 SizedBox( width: 120, child: Text( license.vendor ?? '-', style: ShadcnTheme.bodySmall, overflow: TextOverflow.ellipsis, ), ), // 회사명 SizedBox( width: 150, child: Text( license.companyName ?? '-', style: ShadcnTheme.bodySmall, overflow: TextOverflow.ellipsis, ), ), // 할당 사용자 SizedBox( width: 100, child: Text( license.assignedUserName ?? '-', style: ShadcnTheme.bodySmall, overflow: TextOverflow.ellipsis, ), ), // 상태 SizedBox( width: 80, child: _buildStatusBadge(license, daysRemaining), ), // 구매일 SizedBox( width: 100, child: Text( license.purchaseDate != null ? _dateFormat.format(license.purchaseDate!) : '-', style: ShadcnTheme.bodySmall, ), ), // 만료일 SizedBox( width: 100, child: Text( license.expiryDate != null ? _dateFormat.format(license.expiryDate!) : '-', style: ShadcnTheme.bodySmall, ), ), // 남은 일수 SizedBox( width: 80, child: Text( _getDaysRemainingText(daysRemaining), style: TextStyle( fontSize: 12, color: _getDaysRemainingColor(daysRemaining), fontWeight: daysRemaining != null && daysRemaining <= 30 ? FontWeight.bold : FontWeight.normal, ), ), ), // 관리 SizedBox( width: 100, child: Row( mainAxisSize: MainAxisSize.min, children: [ Flexible( child: IconButton( constraints: const BoxConstraints( minWidth: 30, minHeight: 30, ), padding: const EdgeInsets.all(4), icon: const Icon(Icons.edit_outlined, size: 16), onPressed: license.id != null ? () => _navigateToEdit(license.id!) : null, tooltip: '수정', ), ), Flexible( child: IconButton( constraints: const BoxConstraints( minWidth: 30, minHeight: 30, ), padding: const EdgeInsets.all(4), icon: const Icon(Icons.delete_outline, size: 16), onPressed: license.id != null ? () => _showDeleteDialog(license.id!) : null, tooltip: '삭제', ), ), ], ), ), ], ), ); }).toList(), ], ), ), ), ), // 페이지네이션 컴포넌트 (항상 표시) if (licenses.length > _pageSize) Pagination( totalCount: licenses.length, currentPage: _currentPage, pageSize: _pageSize, onPageChanged: (page) { setState(() { _currentPage = page; }); }, ), ], ), ); } /// 라이선스 상태 표시 배지 Widget _buildStatusBadge(License license, int? daysRemaining) { // 만료 상태 확인 if (daysRemaining != null && daysRemaining <= 0) { return ShadcnBadge( text: '만료', variant: ShadcnBadgeVariant.destructive, size: ShadcnBadgeSize.small, ); } // 만료 임박 if (daysRemaining != null && daysRemaining <= 30) { return ShadcnBadge( text: '만료예정', variant: ShadcnBadgeVariant.warning, size: ShadcnBadgeSize.small, ); } // 활성/비활성 if (license.isActive) { return ShadcnBadge( text: '활성', variant: ShadcnBadgeVariant.success, size: ShadcnBadgeSize.small, ); } else { return ShadcnBadge( text: '비활성', variant: ShadcnBadgeVariant.secondary, size: ShadcnBadgeSize.small, ); } } }