import 'package:crypto/crypto.dart';
import 'dart:convert';
import 'dart:io';
import 'package:flutter_native_image/flutter_native_image.dart';

class EncodeUtil {
  /*
  * Md5加密
  * */
  static String generateMd5(String data) {
    var content = new Utf8Encoder().convert(data);
    var digest = md5.convert(content);
    return digest.toString();
  }

  /*
  * Base64加密
  */
  static String encodeBase64(String data) {
    var content = utf8.encode(data);
    var digest = base64Encode(content);
    return digest;
  }

  /*
  * Base64解密
  */
  static String decodeBase64(String data) {
    // return String.fromCharCodes(base64Decode(data));
    return utf8.decode(base64Decode(data));
  }

  // 图片转成base64
  static Future<String> image2Base64(File file) async {
    // File file = new File(path);
    List<int> imageBytes = await file.readAsBytes();
    return base64Encode(imageBytes);
  }

  // 压缩图片至指定大小
  static Future<File> compressImage(File file, int size) async {
    List<int> originBytes = await file.readAsBytes();
    int originSize = (originBytes.length / 1024).ceil();
    print('原图大小:' + originSize.toString() + 'kb');
    if (originSize <= size) {
      return file;
    }

    int minQuality = 0;
    int maxQuality = 100;

    List<int> imageBytes = originBytes;

    do {
      int midQuality = ((minQuality + maxQuality) / 2).floor();
      File compressedFile = await FlutterNativeImage.compressImage(file.path,
          quality: midQuality);
      imageBytes = await compressedFile.readAsBytes();
      int compressSize = (imageBytes.length / 1024).ceil();
      if (compressSize == size) {
        break;
      } else if (compressSize > size) {
        maxQuality = midQuality;
      } else {
        minQuality = midQuality;
      }
    } while (maxQuality - minQuality > 1);
    File compressedFile =
        await FlutterNativeImage.compressImage(file.path, quality: minQuality);
    imageBytes = await compressedFile.readAsBytes();
    int compressSize = (imageBytes.length / 1024).ceil();
    print('quality:' +
        minQuality.toString() +
        ' 压缩后大小:' +
        compressSize.toString() +
        'kb');

    return compressedFile;
  }
}
