package com.yc.ship.module.resource.service.resource.util;

import cn.hutool.json.JSONUtil;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class MD5Utils {
	
	private final static char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
			'a', 'b', 'c', 'd', 'e', 'f' };
	
	public static String MD5(String s) {
		
		try {
			byte[] strTemp = s.getBytes("utf-8");
			MessageDigest mdTemp = MessageDigest.getInstance("MD5"); 
			mdTemp.update(strTemp);
			byte[] md = mdTemp.digest();
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(str);
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 *生成md5
	 *@param source
	 * @return
	 */
	public static String getMD5(byte[] source) {
		String s = null;
		char[] hexDigits = { // 用来将字节转换成 16 进制表示的字符
				'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(source);
			byte[] tmp = md.digest();          // MD5 的计算结果是一个 128 位的长整数，
			// 用字节表示就是 16 个字节
			char[] str = new char[16 * 2];   // 每个字节用 16 进制表示的话，使用两个字符，
			// 所以表示成 16 进制需要 32 个字符
			int k = 0;                                // 表示转换结果中对应的字符位置
			for (int i = 0; i < 16; i++) {    // 从第一个字节开始，对 MD5 的每一个字节
				// 转换成 16 进制字符的转换
				byte byte0 = tmp[i];  // 取第 i 个字节
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];  // 取字节中高 4 位的数字转换,
				// >>> 为逻辑右移，将符号位一起右移
				str[k++] = hexDigits[byte0 & 0xf];   // 取字节中低 4 位的数字转换
			}
			s = new String(str);  // 换后的结果转换为字符串

		} catch (Exception e) {
			e.printStackTrace();
		}
		return s;
	}

	public static String getMd5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {
		MessageDigest md5 = MessageDigest.getInstance("MD5");
		byte[] bytes = md5.digest(text.getBytes(StandardCharsets.UTF_8));

		StringBuilder builder = new StringBuilder();

		for (byte aByte : bytes) {
			builder.append(Integer.toHexString((0x000000FF & aByte) | 0xFFFFFF00).substring(6));
		}
		return builder.toString();
	}


	public static String mapIterator(Map<String, Object> map){
		Map<String, Object> keymap = new TreeMap<String, Object>();
		Set<String> keySet = map.keySet();
		Iterator<String> iter = keySet.iterator();
		while (iter.hasNext()) {
			String key = iter.next();
			keymap.put(key, map.get(key));
		}
		return JSONUtil.toJsonStr(keymap);
	}

	/**
	 * 获取sign
	 * @param params
	 * @param secret
	 * @return
	 */
	public static String getSign(Map<String, String> params, String secret) {
		Map<String, String> sortedParams = new TreeMap(params);
		StringBuilder builder = new StringBuilder();
		builder.append(secret);
		Iterator var4 = sortedParams.entrySet().iterator();

		while(var4.hasNext()) {
			Map.Entry<String, String> param = (Map.Entry)var4.next();
			builder.append((String)param.getKey()).append((String)param.getValue());
		}

		builder.append(secret);
		// md5 加密
		return md5Hex(builder.toString());
	}
	private static String md5Hex(String data) {
		return toHexString(md5(data));
	}

	private static byte[] md5(String data) {
		return getDigest().digest((data.getBytes()));
	}

	private static MessageDigest getDigest() {
		try {
			return MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException var1) {
			throw new RuntimeException(var1);
		}
	}

	private static String toHexString(byte[] b) {
		StringBuffer sb = new StringBuffer();

		for(int i = 0; i < b.length; ++i) {
			sb.append("0123456789abcdef".charAt(b[i] >>> 4 & 15));
			sb.append("0123456789abcdef".charAt(b[i] & 15));
		}
		return sb.toString();
	}

}
