package com.cpop.pay.framewok.config.ecpp;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.HexUtil;
import cn.hutool.crypto.asymmetric.Sign;
import cn.hutool.crypto.asymmetric.SignAlgorithm;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cpop.pay.framewok.core.request.ecpp.EcppBaseRequest;
import com.cpop.pay.framewok.core.request.ecpp.EcppVerifyRequest;
import com.cpop.pay.framewok.core.response.ecpp.EcppVerifyResponse;
import com.google.common.base.Joiner;
import lombok.Getter;
import lombok.Setter;
import okhttp3.*;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import javax.crypto.Cipher;
import javax.net.ssl.*;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.cert.X509Certificate;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * Description 数字人民币API配置类
 * @authors DB
 * @date    2023-11-24 17:27:07
 * @version 1.0.0
 */
@Getter
@Configuration
@EnableConfigurationProperties(EcppProperties.class)
public class EcppConfiguration {

    EcppProperties ecppProperties;

    public EcppConfiguration(EcppProperties ecppProperties) {
        this.ecppProperties = ecppProperties;
    }

    @Setter
    private volatile String jSessionId;

    @Setter
    private volatile String sessionKey;

    @Setter
    private volatile String sessionIv;

    /**
     * 发送数币请求
     * @author DB
     * @since 2024/1/29
     * @param url 路径
     * @param dto 请求数据
     * @return Response
     */
    public <T extends EcppVerifyRequest> Response sendEcppPost(String url, T ecppRequest) throws IOException {
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        MediaType mediaType = MediaType.Companion.parse("application/json;charset=utf-8");
        EcppBaseRequest ecppBaseRequest = new EcppBaseRequest(ecppRequest);
        RequestBody body = RequestBody.Companion.create(JSONObject.toJSONString(ecppBaseRequest), mediaType);
        String timestamp = String.valueOf(System.currentTimeMillis());
        Request request = new Request
                .Builder()
                .url(url)
                .post(body)
                .addHeader("Content-Type", "application/json")
                //.addHeader("VERIFY",getVerify(timestamp))
                .addHeader("ecpp-header",getEcppHeader(timestamp))
                .build();
        return client.newCall(request).execute();
    }

    /**
     * 发送数币请求
     * @author DB
     * @since 2024/1/29
     * @param url 路径
     * @param jsonBody 请求数据
     * @return Response
     */
    public Response sendEcppPost(String url, String jsonBody) throws IOException {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .sslSocketFactory(getSslSocketFactory(), getX509TrustManager())
                .hostnameVerifier(getHostnameVerifier())
                .build();
        MediaType mediaType = MediaType.Companion.parse("application/json;charset=utf-8");
        RequestBody body = RequestBody.Companion.create(jsonBody, mediaType);
        String timestamp = String.valueOf(System.currentTimeMillis());
        Request request = new Request
                .Builder()
                .url(url)
                .post(body)
                .addHeader("Content-Type", "application/json")
                .addHeader("VERIFY",getVerify(timestamp))
                .addHeader("ecpp-header",getEcppHeader(timestamp))
                .build();
        return client.newCall(request).execute();
    }

    public <V extends EcppVerifyResponse> V parseEcppResponse(Response response, Class<V> clazz) throws IOException {
        //读取响应体
        ResponseBody body = response.body();
        JSONObject result = JSONObject.parseObject(body.string());
        if (result == null) {
            throw new IOException("Http响应为空");
        }
        return JSON.parseObject(result.getString("data"), clazz);
    }

    /**
     * 获取认证
     * @author DB
     * @since 2024/1/29
     * @param timestamp 时间戳
     * @return String
     */
    private String getVerify(String timestamp) {
        List<String> args = new ArrayList<>();
        args.add(ecppProperties.getAppType());
        args.add(ecppProperties.getAppId());
        args.add(sha256withRsaSign(timestamp));
        args.add(timestamp);
        return Joiner.on(':').join(args);
    }

    /**
     * 获取请求头信息
     * @param timestamp 时间戳
     */
    private String getEcppHeader(String timestamp) {
        HashMap<String, String> ecppHeader = new HashMap<>(5);
        ecppHeader.put("appId", ecppProperties.getAppId());
        ecppHeader.put("signatureIdType", ecppProperties.getAppType());
        ecppHeader.put("signatureId", "100");
        ecppHeader.put("timestamp", timestamp);
        ecppHeader.put("signature", sha256withRsaSign(timestamp));
        return JSON.toJSONString(ecppHeader);
    }

    private String sha256withRsaSign(String dataSting) {
        Sign sign = new Sign(SignAlgorithm.SHA256withRSA, ecppProperties.getPrivateKey(), null);
        return Base64.encode(sign.sign(dataSting.getBytes(StandardCharsets.UTF_8)));
    }

    public String genSha256HexSign(String privateKey, String strSrc) {
        Sign sign = new Sign(SignAlgorithm.SHA256withRSA, privateKey, null);
        return HexUtil.encodeHexStr(sign.sign(strSrc.getBytes(StandardCharsets.UTF_8)));
    }

    public final long EXPIRE_TIME = 3300000;

    /**
     * 超时时间
     */
    @Setter
    private volatile long nextExpireTime = 0;

    public Boolean checkKeyTime() {
        return this.nextExpireTime > System.currentTimeMillis();
    }

    /**
     * 公钥加密
     *
     * @param publicKeyText 公钥
     * @param text          内容
     */
    public String encrypt(String publicKeyText, String text) throws Exception {
        X509EncodedKeySpec x509EncodedKeySpec2 = new X509EncodedKeySpec(Base64.decode(publicKeyText));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec2);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] result = cipher.doFinal(text.getBytes());
        return Base64.encode(result);
    }

    /**
     * 私钥解密
     * @author DB
     * @since 2024/1/29
     * @param privateKeyText 私钥内容
     * @param text 内容
     * @return String
     */
    public String decrypt(String privateKeyText, String text) throws Exception{
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec5 = new PKCS8EncodedKeySpec(Base64.decode(privateKeyText));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec5);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] result = cipher.doFinal(Base64.decode(text));
        return new String(result);
    }

    //获取这个SSLSocketFactory
    private SSLSocketFactory getSslSocketFactory() {
        try {
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, getTrustManager(), new SecureRandom());
            return sslContext.getSocketFactory();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    //获取TrustManager
    private TrustManager[] getTrustManager() {
        return new TrustManager[]{
                new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(X509Certificate[] chain, String authType) {
                    }

                    @Override
                    public void checkServerTrusted(X509Certificate[] chain, String authType) {
                    }

                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[]{};
                    }
                }
        };
    }

    //获取HostnameVerifier
    private HostnameVerifier getHostnameVerifier() {
        return (s, sslSession) -> true;
    }

    private X509TrustManager getX509TrustManager() {
        X509TrustManager trustManager = null;
        try {
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init((KeyStore) null);
            TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
            if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
                throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers));
            }
            trustManager = (X509TrustManager) trustManagers[0];
        } catch (Exception e) {
            e.printStackTrace();
        }
        return trustManager;
    }

}
