905086
2026-11-07 6697e53613d5ce562a19795ab41b19803c2bb93d
fluttergamebox/lib/widgets/download_manager.dart
@@ -1,9 +1,10 @@
import 'dart:io';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:fluttergamebox/api/api_client.dart';
import 'package:fluttergamebox/common/theme.dart';
import 'package:fluttergamebox/store/app_state.dart';
import 'package:fluttergamebox/utils/network_info.dart';
import 'package:fluttergamebox/utils/util.dart';
import 'package:path/path.dart' as p;
@@ -16,9 +17,81 @@
  );
}
class _DownloadDialog extends StatelessWidget {
class _DownloadDialog extends StatefulWidget {
  const _DownloadDialog();
  @override
  State<_DownloadDialog> createState() => _DownloadDialogState();
}
class _DownloadDialogState extends State<_DownloadDialog> {
  bool _showDetails = true; // 展开/收起详细任务
  String _isp = '获取中...'; // 网络运营商(真实获取)
  final _logCtrl = ScrollController(); // 解压日志自动滚动到底部
  @override
  void initState() {
    super.initState();
    _loadIsp();
  }
  /// 获取真实网络运营商
  Future<void> _loadIsp() async {
    try {
      final n = await getNetworkInfo();
      if (mounted) setState(() => _isp = n.isp);
    } catch (_) {
      if (mounted) setState(() => _isp = '未知');
    }
  }
  @override
  void dispose() {
    _logCtrl.dispose();
    super.dispose();
  }
  /// 安装完成后启动游戏
  Future<void> _launchGame(DownloadTask task) async {
    final ok = await launchInstalledGame(task.title, task.launchExe);
    if (!ok && mounted) {
      _toast(task.isTool ? '未找到工具文件,请重新下载安装' : '未找到游戏文件,请重新下载安装');
    }
  }
  void _toast(String msg) {
    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: AppColors.red,
              borderRadius: BorderRadius.circular(6),
            ),
            child: Row(
              children: [
                const Icon(Icons.error_outline, 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());
  }
  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: DownloadManager.instance,
@@ -43,6 +116,15 @@
            ),
          );
        }
        // 环形进度:下载阶段用下载进度,安装(解压)阶段用解压进度
        final displayProgress = task.extracting ? task.extractProgress : task.progress;
        if (task.extracting) {
          WidgetsBinding.instance.addPostFrameCallback((_) {
            if (_logCtrl.hasClients) {
              _logCtrl.jumpTo(_logCtrl.position.maxScrollExtent);
            }
          });
        }
        return Dialog(
          backgroundColor: const Color(0xFF1E2130),
          shape:
@@ -110,7 +192,7 @@
                            width: 86,
                            height: 86,
                            child: CircularProgressIndicator(
                              value: task.finished ? 1 : task.progress,
                              value: task.finished ? 1 : displayProgress,
                              color: task.paused
                                  ? AppColors.yellow
                                  : AppColors.accent,
@@ -119,7 +201,7 @@
                            ),
                          ),
                          Text(
                            '${(task.progress * 100).toStringAsFixed(task.progress < 0.1 ? 2 : 0)}%',
                            '${(displayProgress * 100).toStringAsFixed(displayProgress < 0.1 ? 2 : 0)}%',
                            style: const TextStyle(
                                color: Colors.white,
                                fontSize: 15,
@@ -137,7 +219,7 @@
                            children: [
                              Text(
                                task.extracting
                                    ? '正在解压安装...'
                                    ? '正在安装'
                                    : task.extractFailed
                                        ? '解压失败'
                                        : task.finished
@@ -160,11 +242,9 @@
                          ),
                          const SizedBox(height: 8),
                          Text(
                            task.extracting
                                ? '解压中,请勿关闭软件'
                                : task.extractFailed
                                    ? '压缩包保留在下载目录,可手动解压'
                                    : '${formatBytes(task.speed)}/s',
                            task.extractFailed
                                ? '压缩包保留在下载目录,可手动解压'
                                : formatSpeed(task.speed),
                            style: const TextStyle(
                                color: AppColors.textGray, fontSize: 13),
                          ),
@@ -176,9 +256,11 @@
                          ),
                          const SizedBox(height: 4),
                          Text(
                            task.finished
                                ? '已完成'
                                : '剩余时间 ${formatDuration(task.etaSeconds)}',
                            task.extracting
                                ? '00:00:00'
                                : task.finished
                                    ? '已完成'
                                    : '剩余时间 ${formatDuration(task.etaSeconds)}',
                            style: const TextStyle(
                                color: AppColors.textGray, fontSize: 13),
                          ),
@@ -188,103 +270,157 @@
                  ],
                ),
                const SizedBox(height: 16),
                // 网络信息条
                // 网络信息条 + 收起详细任务
                Container(
                  padding:
                      const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                  decoration: BoxDecoration(
                    color: AppColors.bg,
                    borderRadius: BorderRadius.circular(4),
              padding:
                  const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
              decoration: BoxDecoration(
                color: AppColors.bg,
                borderRadius: BorderRadius.circular(4),
              ),
              child: Row(
                children: [
                  Text('网络运营商:$_isp',
                      style: const TextStyle(
                          color: AppColors.textGray, fontSize: 12)),
                  const Spacer(),
                  GestureDetector(
                    onTap: () =>
                        setState(() => _showDetails = !_showDetails),
                    child: Row(
                      children: [
                        Text(
                            _showDetails ? '收起详细任务' : '展开详细任务',
                            style: const TextStyle(
                                color: AppColors.textGray, fontSize: 12)),
                        const SizedBox(width: 4),
                        Icon(
                            _showDetails
                                ? Icons.keyboard_arrow_up
                                : Icons.keyboard_arrow_down,
                            color: AppColors.textGray,
                            size: 14),
                      ],
                    ),
                  ),
                  child: Row(
                    children: [
                      const Text('网络运营商:联通',
                          style: TextStyle(
                              color: AppColors.textGray, fontSize: 12)),
                      const Spacer(),
                      const Text('点击切换线路:自动',
                          style: TextStyle(
                              color: AppColors.textGray, fontSize: 12)),
                    ],
                  const SizedBox(width: 16),
                  const Text('点击切换线路:自动',
                      style: TextStyle(
                          color: AppColors.textGray, fontSize: 12)),
                ],
              ),
            ),
                if (_showDetails) ...[
                  const SizedBox(height: 10),
                  // 详细任务列表:下载阶段显示分卷下载,安装阶段显示解压日志
                  Container(
                    constraints: const BoxConstraints(maxHeight: 180),
                    decoration: BoxDecoration(
                      color: AppColors.bg,
                      borderRadius: BorderRadius.circular(4),
                    ),
                    child: task.extracting || task.extractFailed
                        ? ListView.builder(
                            shrinkWrap: true,
                            controller: _logCtrl,
                            itemCount: task.extractLog.length,
                            itemBuilder: (context, i) {
                              final e = task.extractLog[i];
                              return Padding(
                                padding: const EdgeInsets.symmetric(
                                    horizontal: 12, vertical: 6),
                                child: Row(
                                  children: [
                                    SizedBox(
                                      width: 40,
                                      child: Text('${e.percent}%',
                                          style: const TextStyle(
                                              color: AppColors.textWhite,
                                              fontSize: 11)),
                                    ),
                                    Expanded(
                                      child: Text(e.path,
                                          maxLines: 1,
                                          overflow: TextOverflow.ellipsis,
                                          style: const TextStyle(
                                              color: AppColors.textGray,
                                              fontSize: 11)),
                                    ),
                                  ],
                                ),
                              );
                            },
                          )
                        : ListView.builder(
                            shrinkWrap: true,
                            itemCount: task.files.length,
                            itemBuilder: (context, i) {
                              final f = task.files[i];
                              Color stColor = AppColors.textDim;
                              String stLabel = '等待下载';
                              switch (f.status) {
                                case DownloadStatus.preparing:
                                  stColor = AppColors.yellow;
                                  stLabel = '正在准备';
                                case DownloadStatus.downloading:
                                  stColor = AppColors.green;
                                  stLabel = '正在下载';
                                case DownloadStatus.paused:
                                  stColor = AppColors.yellow;
                                  stLabel = '已暂停';
                                case DownloadStatus.done:
                                  stColor = AppColors.green;
                                  stLabel = '已完成';
                                case DownloadStatus.failed:
                                  stColor = AppColors.red;
                                  stLabel = '下载失败';
                                default:
                                  stLabel = '等待下载';
                              }
                              return Padding(
                                padding: const EdgeInsets.symmetric(
                                    horizontal: 12, vertical: 6),
                                child: Row(
                                  children: [
                                    SizedBox(
                                      width: 200,
                                      child: Text(f.name,
                                          maxLines: 1,
                                          overflow: TextOverflow.ellipsis,
                                          style: const TextStyle(
                                              color: AppColors.textWhite,
                                              fontSize: 12)),
                                    ),
                                    Expanded(
                                      child: LinearProgressIndicator(
                                        value: f.progress,
                                        backgroundColor: AppColors.bgLighter,
                                        color: AppColors.accent,
                                        minHeight: 3,
                                      ),
                                    ),
                                    const SizedBox(width: 10),
                                    SizedBox(
                                      width: 130,
                                      child: Text(
                                          '${formatBytes(f.received)}/${formatBytes(f.totalBytes)}',
                                          style: const TextStyle(
                                              color: AppColors.textGray,
                                              fontSize: 11)),
                                    ),
                                    SizedBox(
                                      width: 60,
                                      child: Text(stLabel,
                                          style: TextStyle(
                                              color: stColor, fontSize: 11)),
                                    ),
                                  ],
                                ),
                              );
                            },
                          ),
                  ),
                ),
                const SizedBox(height: 10),
                // 文件列表
                Container(
                  constraints: const BoxConstraints(maxHeight: 180),
                  decoration: BoxDecoration(
                    color: AppColors.bg,
                    borderRadius: BorderRadius.circular(4),
                  ),
                  child: ListView.builder(
                    shrinkWrap: true,
                    itemCount: task.files.length,
                    itemBuilder: (context, i) {
                      final f = task.files[i];
                      Color stColor = AppColors.textDim;
                      String stLabel = '等待下载';
                      switch (f.status) {
                        case DownloadStatus.preparing:
                          stColor = AppColors.yellow;
                          stLabel = '正在准备';
                        case DownloadStatus.downloading:
                          stColor = AppColors.green;
                          stLabel = '正在下载';
                        case DownloadStatus.paused:
                          stColor = AppColors.yellow;
                          stLabel = '已暂停';
                        case DownloadStatus.done:
                          stColor = AppColors.green;
                          stLabel = '已完成';
                        case DownloadStatus.failed:
                          stColor = AppColors.red;
                          stLabel = '下载失败';
                        default:
                          stLabel = '等待下载';
                      }
                      return Padding(
                        padding: const EdgeInsets.symmetric(
                            horizontal: 12, vertical: 6),
                        child: Row(
                          children: [
                            SizedBox(
                              width: 200,
                              child: Text(f.name,
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis,
                                  style: const TextStyle(
                                      color: AppColors.textWhite,
                                      fontSize: 12)),
                            ),
                            Expanded(
                              child: LinearProgressIndicator(
                                value: f.progress,
                                backgroundColor: AppColors.bgLighter,
                                color: AppColors.accent,
                                minHeight: 3,
                              ),
                            ),
                            const SizedBox(width: 10),
                            SizedBox(
                              width: 130,
                              child: Text(
                                  '${formatBytes(f.received)}/${formatBytes(f.totalBytes)}',
                                  style: const TextStyle(
                                      color: AppColors.textGray,
                                      fontSize: 11)),
                            ),
                            SizedBox(
                              width: 60,
                              child: Text(stLabel,
                                  style: TextStyle(
                                      color: stColor, fontSize: 11)),
                            ),
                          ],
                        ),
                      );
                    },
                  ),
                ),
                ],
                const SizedBox(height: 18),
                // 操作按钮
                Row(
@@ -301,34 +437,54 @@
                                }
                              },
                        style: ElevatedButton.styleFrom(
                          backgroundColor: task.paused
                              ? AppColors.accent
                              : const Color(0xFF3A3F52),
                          backgroundColor: AppColors.accent,
                          foregroundColor: Colors.white,
                          disabledBackgroundColor:
                              AppColors.green.withOpacity(0.3),
                          disabledBackgroundColor: AppColors.bgLighter,
                          disabledForegroundColor: AppColors.textDim,
                          padding: const EdgeInsets.symmetric(vertical: 12),
                        ),
                        child: Text(task.finished
                            ? '下载完成'
                            : task.paused
                                ? '继续下载'
                                : '暂停下载'),
                        child: Text(task.extracting
                            ? '正在安装'
                            : task.finished
                                ? '下载完成'
                                : task.paused
                                    ? '继续下载'
                                    : '暂停下载'),
                      ),
                    ),
                    const SizedBox(width: 12),
                    Expanded(
                      child: ElevatedButton(
                        onPressed: () {
                          DownloadManager.instance.cancelTask();
                          Navigator.pop(context);
                        },
                        // 安装完成后变为启动按钮
                        onPressed: task.extracting
                            ? null
                            : (task.finished && !task.extractFailed)
                                ? () => _launchGame(task)
                                : () {
                                    DownloadManager.instance.cancelTask();
                                    Navigator.pop(context);
                                  },
                        style: ElevatedButton.styleFrom(
                          backgroundColor: const Color(0xFF3A3F52),
                          backgroundColor:
                              (task.finished && !task.extractFailed)
                                  ? AppColors.accent
                                  : const Color(0xFF3A3F52),
                          foregroundColor: Colors.white,
                          disabledBackgroundColor: AppColors.bgLighter,
                          disabledForegroundColor: AppColors.textDim,
                          padding: const EdgeInsets.symmetric(vertical: 12),
                        ),
                        child: const Text('取消安装'),
                        child: (task.finished && !task.extractFailed)
                            ? Row(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  const Icon(Icons.play_arrow, size: 18),
                                  const SizedBox(width: 8),
                                  Text(task.isTool ? '启动' : '启动游戏',
                                      style: const TextStyle(fontSize: 14)),
                                ],
                              )
                            : const Text('取消安装'),
                      ),
                    ),
                  ],
@@ -398,3 +554,152 @@
  }
  Process.run('explorer.exe', [p.normalize(dir.path)]);
}
/// 下载路径选择弹窗(详情页下载、资源库安装共用)
class DownloadPathDialog extends StatefulWidget {
  final String gameTitle;
  const DownloadPathDialog({super.key, required this.gameTitle});
  @override
  State<DownloadPathDialog> createState() => _DownloadPathDialogState();
}
class _DownloadPathDialogState extends State<DownloadPathDialog> {
  final _dlCtrl = TextEditingController();
  final _insCtrl = TextEditingController();
  @override
  void initState() {
    super.initState();
    _load();
  }
  @override
  void dispose() {
    _dlCtrl.dispose();
    _insCtrl.dispose();
    super.dispose();
  }
  Future<void> _load() async {
    final dl = await AppPrefs.getDownloadPath();
    final ins = await AppPrefs.getInstallPath();
    setState(() {
      _dlCtrl.text = dl.isEmpty ? 'C:\\99GameBox\\99GameD' : dl;
      _insCtrl.text = ins.isEmpty ? 'C:\\99GameBox\\99GameI' : ins;
    });
  }
  @override
  Widget build(BuildContext context) {
    return Dialog(
      backgroundColor: const Color(0xFF1E2130),
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(6)),
      child: Container(
        width: 500,
        padding: const EdgeInsets.all(24),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                const Icon(Icons.folder,
                    size: 16, color: AppColors.textGray),
                const SizedBox(width: 8),
                const Text('请选择下载安装路径',
                    style: TextStyle(
                        color: Colors.white,
                        fontSize: 14,
                        fontWeight: FontWeight.w500)),
                const Spacer(),
                GestureDetector(
                  onTap: () => Navigator.pop(context, false),
                  child: const Icon(Icons.close,
                      size: 16, color: AppColors.textGray),
                ),
              ],
            ),
            const SizedBox(height: 18),
            _pathRow('下载路径', _dlCtrl),
            const SizedBox(height: 12),
            _pathRow('安装路径', _insCtrl),
            const SizedBox(height: 20),
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                OutlinedButton(
                  onPressed: () => Navigator.pop(context, false),
                  style: OutlinedButton.styleFrom(
                    foregroundColor: AppColors.textGray,
                    side: const BorderSide(color: AppColors.bgLighter),
                    padding: const EdgeInsets.symmetric(
                        horizontal: 22, vertical: 10),
                  ),
                  child: const Text('取消'),
                ),
                const SizedBox(width: 12),
                ElevatedButton(
                  onPressed: () async {
                    await AppPrefs.setPaths(_dlCtrl.text, _insCtrl.text);
                    if (context.mounted) Navigator.pop(context, true);
                  },
                  style: ElevatedButton.styleFrom(
                    backgroundColor: AppColors.accent,
                    foregroundColor: Colors.white,
                    padding: const EdgeInsets.symmetric(
                        horizontal: 22, vertical: 10),
                  ),
                  child: const Text('确认'),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
  Widget _pathRow(String label, TextEditingController ctrl) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(label,
            style: const TextStyle(color: AppColors.textGray, fontSize: 12)),
        const SizedBox(height: 6),
        Row(
          children: [
            Expanded(
              child: TextField(
                controller: ctrl,
                style: const TextStyle(color: Colors.black, fontSize: 13),
                decoration: InputDecoration(
                  filled: true,
                  fillColor: Colors.white,
                  contentPadding: const EdgeInsets.symmetric(
                      horizontal: 10, vertical: 10),
                  border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(4),
                      borderSide: BorderSide.none),
                ),
              ),
            ),
            const SizedBox(width: 8),
            ElevatedButton(
              onPressed: () async {
                final dir = await FilePicker.platform.getDirectoryPath();
                if (dir != null) setState(() => ctrl.text = dir);
              },
              style: ElevatedButton.styleFrom(
                backgroundColor: AppColors.accent,
                foregroundColor: Colors.white,
                padding: const EdgeInsets.symmetric(
                    horizontal: 14, vertical: 11),
              ),
              child: const Text('选择目录', style: TextStyle(fontSize: 12)),
            ),
          ],
        ),
      ],
    );
  }
}