package com.iamberry.wechat.tools;

import java.io.ByteArrayOutputStream;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;

/**
 * 请求校验工具类
 * @author fzh
 */
public class SignUtil{
	
	/**
	 * 验证签名
	 * @param signature
	 * @param timestamp
	 * @param nonce
	 * @return
	 */
	public static boolean checkSignature(String signature, String timestamp, String nonce, String token) {
		String[] arr = new String[] { token, timestamp, nonce };
		// 将token、timestamp、nonce三个参数进行字典序排序
		Arrays.sort(arr);
		StringBuilder content = new StringBuilder();
		for (int i = 0; i < arr.length; i++) {
			content.append(arr[i]);
		}
		
		String tmpStr = Sha1Util.getSha1(content.toString());

		content = null;
		// 将sha1加密后的字符串可与signature对比，标识该请求来源于微信
		return tmpStr != null ? tmpStr.equals(signature.toUpperCase()) : false;
	}
	
	/**
	 * 参数按字典序排序
	 * @param params
	 * @return
	 */
	public static String sortParams(Object... params){
		Arrays.sort(params);
		StringBuilder content = new StringBuilder();
		for (int i = 0; i < params.length; i++) {
			content.append(params[i]).append(i==params.length-1?"=%s":"=%s&");
		}
		return content.toString();
	}
	
	/**
	 * 获取随机字串（16位）
	 * @return
	 */
	public static String getNonceStr(){
		String nonce_str = "";
	    String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
	    int maxPos = chars.length();
	    for (int i = 0; i < 16; i++){
	       nonce_str += chars.charAt((int) Math.floor(Math.random() * maxPos));
	    }
	    return nonce_str;
	}

	/**
	 * 获取时间戳
	 * @return
	 */
	public static String getTimeStamp() {
		return String.valueOf(System.currentTimeMillis() / 1000);
	}
	
	/*
	* 16进制数字字符集
	*/
	private static String hexString = "0123456789ABCDEF"; //此处不可随意改动
	
	/*
	* 将字符串编码成16进制数字 
	*/
	public static String encode(String str) {
	   // 根据默认编码获取字节数组
	   byte[] bytes = str.getBytes();
	   StringBuilder sb = new StringBuilder(bytes.length * 2);
	   // 将字节数组中每个字节拆解成2位16进制整数
	   for (int i = 0; i < bytes.length; i++) {
		    sb.append(hexString.charAt((bytes[i] & 0xf0) >> 4));
		    sb.append(hexString.charAt((bytes[i] & 0x0f) >> 0));
	   }
	   return sb.toString();
	}

	/*
	* 将16进制数字解码成字符串
    */
	public static String decode(String bytes) {
	   ByteArrayOutputStream baos = new ByteArrayOutputStream(bytes.length() / 2);
	   // 将每2位16进制整数组装成一个字节
	   for (int i = 0; i < bytes.length(); i += 2){
		   baos.write((hexString.indexOf(bytes.charAt(i)) << 4 | hexString.indexOf(bytes.charAt(i + 1))));
	   }
	   return new String(baos.toByteArray());
	}
	
	/**
     * @Description：将请求参数转换为xml格式的string
     * @param parameters  请求参数
     * @return
     */
    @SuppressWarnings("rawtypes")
	public static String getRequestXml(SortedMap<Object,Object> parameters){
        StringBuffer sb = new StringBuffer();
        sb.append("<xml>");
        Set es = parameters.entrySet();
        Iterator it = es.iterator();
        while(it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();
            String k = (String)entry.getKey();
            String v = (String)entry.getValue();
            if ("attach".equalsIgnoreCase(k)||"body".equalsIgnoreCase(k)||"sign".equalsIgnoreCase(k)) {
                sb.append("<"+k+">"+"<![CDATA["+v+"]]></"+k+">");
            }else {
                sb.append("<"+k+">"+v+"</"+k+">");
            }
        }
        sb.append("</xml>");
        return sb.toString();
    }
}

