package com.duiba.tuia.youtui.web.tool;/**
 * Created by chengdeman .
 * 17/7/3 .
 */

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.util.Iterator;
import java.util.Map;
import java.util.SortedMap;
import java.util.UUID;

/**
 * 对接第三方APIutils
 *
 * @author chengdeman
 * @create 2017-07-03 下午2:54
 **/
public abstract class APIUtils {

    private APIUtils() {
    }

    /** The Constant log. */
    private static final Logger log = LoggerFactory.getLogger(APIUtils.class);

    /**
     *  考拉ipua签名
     * @param secretKey
     * @param parameterMap
     * @return
     */
    public static String createSign(String secretKey, SortedMap<String, String> parameterMap)
    {
        StringBuilder sign = new StringBuilder(secretKey);

        Iterator it = parameterMap.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();
            if (!(entry.getKey()).equals("sign"))
            {
                sign = sign.append((String)entry.getKey()).append((String)entry.getValue());
            }
        }
        sign = sign.append(secretKey);
        try
        {
            sign = new StringBuilder(md5Encode2UpperCase(sign.toString()));
        } catch (Exception e) {
            log.warn(e.getMessage());
        }

        return sign.toString();
    }

    public static String md5Encode2UpperCase(String sign) throws UnsupportedEncodingException {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            log.warn(e.getMessage());
            return "";
        }

        byte[] byteArray = sign.getBytes("UTF-8");
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuilder hexValue = new StringBuilder();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = md5Bytes[i] & 0xFF;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString().toUpperCase();
    }

    /**
     * 猛犸tick
     * @return
     */
    public static String getTick() {
        return UUID.randomUUID().toString();
    }
}
