package com.yihu.jw.healthCare.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;


public class SafeUtil {


    public static void main(String[] args) throws Exception {
        //String reqStr = "{\"funid\":\"N09.00.00.01\",\"data\":{\"idNo\":\"350823199201173123\",\"first\":\"022\",\"keyword1\":\"5\",\"keyword2\":\"通过审核\",\"keyword3\":\"20200706155415\"},\"access_token\":\"4f886faf22775ccc9c8add16268ca9cd\",\"sign_type\":\"MD5\",\"encrypt_type\":\"AES\"}";
        //solution(reqStr,"signBefore");
        System.out.println(AES.aesDecrypt("BUOL01yRhFPlT2J+6wTYzNc9Hv3aAwwjOGdqoU6NIe2wvR9MMg6p0Jv4h012uwDKrBv3HGIXu1t7xVStC/nX4QKmYDelbd+hUFl5QZQ6FX1f0LPXNki99HKcSV00aB+DDb9j9ocfr/z3G091yNHAo+VD/FxFo60agRdcv1vl7Hg=", "4bfb6947baf9df93"));

    }

    public static String  solution(String reqStr,String signKey,String type) throws Exception {

        if("beforeSign".equals(type)){
            //先签名再加密
            reqStr = sign(reqStr,signKey);
            reqStr = encrypt(reqStr,signKey);
        }else{
            //先加密再签名
            reqStr = encrypt(reqStr,signKey);
            reqStr = sign(reqStr,signKey);
        }
        System.out.println("最终请求数据消息体（签名加密后的）：" + reqStr);
        return reqStr;
    }

    private static String getSortSignTemp(JSONObject json) {
        String signTemp = "";
        String jsonStr = JSONObject.toJSONString(json, SerializerFeature.MapSortField);
        LinkedHashMap m = JSON.parseObject(jsonStr, LinkedHashMap.class);
        Iterator<Map.Entry> iterator = m.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry entry = iterator.next();
            String strVal = "";
            if (entry.getValue() instanceof Map) {
                strVal = JSONObject.toJSONString(entry.getValue(), SerializerFeature.MapSortField);
            } else {
                strVal = ConvertUtils.toString(entry.getValue(), "");
            }
            signTemp += entry.getKey() + "=" + strVal + "&";
        }
        signTemp = StringUtils.trimEnd(signTemp, "&");
        return signTemp;
    }

    public static String sign(String reqStr,String signKey) {


        JSONObject md5Json = JSONObject.parseObject(reqStr);
        String sign = md5Json.getString("sign");
        md5Json.remove("sign");
        String signTemp = getSortSignTemp(md5Json) + "&key=" + signKey;
        System.out.println(signTemp);
        String md5Sign = MD5.md5(signTemp).toUpperCase();
        md5Json.put("sign", md5Sign);

        reqStr = JSON.toJSONString(md5Json);
        return reqStr;
    }

    public static   String encrypt(String reqStr,String decryptKey) {
        //key

        JSONObject encJson = JSONObject.parseObject(reqStr);
        JSONObject dataJson = encJson.getJSONObject("data");
        encJson.remove("data");
        String encData = "";
        try {
            encData = AES.aesEncrypt(JSON.toJSONString(dataJson), decryptKey);

        } catch (Exception e) {
            e.printStackTrace();
        }
        encJson.put("encrypt_data", encData);


        reqStr = JSON.toJSONString(encJson);
        reqStr = reqStr.replaceAll("\\\\r\\\\n", "");
        try {
            System.out.println("解密 : " + AES.aesDecrypt(encData, decryptKey));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return reqStr;
    }

}
