package com.winsun.utils;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;

import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * Created by wangwenbo on 2018/5/24.
 */
/* 签名验证相关utilS*/
public class SignUtil {
    /**
     * 将输入的参数转换成sign
     * @param param 请求的参数（不包含sign，否则会把sign当作数据一齐处理）
     * @param appKey 指定的秘钥
     * @return
     */
    public static String createUnifiedOrderSign(final Map<String,String> param, String appKey) {
        List<String> keies = new ArrayList<>();
        keies.addAll(param.keySet());
        Collections.sort(keies);
        List<String> datas = new ArrayList<>();
        keies.forEach(key -> {
            datas.add(key + "=" + param.getOrDefault(key, ""));
        });
        datas.add(appKey);

        return DigestUtils.md5Hex(StringUtils.join(datas, "&")).toLowerCase();
    }

    private static final String TOKEN = "supperapp"; // 加密token

    /***
     * MD5加密 生成32位md5码 速度比较快 性能高 安全强度比sha1要低
     *
     * @param 待加密字符串
     * @return 返回32位md5码
     */
    public static String md5EncodeSignature(String inStr) throws Exception {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }

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

    /***
     * SHA加密 生成40位SHA码 加密速度比md5慢 性能比md5低 安全强度比md5高
     *
     * @param 待加密字符串
     * @return 返回40位SHA码
     */
    public static String shaEncodeSignature(String inStr) throws Exception {
        MessageDigest sha = null;
        try {
            sha = MessageDigest.getInstance("SHA");
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }

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

    /**
     * 签名加密
     *
     * @param inStr
     * @param type
     *            加密方式 1，MD5 2，SHA
     * @return
     */
    public static String signature(String inStr, int type) {
        String encodeStr = "";
        int sel = type;
        if (sel == 0) {
            try {
                encodeStr = md5EncodeSignature(TOKEN+":"+ inStr);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            try {
                encodeStr = shaEncodeSignature(TOKEN+":" + inStr);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return encodeStr;
    }

    //把一个字符串中的大写转为小写，小写转换为大写
    public static String exChange(String str){
        StringBuffer sb = new StringBuffer();
        if(str!=null){
            for(int i=0;i<str.length();i++){
                char c = str.charAt(i);
                if(Character.isLowerCase(c)){
                    sb.append(Character.toUpperCase(c));   // 小转大
                }else{
                    sb.append(c);
                }
            }
        }

        return sb.toString();
    }

}
