import 'dart:async'; import 'package:flutter/material.dart'; import 'package:fluttergamebox/api/api_client.dart'; import 'package:fluttergamebox/api/api_service.dart'; import 'package:fluttergamebox/common/theme.dart'; import 'package:fluttergamebox/store/app_state.dart'; import 'package:fluttergamebox/utils/util.dart'; import 'package:fluttergamebox/widgets/download_manager.dart'; class DetailPage extends StatefulWidget { final int gameId; final VoidCallback? onBack; // 在主Shell内展示时由Shell提供(保留顶部导航栏) const DetailPage({super.key, required this.gameId, this.onBack}); @override State createState() => _DetailPageState(); } class _DetailPageState extends State { Game? game; bool isFavorite = false; bool inLibrary = false; bool _installed = false; // 游戏是否已安装到本机 bool _loading = true; int _mediaIndex = 0; Timer? _slideTimer; late PageController _pageCtrl; @override void initState() { super.initState(); _pageCtrl = PageController(); _load(); } @override void dispose() { _slideTimer?.cancel(); _pageCtrl.dispose(); super.dispose(); } Future _load() async { final res = await ApiService.gameDetail(widget.gameId); if (!mounted) return; if (res['code'] == 0) { setState(() { game = Game.fromJson(res['data']['game']); isFavorite = res['data']['is_favorite'] == true; inLibrary = res['data']['in_library'] == true; _loading = false; }); // 媒体自动轮播 _slideTimer?.cancel(); _slideTimer = Timer.periodic(const Duration(seconds: 5), (_) { final mediaCount = 1 + (game?.screenshots.length ?? 0); if (mediaCount > 1 && mounted && _pageCtrl.hasClients) { _pageCtrl.nextPage( duration: const Duration(milliseconds: 400), curve: Curves.easeInOut); } }); // 检测游戏是否已安装到本机 _installed = await isGameInstalled(game!.title, game!.launchExe); if (mounted) setState(() {}); } else { setState(() => _loading = false); } } Future _toggleFavorite() async { final res = await ApiService.toggleFavorite(widget.gameId); if (res['code'] == 0 && mounted) { setState(() => isFavorite = !isFavorite); _toast(res['msg'] ?? '操作成功'); } } Future _addToLibrary() async { final res = await ApiService.addToLibrary(widget.gameId); if (res['code'] == 0 && mounted) { setState(() => inLibrary = true); _showConfirmDialog( '兑换成功!', '游戏已加入资源库,请在资源库页面查看。'); } else if (mounted) { _toast(res['msg'] ?? '添加失败', error: true); } } Future _download() async { if (game == null) return; // 每次下载前都弹出选择下载安装路径 final ok = await _askDownloadPath(); if (!ok) return; // 会员校验+开始下载 try { await DownloadManager.instance.startDownload(game!); if (mounted) showDownloadDialog(context); setState(() => inLibrary = true); } catch (e) { if (mounted) _toast(e.toString(), error: true); } } /// 启动已安装的游戏 Future _launch() async { if (game == null) return; final ok = await launchInstalledGame(game!.title, game!.launchExe); if (!ok && mounted) { _toast('未找到游戏文件,请先下载游戏', error: true); } } /// 下载前选择下载安装路径 Future _askDownloadPath() async { final result = await showDialog( context: context, builder: (context) => DownloadPathDialog(gameTitle: game!.title), ); return result == true; } void _toast(String msg, {bool error = false}) { final overlay = Overlay.of(context); final entry = OverlayEntry( builder: (context) => Positioned( top: 60, left: MediaQuery.of(context).size.width / 2 - 140, child: Material( color: Colors.transparent, child: Container( width: 280, padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), decoration: BoxDecoration( color: error ? AppColors.red : AppColors.green, borderRadius: BorderRadius.circular(6), ), child: Row( children: [ Icon(error ? Icons.error_outline : Icons.check_circle, color: Colors.white, size: 18), const SizedBox(width: 8), Expanded( child: Text(msg, style: const TextStyle( color: Colors.white, fontSize: 13)), ), ], ), ), ), ), ); overlay.insert(entry); Future.delayed(const Duration(seconds: 2), () => entry.remove()); } void _showConfirmDialog(String title, String content) { showDialog( context: context, builder: (context) => Dialog( backgroundColor: Colors.white, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), child: Container( width: 360, padding: const EdgeInsets.all(24), child: Column( mainAxisSize: MainAxisSize.min, children: [ const Icon(Icons.check_circle, color: AppColors.green, size: 48), const SizedBox(height: 16), Text(title, style: const TextStyle( color: Colors.black, fontSize: 16, fontWeight: FontWeight.bold)), const SizedBox(height: 8), Text(content, textAlign: TextAlign.center, style: const TextStyle( color: Color(0xFF666666), fontSize: 13)), const SizedBox(height: 20), SizedBox( width: 120, child: ElevatedButton( onPressed: () => Navigator.pop(context), style: ElevatedButton.styleFrom( backgroundColor: AppColors.accent, foregroundColor: Colors.white, ), child: const Text('确定'), ), ), ], ), ), ), ); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: AppColors.bg, body: _loading ? const Center( child: CircularProgressIndicator(color: AppColors.accent)) : game == null ? const Center( child: Text('游戏不存在', style: TextStyle(color: AppColors.textGray))) : Column( children: [ _buildHeader(), Expanded( child: SingleChildScrollView( child: Padding( padding: const EdgeInsets.fromLTRB(70, 16, 70, 40), child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ // 左侧:媒体+介绍 Expanded(child: _buildLeft()), const SizedBox(width: 20), // 右侧:配置+操作 SizedBox(width: 320, child: _buildRight()), ], ), ), ), ), ], ), ); } Widget _buildHeader() { return Container( height: 52, color: const Color(0xFF191C2B), padding: const EdgeInsets.symmetric(horizontal: 16), child: Row( children: [ IconButton( icon: const Icon(Icons.arrow_back, size: 20, color: AppColors.textGray), onPressed: () { if (widget.onBack != null) { widget.onBack!(); } else { Navigator.pop(context); } }, ), const SizedBox(width: 8), Expanded( child: Text(game!.title, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle( color: Colors.white, fontSize: 15, fontWeight: FontWeight.w500)), ), // 收藏 GestureDetector( onTap: _toggleFavorite, child: Row( children: [ Icon( isFavorite ? Icons.star : Icons.star_border, size: 18, color: isFavorite ? AppColors.yellow : AppColors.textGray, ), const SizedBox(width: 4), Text(isFavorite ? '取消收藏' : '收藏', style: TextStyle( color: isFavorite ? AppColors.yellow : AppColors.textGray, fontSize: 13)), ], ), ), const SizedBox(width: 20), ], ), ); } Widget _buildLeft() { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ // 媒体轮播 _buildMedia(), const SizedBox(height: 20), // 游戏介绍 const Text('游戏介绍', style: TextStyle( color: Colors.white, fontSize: 15, fontWeight: FontWeight.w500)), const SizedBox(height: 12), Container( width: double.infinity, padding: const EdgeInsets.all(16), decoration: BoxDecoration( color: AppColors.bgLight, borderRadius: BorderRadius.circular(6), ), child: Text( game!.description.isEmpty ? '暂无介绍' : game!.description, style: const TextStyle( color: AppColors.textGray, fontSize: 13, height: 1.8), ), ), // 截图 if (game!.screenshots.isNotEmpty) ...[ const SizedBox(height: 20), const Text('游戏截图', style: TextStyle( color: Colors.white, fontSize: 15, fontWeight: FontWeight.w500)), const SizedBox(height: 12), Wrap( spacing: 10, runSpacing: 10, children: game!.screenshots .map((s) => ClipRRect( borderRadius: BorderRadius.circular(4), child: Image.network( ApiClient.baseUrl + s, width: 200, height: 112, fit: BoxFit.cover, errorBuilder: (_, __, ___) => Container( width: 200, height: 112, color: AppColors.bgLighter, ), ), )) .toList(), ), ], ], ); } Widget _buildMedia() { final mediaCount = 1 + game!.screenshots.length; return Column( children: [ AspectRatio( aspectRatio: 16 / 8, child: PageView.builder( controller: _pageCtrl, itemCount: mediaCount, onPageChanged: (i) => setState(() => _mediaIndex = i), itemBuilder: (context, i) { if (i == 0 && game!.video.isNotEmpty) { // 视频占位(展示封面+播放按钮) return _buildMediaItem(game!.cover, isVideo: true); } final img = i == 0 ? game!.cover : game!.screenshots[i - 1]; return _buildMediaItem(img); }, ), ), const SizedBox(height: 8), // 缩略图 Row( children: [ for (var i = 0; i < mediaCount; i++) GestureDetector( onTap: () => _pageCtrl.animateToPage(i, duration: const Duration(milliseconds: 300), curve: Curves.easeInOut), child: Container( width: 88, height: 50, margin: const EdgeInsets.only(right: 8), decoration: BoxDecoration( borderRadius: BorderRadius.circular(4), border: Border.all( color: _mediaIndex == i ? AppColors.accent : Colors.transparent, width: 2, ), ), child: ClipRRect( borderRadius: BorderRadius.circular(3), child: Image.network( ApiClient.baseUrl + (i == 0 ? game!.cover : game!.screenshots[i - 1]), fit: BoxFit.cover, errorBuilder: (_, __, ___) => Container(color: AppColors.bgLighter), ), ), ), ), ], ), ], ); } Widget _buildMediaItem(String img, {bool isVideo = false}) { return ClipRRect( borderRadius: BorderRadius.circular(8), child: Stack( fit: StackFit.expand, children: [ Image.network( ApiClient.baseUrl + img, fit: BoxFit.cover, errorBuilder: (_, __, ___) => Container(color: AppColors.bgLighter), ), if (isVideo) Center( child: Container( width: 64, height: 64, decoration: BoxDecoration( color: Colors.black.withOpacity(0.5), shape: BoxShape.circle, border: Border.all(color: Colors.white38), ), child: const Icon(Icons.play_arrow, color: Colors.white, size: 36), ), ), // 版本说明条 Positioned( left: 0, right: 0, bottom: 0, child: Container( padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10), decoration: BoxDecoration( gradient: LinearGradient( begin: Alignment.bottomCenter, end: Alignment.topCenter, colors: [ Colors.black.withOpacity(0.8), Colors.transparent, ], ), ), child: Text(game!.versionNote, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(color: Colors.white, fontSize: 13)), ), ), ], ), ); } Widget _buildRight() { return Container( padding: const EdgeInsets.all(20), decoration: BoxDecoration( color: AppColors.bgLight, borderRadius: BorderRadius.circular(8), ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ // 类别标签 Wrap( spacing: 8, runSpacing: 8, children: [ _tag(game!.platformLabel, AppColors.accent), for (final t in game!.tags.split(',')) if (t.trim().isNotEmpty) _tag(t.trim(), AppColors.bgLighter), ], ), const SizedBox(height: 18), _infoRow('游戏大小', game!.size), _infoRow('磁盘占用', game!.installSize), const Divider(color: AppColors.bgLighter, height: 28), _infoRow('操作系统', game!.osReq), _infoRow('CPU', game!.cpuReq), _infoRow('内存', game!.ramReq), _infoRow('显卡', game!.gpuReq), const SizedBox(height: 20), // 加入资源库 SizedBox( width: double.infinity, height: 44, child: ElevatedButton( onPressed: inLibrary ? null : _addToLibrary, style: ElevatedButton.styleFrom( backgroundColor: inLibrary ? const Color(0xFF3A3F52) : const Color(0xFF00A651), foregroundColor: Colors.white, disabledBackgroundColor: const Color(0xFF3A3F52), disabledForegroundColor: AppColors.textGray, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(4)), ), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Icon( inLibrary ? Icons.check_circle_outline : Icons.add_circle_outline, size: 18, ), const SizedBox(width: 8), Text(inLibrary ? '已在资源库' : '加入资源库', style: const TextStyle(fontSize: 14)), ], ), ), ), const SizedBox(height: 12), // 下载游戏 / 启动游戏(已安装则切换为启动) ListenableBuilder( listenable: DownloadManager.instance, builder: (context, _) { // 本机已安装,或该游戏下载任务已完成(含解压)则显示启动按钮 final t = DownloadManager.instance.activeTask; final installed = _installed || (t != null && t.gameId == game!.id && !t.isTool && t.finished && !t.extractFailed); return SizedBox( width: double.infinity, height: 44, child: ElevatedButton( onPressed: installed ? _launch : _download, style: ElevatedButton.styleFrom( backgroundColor: AppColors.accent, foregroundColor: Colors.white, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(4)), ), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Icon(installed ? Icons.play_arrow : Icons.download, size: 18), const SizedBox(width: 8), Text(installed ? '启动游戏' : '下载游戏', style: const TextStyle(fontSize: 14)), ], ), ), ); }, ), ], ), ); } Widget _tag(String text, Color color) { return Container( padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), decoration: BoxDecoration( color: color, borderRadius: BorderRadius.circular(3), ), child: Text(text, style: const TextStyle(color: Colors.white, fontSize: 12)), ); } Widget _infoRow(String label, String value) { return Padding( padding: const EdgeInsets.symmetric(vertical: 5), child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox( width: 60, child: Text(label, style: const TextStyle( color: AppColors.textDim, fontSize: 13)), ), Expanded( child: Text(value.isEmpty ? '-' : value, style: const TextStyle( color: AppColors.textWhite, fontSize: 13)), ), ], ), ); } }