package com.library.util.turnpay;

import java.util.Map;
import java.util.TreeMap;

public class FunctionUtil
{
    /**
     * 使用 Map按key进行排序
     * @param map
     * @return
     */
    public static Map<String, String> sortMapByKey(Map<String, String> map) {
        if (map == null || map.isEmpty()) {
            return null;
        }
        Map<String, String> sortMap = new TreeMap<String, String>(
                new MapKeyComparator());
        sortMap.putAll(map);
        return sortMap;
    }
    
    public static String getMd5SignByMap(Map<String, String> map, String secretKey, String...charset) {
        return md5Sign(sortMapByKey(map), secretKey, charset);
    }
    /**
     * 拼接参数（key+value）按md5加密
     * @param param
     * @return
     */
    public static String md5Sign(Map<String, String> param, String secretKey, String...charset) {
        if(param == null) {
            return "";
        }
        StringBuffer sb = new StringBuffer();
        String value = "";
        for(Map.Entry<String, String> entry: param.entrySet()) {
            value = entry.getValue();
            //空值不参与加密
            if(value != null && !"".equals(value)) {
                sb.append(entry.getKey()).append("=").append(value).append("&");
            }
        }
        //拼接密钥
        sb.append("key=" + secretKey);
//        System.out.println("拼接加密字符串:" + sb.toString());
        String signValue = null;
        try {
            signValue = MD5Encrypt.getMessageDigest(sb.toString(), charset).toUpperCase();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return signValue;
    }
    /**
     * 转换map为http传输参数格式
     * @param param
     * @return
     */
    public static String map2HttpParam(Map<String, String> param) {
        
        StringBuffer sb = new StringBuffer();
        boolean isFirst = true;
        for(Map.Entry<String, String> entry: param.entrySet()) {
            if(isFirst) {
                isFirst = false;
            }
            else {
                sb.append("&");
            }
            sb.append(entry.getKey()).append("=").append(entry.getValue());
        }
        return sb.toString();
    }
}
