package com.huimv.management.rsa;

import com.huimv.common.utils.Constant;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

/**
 * @description 发送端
 * 
 * @author admin
 *
 */
public class ClientController {

    //私钥
//    private final static String PRIVATE_KEY = "MIIBUwIBADANBgkqhkiG9w0BAQEFAASCAT0wggE5AgEAAkEAnPWR8anPt0YVkJRj+Rdu9gFdkR3leD5LxJFEP6naIYJ5CUon4XJy5uh7uEivyOHJMQqlo4U3zBbn9A1d07MOcwIDAQABAkAZhys0ddztvv1U5X2ZDsGiSziPmKAwvVkPYF0MSbDLkC6ZF6SDosPnBOQGY1YXF88eknAxEmuhWHnRAb05QnUJAiEA03SgC954tZS4OLyRf/4ArNdOBYurKQPbCapDgwAesYUCIQC+BhF3FBGyIlnh7D1iN+uNm1atga5go3widi7dqRnFlwIgEuQldEoA4MAToUX/fb7Ukpx9pPMwbG6iv/9NHsQA+f0CIALRfDjT519I+yRKqK5oPeofv61bGwb75b9tGUzYUTWJAiBLKFNjABVQWu5zYD+IGx3ooJyAFn7rwFGL8Y3h1V1ITg==";
    private final static String PRIVATE_KEY = "MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAi8mzQlAAkln1VgrKjr0HINjMOkJOPK79tRzD7tIjU+pm2WJRiaNSZpB3MqKAKOlAfZKrfH5VKZ+emtmE/oI5iQIDAQABAkBYO/V5evQRbNTt/ZvDo09XjWDDuUyXA0HDSyflnCCOe2qvwydIWNYcvEdD98coIkPnL+MgkB0wVNYtWICTbyEBAiEA1wPPL8KKAcsuQAyKYGEuJ/hg5Uw5PhqXvUDWprPL0ykCIQCmbwBPL5dSilm39gi1MjIAZQpNSxO2qFapu/7u0/NfYQIhAMy6wdKWB9ZBYp510mSG4+4HICv08iRiKc14KWq9k/xRAiBtm+LvQ597+6OUtNMNSi6F9gUv3EbyX7EbfbUqYqoAYQIgWVUFfuaLNnGb+TR9ImT4NA/JHoaADTQNI0XeGwOV0G4=";

    public static String sender() throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, SignatureException, UnsupportedEncodingException {
        // 请求所需的参数
        Map<String, Object> requestParam = new HashMap<>(16);
//        requestParam.put("userName", "小明");
//        requestParam.put("phone", "15866552236");
//        requestParam.put("address", "北京");
//        requestParam.put("status", 1);
        requestParam.put("token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJhdXRoMCIsImV4cCI6MTYyMDM2OTY4NH0.5XdV22FSaCaJFuLkWGN-SajCn4VXD0S1Hi6wcr1Vz78");
        requestParam.put("random", 10050);
        requestParam.put("timestamp", System.currentTimeMillis());
//        requestParam.put("status", 1);

        // 将需要签名的参数内容按参数名的字典顺序进行排序，并拼接为字符串
        StringBuilder sb = new StringBuilder();
        requestParam.entrySet().stream().sorted(
                    Comparator.comparing(Map.Entry::getKey)).forEach(entry ->
                        sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&"));
        String paramStr = sb.toString().substring(0, sb.length() - 1);
        System.out.println("paramStr:" + paramStr);
        
        // 使用私钥生成签名字符串
        String sign = JdkSignatureUtil.executeSignature(Constant.RSA_SIGN_PRIVATE_KEY, paramStr);
        
        // 对签名字符串进行url编码
        String urlEncodeSign = URLEncoder.encode(sign, "UTF-8");
//        String urlEncodeSign = URLEncoder.encode(sign, StandardCharsets.UTF_8.toString());
        
        // 请求参数中需带上签名字符串
        requestParam.put("sign", urlEncodeSign);
        
        // 发送请求
        return postJson("http://localhost:9200 /test", requestParam);
    }
    
    /**
     * 发送数据类型为json的post请求
     * 
     * @param <T>
     * @param url
     * @param param
     * @return
     */
    public static <T> String postJson(String url, T param) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<T> httpEntity = new HttpEntity<>(param, headers);

        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, httpEntity, String.class);

        return responseEntity.getBody();
    }
    
    public static void main(String[] args) {
        try {
            System.out.println(sender());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}