package com.gree.mall.manager.utils;

import com.gree.mall.manager.bean.OutAppDefaultReq;
import com.gree.mall.manager.controller.common.CryptTool;
import org.apache.commons.codec.binary.Base64;

import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2019/5/24 0024.
 */
public class SignUtil {

    private static String token = "zhima";

    /**
     * 校验签名
     * @param signature 签名
     * @param timestamp 时间戳
     * @param nonce 随机数
     * @return 布尔值
     */
    public static boolean checkSignature(String signature,String timestamp,String nonce){
        String checktext = null;
        if (null != signature) {
            //对ToKen,timestamp,nonce 按字典排序
            String[] paramArr = new String[]{token,timestamp,nonce};
            Arrays.sort(paramArr);
            //将排序后的结果拼成一个字符串
            String content = paramArr[0].concat(paramArr[1]).concat(paramArr[2]);

            try {
                MessageDigest md = MessageDigest.getInstance("SHA-1");
                //对接后的字符串进行sha1加密
                byte[] digest = md.digest(content.toString().getBytes());
                checktext = byteToStr(digest);
            } catch (NoSuchAlgorithmException e){
                e.printStackTrace();
            }
        }
        //将加密后的字符串与signature进行对比
        return checktext !=null ? checktext.equals(signature.toUpperCase()) : false;
    }

    /**
     * 将字节数组转化我16进制字符串
     * @param byteArrays 字符数组
     * @return 字符串
     */
    private static String byteToStr(byte[] byteArrays){
        String str = "";
        for (int i = 0; i < byteArrays.length; i++) {
            str += byteToHexStr(byteArrays[i]);
        }
        return str;
    }

    /**
     *  将字节转化为十六进制字符串
     * @param myByte 字节
     * @return 字符串
     */
    private static String byteToHexStr(byte myByte) {
        char[] Digit = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
        char[] tampArr = new char[2];
        tampArr[0] = Digit[(myByte >>> 4) & 0X0F];
        tampArr[1] = Digit[myByte & 0X0F];
        String str = new String(tampArr);
        return str;
    }

    public static String bizContent(String jsonObject) throws Exception {
        String encodedObject = URLEncoder.encode(jsonObject, "UTF-8");
        encodedObject = encodedObject.replaceAll("\\+", "%20");
        return CryptTool.encryptBASE64(encodedObject.getBytes("UTF-8"));
    }


    public static OutAppDefaultReq getReqParam(String appid, String apiPath, String bizObject, String appKey) throws Exception {
        String bizContent = bizContent(bizObject);
        Timestamp ts = new Timestamp(System.currentTimeMillis());
        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String timestamp = sdf.format(ts);
        String version = "V1.0";
        String rand = StringUtil.getRandomSMS();
        return OutAppDefaultReq
                .builder()
                .appid(appid)
                .timestamp(timestamp)
                .signType("SHA256")
                .sign(getSign(appid,appKey,version,timestamp,bizContent,apiPath,rand))
                .version(version)
                .apiPath(apiPath)
                .bizContent(bizContent)
                .rand(rand).build();
    }



    public static String getSign(String appid, String appKey, String version, String timestamp, String bizContent, String apiPath, String rand) throws Exception {
        Map<String, Object> map = new HashMap(10);
        map.put("appid", appid);
        map.put("version", version);
        map.put("timestamp", timestamp);
        map.put("bizContent", bizContent);
        map.put("apiPath", apiPath);
        map.put("rand", rand);
        List<String> list = new ArrayList(map.keySet());
        Collections.sort(list);
        StringBuilder builder = new StringBuilder();
        Iterator var8 = list.iterator();
        String sign;
        while(var8.hasNext()) {
            sign = (String)var8.next();
            Object value = map.get(sign);
            if (null != value && !"".equals(value)) {
                builder.append(sign).append("=").append(value).append("&");
            }
        }
        String content = builder.substring(0, builder.length() - 1);
        String sha256 = CryptTool.sha256(CryptTool.sha256(content) + appKey);
        sign = CryptTool.encryptBASE64(sha256.getBytes("UTF-8"));
        return sign.trim();
    }




}
