//下载文件
import 'dart:io';

import 'package:path_provider/path_provider.dart';

class LocalDownload {
  static Future<String> getLocalFilePath(String url, String path) async {
    Uri uri = Uri.parse(url);
    String fileName = uri.pathSegments.last;
    //获取下载目录
    Directory dir = await getApplicationCacheDirectory();
    Directory uploadPath = Directory("${dir.path}$path/");
    return uploadPath.path + fileName;
  }

  /// 公用下载方法
  /// url 下载网络地址
  /// path 存储地址，如/test
  /// onProgress 下载回调函数
  /// onDone 下载完毕回调
  static downLoadFile({
    required url,
    required path,
    required Function(double) onProgress,
    required Function(String) onDone,
  }) async {
    HttpClient client = HttpClient();
    Uri uri = Uri.parse(url);
    //获取本地文件路径
    String filePath = await getLocalFilePath(url, path);
    // 发起 get 请求
    HttpClientRequest request = await client.getUrl(uri);
    // 响应
    HttpClientResponse response = await request.close();
    int contentLength = response.contentLength; // 获取文件总大小
    int bytesReceived = 0; // 已接收的字节数
    List<int> chunkList = [];
    if (response.statusCode == 200) {
      response.listen(
        (List<int> chunk) {
          chunkList.addAll(chunk);
          bytesReceived += chunk.length; //更新已接受的字节数
          //进度
          double progress = bytesReceived * 100 / contentLength * 100;
          progress = (progress / 100).truncateToDouble();
          onProgress(progress);
        },
        onDone: () async {
          //下载完毕
          client.close();
          File file = File(filePath);
          if (!file.existsSync()) {
            file.createSync(recursive: true);
            await file.writeAsBytes(chunkList);
          }
          onDone(file.path);
        },
        onError: () {
          client.close();
        },
        cancelOnError: true,
      );
    }
  }

  ///获取本地地址
  ///
  static Future<String> getFilePath({
    required url,
    required path,
  }) async {
    //获取本地文件路径
    String filePath = await getLocalFilePath(url, path);
    File file = File(filePath);
    if (file.existsSync()) {
      return file.path;
    } else {
      return '';
    }
  }
}
