package com.jpsoft.shinestar.modules.realname.http;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TreeMap;

@Slf4j
public class RealnameSysRequest {
    public JSONObject sendPost(String appId,String appSecret, String url, String method,String data){
        /**
         接口参数签名方法
         第一步：拼接参数字符串
         将除sign以外的请求参数（包括标准参数，除非有特别说明）按照参数名称的字典升序排列，
         然后按此顺序，将”参数名＝参数值”用”&”符号连接。
         appid=appcode123&data=[]&format=json&iscompany=2&method=employee.create&nonce=11223344&timestamp=1558593970&version=2.0
         **/
        TreeMap<String,Object> treeMap = new TreeMap<>();
        treeMap.put("method",method);
        treeMap.put("version","1.0");
        treeMap.put("appid",appId);
        treeMap.put("iscompany","1");
        treeMap.put("format","json");

        long timestamp = (new Date()).getTime()/1000;
        treeMap.put("timestamp", timestamp);
        treeMap.put("nonce", timestamp);

        treeMap.put("data", data);

        List<BasicNameValuePair> params = new ArrayList<>();
        StringBuilder sb = new StringBuilder();

        for (String key : treeMap.keySet()) {
            if (sb.length()>0){
                sb.append("&");
            }

            sb.append(key + "=" + treeMap.get(key));

            params.add(new BasicNameValuePair(key, treeMap.get(key).toString()));

            log.warn(key + ":" + treeMap.get(key));
        }

        /**
         * 第二步：在拼接参数字符串后再拼接&appsecret，如&appsecret=df23hlir85353；appsecret即密钥，由服务信息平台技术支持人员提供。
         * 示例：appid=appcode123&data=[]&format=json&iscompany=2&method=employee.create&nonce=11223344&timestamp=1558593970&version=2.0&appsecret=df23hlir85353gfgd86775jjdh6322
         **/
        sb.append("&appsecret=" + appSecret);

        /**
         * （3）第三步：将上一步的获得的字符串全部转换为小写。再进行SHA256加密（SHA256 64位），生成的字符串就是验签数据sign。注意：SHA256加密哈希值请转换为16进制表示。
         **/
        String plainText = sb.toString();

        StringBuilder postDataSb = new StringBuilder();
        postDataSb.append(plainText);

        plainText = plainText.toLowerCase();

        JSONObject jsonObject = new JSONObject();

        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(plainText.getBytes("UTF-8"));
            byte[] bytes = messageDigest.digest();

            StringBuffer stringBuffer = new StringBuffer();

            for (int i=0;i<bytes.length;i++) {
                String temp = Integer.toHexString(bytes[i] & 0xFF);

                if (temp.length() == 1) {
                    stringBuffer.append("0");
                }

                stringBuffer.append(temp);
            }

            log.warn("sign:" + stringBuffer.toString());
            params.add(new BasicNameValuePair("sign", stringBuffer.toString()));

            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);

            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(params, "UTF-8");
            urlEncodedFormEntity.setContentEncoding("UTF-8");
            httpPost.setEntity(urlEncodedFormEntity);
            CloseableHttpResponse response = httpClient.execute(httpPost);

            String content = EntityUtils.toString(response.getEntity(),"UTF-8");

            jsonObject = JSONObject.parseObject(content);

            log.warn("返回消息：" + jsonObject.get("message"));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return jsonObject;
    }
}
