905086
2026-11-07 7fd2270570811c0d29f0d5d87d11bfc4612e0743
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
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<DetailPage> createState() => _DetailPageState();
}
 
class _DetailPageState extends State<DetailPage> {
  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<void> _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<void> _toggleFavorite() async {
    final res = await ApiService.toggleFavorite(widget.gameId);
    if (res['code'] == 0 && mounted) {
      setState(() => isFavorite = !isFavorite);
      // 通知收藏页实时刷新
      AppState.instance.bumpFavorites();
      _toast(res['msg'] ?? '操作成功');
    }
  }
 
  Future<void> _addToLibrary() async {
    final res = await ApiService.addToLibrary(widget.gameId);
    if (res['code'] == 0 && mounted) {
      setState(() => inLibrary = true);
      // 通知资源库页实时刷新
      AppState.instance.bumpLibrary();
      _showConfirmDialog(
          '兑换成功!', '游戏已加入资源库,请在资源库页面查看。');
    } else if (mounted) {
      _toast(res['msg'] ?? '添加失败', error: true);
    }
  }
 
  Future<void> _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<void> _launch() async {
    if (game == null) return;
    final ok = await launchInstalledGame(game!.title, game!.launchExe);
    if (!ok && mounted) {
      _toast('未找到游戏文件,请先下载游戏', error: true);
    }
  }
 
  /// 下载前选择下载安装路径(并校验磁盘剩余空间)
  Future<bool> _askDownloadPath() async {
    final result = await showDialog<bool>(
      context: context,
      builder: (context) => DownloadPathDialog(
        gameTitle: game!.title,
        requiredGb: game!.requiredDiskGb,
      ),
    );
    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('游戏大小', sizeWithGb(game!.size)),
          _infoRow('磁盘占用', sizeWithGb(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)),
          ),
        ],
      ),
    );
  }
}