package com.quyunshuo.androidbaseframemvvm.base.utils;

import android.util.Log;


import com.quyunshuo.androidbaseframemvvm.base.utils.commons.DigestUtils;



import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * MD5加密工具类
 * Created by MinKin.
 */
public class MD5Util {

    public static String getMD5Str(String password) {
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.reset();
            messageDigest.update(password.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        byte[] byteArray = messageDigest.digest();
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < byteArray.length; i++) {
            if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) {
                buffer.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
            } else {
                buffer.append(Integer.toHexString(0xFF & byteArray[i]));
            }
        }
        //16位加密，从第9位到25位
        return buffer.substring(0, 32).toString().toLowerCase();
    }

    /**
     * 生成签名
     * @param map
     * @return
     */
    public static String getSignToken(Map<String, String> map) {
        String result = "";
        try {
            List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(map.entrySet());
            // 对所有传入参数按照字段名的 ASCII 码从小到大排序（字典序）
            Collections.sort(infoIds, new Comparator<Map.Entry<String, String>>() {

                public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
                    return (o1.getKey()).toString().compareTo(o2.getKey());
                }
            });
            // 构造签名键值对的格式
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, String> item : infoIds) {
                if (item.getKey() != null || item.getKey() != "") {
                    String key = item.getKey();
                    String val = item.getValue();
                    if (!(val == "" || val == null)) {
                        sb.append(key + "=" + val + "&");
                    }
                }
            }
            //密钥
            result = sb.toString()+"key=C0775C5A8B0F42CF973CFF9552B8C769";
            System.out.println(result);

            Log.d("getPayUrl", "payUrlBean getSignToken1: "+result);
            //进行MD5加密
            result  = md5(result);
//            result = getMD5Value(result);
        } catch (Exception e) {
            return null;
        }
        return result;
    }


    /**
     * Description:MD5工具生成token
     * @param value
     * @return
     */
    public static String getMD5Value(String value){
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            byte[] md5ValueByteArray = messageDigest.digest(value.getBytes());
            BigInteger bigInteger = new BigInteger(1 , md5ValueByteArray);
            return bigInteger.toString(16).toUpperCase();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * MD5方法
     * @param text 明文
     * @return 密文
     * @throws Exception
     */
    public static String md5(String text) throws Exception {
        //加密后的字符串
        String encodeStr= DigestUtils.md5Hex(text ).toUpperCase();
        return encodeStr;
    }

    public static String calcSign(Map<String, String> params, String secret) {
        params = new TreeMap<>(params);
        StringBuilder stringBuilder = new StringBuilder();
        int size = params.size();
        int index = 0;
        for(Map.Entry<String, String> entry: params.entrySet()) {
            index++;
            stringBuilder.append(entry.getKey()).append("=").append(entry.getValue());
            if(index < size) {
                stringBuilder.append("&");
            }
        }

        return DigestUtils.sha256Hex(stringBuilder.toString());
    }

}


