package cn.pluss.platform.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import com.alibaba.fastjson.JSONObject;

public class WechatSignUtil {

	
	public static String getSign(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 + ":");
					}
				}
 
			}
//			sb.append(PropertyManager.getProperty("SIGNKEY"));
			result = sb.toString();

			
		} catch (Exception e) {
			return null;
		}
		return result;
	}
	/**
	 * 获取HMAC-SHA256签名
	 *
	 * @param paramMap 签名参数（sign不参与签名）
	 * @param key      签名密钥
	 * @return HMAC-SHA256签名结果
	 */
	public final static String sha256Sign(Map<String, String> paramMap, String key) {
		try {
			String payParam = getSignTemp(paramMap, key);
			Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
			SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
			sha256_HMAC.init(secret_key);
			byte[] array = sha256_HMAC.doFinal(payParam.getBytes("UTF-8"));
			StringBuilder sb = new StringBuilder();
			for (byte item : array) {
				sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
			}
			String sign = sb.toString().toUpperCase();
			return sign;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 获取签名参数字符串
	 *
	 * @param paramMap 签名参数（sign字段不参与签名）
	 * @param payKey   签名密钥
	 * @return 待签名字符串
	 */
	public static String getSignTemp(Map<String, String> paramMap, String payKey) {
		ArrayList<String> keyList = new ArrayList<>(paramMap.keySet());
		Collections.sort(keyList);
		StringBuilder signParam = new StringBuilder();
		for (String key : keyList) {
			System.out.println(key+"======"+paramMap.get(key));
			if (!"sign".equals(key) && !StringUtil.isEmpty(paramMap.get(key).toString())) {
				signParam.append(key).append("=").append(paramMap.get(key)).append("&");
			}
		}
		signParam.delete(signParam.length() - 1, signParam.length());
		signParam.append("&key=").append(payKey);
		return signParam.toString();
	}
}
