/*
 * @Author: XianKaiQun
 * @Date: 2020-07-22 15:01:31
 * @LastEditors  : WuWei
 * @LastEditTime : 2023-05-10 14:42:59
 * @Description: 
 */

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

import 'package:wisdom_cli/wisdom_cli.dart';
import 'package:dio/dio.dart' as _Dio; // TOD:因dio依赖库与flutter自带http库 有类命名冲突

///文件下载
class WisDownloadUtil {
  ///下载路径
  static Future<String> get path async {
    final directory = Platform.isAndroid
        ? await getExternalStorageDirectory()
        : await getApplicationDocumentsDirectory();
    return directory?.path ?? '' + '/Download/';
  }

  ///下载
  ///
  ///[url]
  ///
  ///[fileName]文件名，记得带上拓展名
  ///
  ///[onReceiveProgress] count当前已下载大小 total总大小
  static Future<String?> intent(String url, String fileName,
      {Function(int count, int total)? onReceiveProgress,
      _Dio.Options? options,
      double? progress}) async {
    String? filePath = await _isExist(url);
    if (filePath == null) {
      var res = await _Dio.Dio().download(
        url,
        await path + fileName,
        onReceiveProgress: (count, total) {
          if (onReceiveProgress != null) return onReceiveProgress(count, total);
        },
        options: options,
      );
      if (res.statusCode! < 300) {
        Map fileKeys = WisStorageUtil.get<Map>(key: _storage) ?? {};
        fileKeys[url] = await path + fileName;
        await WisStorageUtil.set(key: _storage, data: fileKeys);
        return await path + fileName;
      }
    } else {
      return filePath;
    }
    return null;
  }

  ///储存md5键
  static String _storage = 'download-asdkjflkjfeiogjr';

  ///判断是否已经下载过了且文件还在
  ///存在就返回文件路径
  ///不存在返回null
  static Future<String?> _isExist(String url) async {
    Map fileKeys = WisStorageUtil.get<Map>(key: _storage) ?? {};
    String? _path = fileKeys[url];

    ///下载过
    if (fileKeys[url] != null) {
      File file = File(_path!);
      var exists = await file.exists();
      if (exists) {
        return _path;
      } else {
        //文件不存在就确保储存中的这条url也删了
        fileKeys.remove(url);
        await WisStorageUtil.set(key: _storage, data: fileKeys);
        return null;
      }
    } else {
      return null;
    }
  }

  static delete() async {}
}
