package com.jpsoft.shinestar.modules.common.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

public class Sign {

    public static Map<String, String> sign(String jsapi_ticket, String url) {
        Map<String, String> ret = new HashMap<String, String>();
        String nonce_str = create_nonce_str();
        String timestamp = create_timestamp();
        String string1;
        String signature = "";

        //注意这里参数名必须全部小写，且必须有序
        string1 = "jsapi_ticket=" + jsapi_ticket +
                "&noncestr=" + nonce_str +
                "&timestamp=" + timestamp +
                "&url=" + url;

        try {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        ret.put("url", url);
        ret.put("jsapi_ticket", jsapi_ticket);
        ret.put("nonceStr", nonce_str);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);

        return ret;
    }

    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    private static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }

    private static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }


    public static String parkSign(Map<String, Object> map, String signKey) {


        if (map == null) {
            return null;
        }
        if (map.containsKey("sign")) {
            map.remove("sign");
        }

        List<String> keyList = new ArrayList<String>(map.keySet());
        Collections.sort(keyList);
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < keyList.size(); i++) {
            String key = keyList.get(i);
            Object value = map.get(key);
            sb.append(key + "=" + value + "&");
        }
        String signStr = (sb.substring(0,
                sb.length() - 1) + signKey).toLowerCase();
        System.out.println("before sign: " + signStr);
        String md5Str = MD5(signStr);
        System.out.println("after sign: " + md5Str);
        return md5Str;


    }

    /**
     * 生成MD5
     */
    public static String

    MD5(String s) {
        return MD5(s, "utf-8");
    }

    /**
     * 生成MD5
     */
    public static String

    MD5(String s, String charset) {

        try {
            MessageDigest messagedigest =
                    MessageDigest.getInstance("MD5");
            messagedigest.reset();
            byte abyte0[] = messagedigest.digest(s.getBytes(charset));
            return byteToString(abyte0);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }

    private static String

    byteToString(byte abyte0[]) {
        int i = abyte0.length;
        char ac[] = new char[i * 2];
        int j = 0;
        for (int k = 0; k < i; k++) {
            byte byte0 = abyte0[k];
            ac[j++] = hexDigits[byte0 >>> 4 & 0xf];
            ac[j++] = hexDigits[byte0 & 0xf];
        }
        return new String(ac);
    }

    private static final char hexDigits[] =

            {
                    '0', '1', '2', '3', '4', '5',
                    '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
            };
}
