import 'dart:convert';
import 'package:steel_crypt/steel_crypt.dart';
import 'package:convert/convert.dart';
import 'package:crypto/crypto.dart';

class CaptchaUtil{
  ///aes加密
  /// [key]AesCrypt加密key
  /// [content] 需要加密的内容字符串
  static String aesEncode({String key, String content}) {
    var aesCrypt = AesCrypt(
        key: base64UrlEncode(key.codeUnits), padding: PaddingAES.pkcs7);
    return aesCrypt.ecb.encrypt(inp: content);
  }

  ///aes解密
  /// [key]aes解密key
  /// [content] 需要加密的内容字符串
  static String aesDecode({String key, String content}) {
    var aesCrypt = AesCrypt(
        key: base64UrlEncode(key.codeUnits), padding: PaddingAES.pkcs7);
    return aesCrypt.ecb.decrypt(enc: content);
  }
  /// isEmpty.
  static bool isEmpty(Object value) {
    if (value == null) return true;
    if (value is String && value.isEmpty) {
      return true;
    }
    return false;
  }

  //list length == 0  || list == null
  static bool isListEmpty(Object value) {
    if (value == null) return true;
    if (value is List && value.length == 0) {
      return true;
    }
    return false;
  }

  static String jsonFormat(Map<dynamic, dynamic> map) {
    Map _map = Map<String, Object>.from(map);
    JsonEncoder encoder = JsonEncoder.withIndent('  ');
    return encoder.convert(_map);
  }


  static String generateMd5(String data){
    var content = new Utf8Encoder().convert(data);
    var digest = md5.convert(content);
    return hex.encode(digest.bytes);
  }

  static signData(Object params, tokenStr) async {
    var time = new DateTime.now().millisecondsSinceEpoch;
    String token = tokenStr;
    Map<String, dynamic> reqData = new Map();
    Map<String, dynamic> paramsObj = new Map();
    paramsObj = params as Map<String, dynamic>;
    var arr = [];
    //将字典转成数组
    paramsObj?.forEach((key, value) => arr.add(key));
    //进行签名校验
    Map cr = new Map();
    cr['token'] = token;
    cr['time'] = time.toString();
    cr['reqData'] = json.encode(paramsObj);
    var array = [];
    cr.forEach((key, value) => array.add(key));
    array.sort();
    var str = '';
    for (var i = 0; i < array.length; i++) {
      var key = array[i];
      var value = cr[key];
      str += key + value;
    }

    reqData["time"] = time;
    reqData["token"] = token;
    reqData['reqData'] = params;
    reqData['sign'] = generateMd5(str);

    return reqData;
  }
}