package com.friday.custody.service.trustService.cmsc.utils;

import cfca.sadk.algorithm.common.Mechanism;
import cfca.sadk.algorithm.common.PKIException;
import cfca.sadk.lib.crypto.JCrypto;
import cfca.sadk.lib.crypto.Session;
import cfca.sadk.util.CertUtil;
import cfca.sadk.util.KeyUtil;
import cfca.sadk.util.Signature;
import cfca.sadk.x509.certificate.X509Cert;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.PrivateKey;
import java.util.HashMap;

@Slf4j
public class CMSCRemoteUtil {

    //test
    private static String uapServerType = "668";
    private static String uapUserNo = "test001";
    private static String uapLicenceKey = "dbb5b1ee-ab91-41fe-b9d3-47ceef6d4a30";
    private static String uapRequestId = "20211109000001";
    private static String url = "http://210.21.237.135:27011/v1/request";

    public static HashMap getDataFromRemote(String url, HttpHeaders headers, MultiValueMap<String, Object> map, HttpMethod method) {
//        HashMap<String, Object> remoteData = JSON.parseObject(JSON.toJSONString(RestTemplateUtil.getDataFromRemote(url,
//                headers).getBody()),
//                HashMap.class);
//        Object result = null;
//        if ((Integer) remoteData.get("code") == 200) {
//            result = .get("data");
//        }
//         remoteData;


        HttpEntity<JSONObject> dataFromRemote = RestTemplateUtil.getDataFromRemote(url, headers, map, method);
        System.out.println(JSON.toJSONString(dataFromRemote));
        return  null;
    }

    static RestTemplate restTemplate = new RestTemplate();

    //prod
//    private static String uapServerType = "668";
////    private static String uapUserNo = "client_ShangHaiYiCunTouZi";
//    private static String uapUserNo = "test001";
////    private static String uapLicenceKey = "2170f2aa-f86f-422f-910c-be87fa169fa8";
//    private static String uapLicenceKey = "dbb5b1ee-ab91-41fe-b9d3-47ceef6d4a30";
//    private static String uapRequestId = "20211109000001";
//    private static String url = "https://tgjjapi.newone.com.cn/v1/request";

    public static String getSign(String pfxIs, String pfxFilePwd, String companyId, String timeStramp, String businessData) throws PKIException, UnsupportedEncodingException {
        try {
//            X509Cert cert = CertUtil.getCertFromPFX(pfxIs,"yctz123");
            X509Cert cert = CertUtil.getCertFromPFX(pfxIs, pfxFilePwd);
            PrivateKey priKey = KeyUtil.getPrivateKeyFromPFX(pfxIs, pfxFilePwd);

            String deviceName = JCrypto.JSOFT_LIB;
            JCrypto.getInstance().initialize(deviceName, null);
            Session session = JCrypto.getInstance().openSession(deviceName);

//        String companyId = "b759a8a2afef4a2788c5050b4ac6d9f6";
//            String companyId = "20f45d0f27789868e055000000000001";
//            String timeStramp = "20191120121225";
            log.info("timeStramp---->--->-->->" + timeStramp);
            // 待签名消息
            String waitSingn = MD5Utils.MD5Upper(companyId.concat(timeStramp));
            byte[] sourceData = waitSingn.getBytes(StandardCharsets.UTF_8);
            Signature util = new Signature();
            String signAlg = Mechanism.SHA256_RSA;
            // 签名，必须指定签名算法，返回BASE64签名结果
            byte[] base64P7SignedData = util.p7SignMessageDetach(signAlg, sourceData,
                    priKey, cert, session); //使用证书和私钥进行签名
            return new String(base64P7SignedData);
        } catch (Exception e) {
            log.error(" error:", e);
            return null;
        }
    }

    public static HashMap getRemoteData(String pfxIs, String pfxFilePwd, String companyId, String timeStramp, String businessparam, String uapRequestNo, String url) {
        try {
            //1 塞请求头
            HttpHeaders headers = new HttpHeaders();
            headers.set("uap-server-type", uapServerType);
            headers.set("uap-request-no", uapRequestNo);
            headers.set("uap-user-no", uapUserNo);
            headers.set("uap-licence-key", uapLicenceKey);
            headers.set("uap-request-id", uapRequestId);
            //2 设置请求参数
            // 获得签名
            String sign = getSign(pfxIs, pfxFilePwd, companyId, timeStramp, businessparam);
//            StringBuffer sb = new StringBuffer();
//            String params = sb.append("?companyid=").append(companyId).append("&timeStramp=").append(timeStramp).append("&signature=").append(sign)
//                    .append("&businessparam=").append(businessparam).toString();
            HashMap<String, Object> body = new HashMap<>();
//            body.put("companyid", companyId);
//            body.put("timeStramp", timeStramp);
//            body.put("signature", sign);
//            body.put("businessparam", businessparam);
            StringBuffer sb = new StringBuffer(url);
            sb.append("?companyid=" + companyId);
            sb.append("&timeStramp=" + timeStramp);
            sb.append("&signature=" + sign);
            sb.append("&businessparam=" + URLEncoder.encode(businessparam, "utf-8"));

            ResponseEntity<JSONObject> res = restTemplate.postForEntity(sb.toString(), new HttpEntity<>(body, headers), JSONObject.class);
            return  JSON.parseObject(JSON.toJSONString(res.getBody()),
                    HashMap.class);
        } catch (Exception e) {
            log.error(" error:", e);
            return null;
        }
    }


//    public static Object getRemoteDataNew(String pfxIs, String pfxFilePwd, String companyId, String timeStramp,
//                                          String businessparam, String uapRequestNo, String url) throws UnsupportedEncodingException, PKIException {
//
//        //1.创建HttpClient对象
//        CloseableHttpClient httpClient = HttpClients.createDefault();
//        //2.创建HttpPost对象，设置URL地址
//        HttpPost httpPost = new HttpPost(url);
//        //声明list集合，用来分装表单中的参数
//        //要求：设置请求的地址是：http://yun.itheima.com/search?keys=java
//        Header[] headers = new Header[5];
//        headers[0] = new BasicHeader("uap-server-type", uapServerType);
//        headers[1] = new BasicHeader("uap-request-no", uapRequestNo);
//        headers[2] = new BasicHeader("uap-user-no", uapUserNo);
//        headers[3] = new BasicHeader("uap-licence-key", uapLicenceKey);
//        headers[4] = new BasicHeader("uap-request-id", uapRequestId);
//        httpPost.setHeaders(headers);
//        // 获得签名
//        String sign = getSign(pfxIs, pfxFilePwd, companyId, timeStramp, businessparam);
//        List params = new ArrayList();
//        params.add(new BasicNameValuePair("companyid", companyId));
//        params.add(new BasicNameValuePair("timestamp", timeStramp));
//        params.add(new BasicNameValuePair("signature", sign));
//        params.add(new BasicNameValuePair("businessparam", businessparam));
//        // 创建表单的Entity对象,第一个参数是封装好的表单数据，第二个参数就是编码方式
//        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "utf8");
//        //设置表单的Entity对象到Post请求中
//        httpPost.setEntity(formEntity);
//        //使用httpClient发起响应获取repsonse
//        CloseableHttpResponse response = null;
//        try {
//            response = httpClient.execute(httpPost);
//            //4.解析响应，获取数据
//            //判断状态码是否是200
//            if (response.getStatusLine().getStatusCode() == 200) {
//                org.apache.http.HttpEntity httpEntity = response.getEntity();
//                String content = EntityUtils.toString(httpEntity, "utf8");
//                System.out.println("请求结果是：" + content.length());
//                return content;
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            try {
//                if(response!=null){
//                    response.close();
//                }
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//            try {
//                httpClient.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//        log.info(JSON.toJSONString(response));
//        log.info("查询失败！");
//        return null;
//    }
}
