/// 精选推荐模块
library;

import 'dart:async';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:path_provider/path_provider.dart';

// 下载管理器类
class DownloadManager {
  static final Dio _dio = Dio();

  static Future<String> downloadFile({
    required String url,
    required String fileName,
    required Function(int) onProgress,
    required Function(String) onComplete,
    required Function(String) onError,
  }) async {
    try {
      // 获取存储目录
      Directory directory;
      if (Platform.isAndroid) {
        directory = await getExternalStorageDirectory() ?? await getApplicationDocumentsDirectory();
      } else {
        directory = await getApplicationDocumentsDirectory();
      }

      String downloadDir = '${directory.path}/Downloads';
      await Directory(downloadDir).create(recursive: true);

      String safeFileName = _getSafeFileName(fileName);
      String filePath = '$downloadDir/$safeFileName';

      await _dio.download(
        url,
        filePath,
        onReceiveProgress: (received, total) {
          if (total != -1) {
            int progress = (received / total * 100).toInt();
            onProgress(progress);
          }
        },
      );

      onComplete(filePath);
      return filePath;
    } catch (e) {
      onError(e.toString());
      rethrow;
    }
  }

  static String _getSafeFileName(String fileName) {
    return fileName.replaceAll(RegExp(r'[<>:"/\\|?*]'), '_');
  }
}
