package com.hzs.third.pay.jdpay.sdk;

import com.hzs.third.pay.jdpay.util.JdPayApiUtil;
import lombok.extern.slf4j.Slf4j;

import java.security.SecureRandom;
import java.util.Random;

@Slf4j
public class JdPayHttpClientProxy {

    private static final Random RANDOM = new SecureRandom();

    private final JdPayNewConfig jdPayNewConfig;

    private final JdPayHttpClient jdPayHttpClient;

    public JdPayHttpClientProxy(JdPayNewConfig jdPayNewConfig, JdPayHttpClient jdPayHttpClient) {
        this.jdPayNewConfig = jdPayNewConfig;
        this.jdPayHttpClient = jdPayHttpClient;
    }

    /**
     * 获取随机字符串，含数字和大小写英文字母
     */
    private static String genNonceStr() {
        char[] nonceChars = new char[32];
        for (int index = 0; index < nonceChars.length; ++index) {
            nonceChars[index] = JdPayConstant.SYMBOLS.charAt(RANDOM.nextInt(JdPayConstant.SYMBOLS.length()));
        }
        return new String(nonceChars);
    }

    public String execute(String urlSuffix, String request) throws Exception {
        long startTimestampMs = System.currentTimeMillis();
        String response;
        // 接口名称
        String apiName = urlSuffix.replaceFirst(JdPayConstant.URL_PATH, "");
        // 唯一请求号
        String reqNo = genNonceStr();
        try {
            log.info("1.{}接口请求参数:{}", apiName, request);
            // 请求参数加密和签名
            String httpRequest = JdPayApiUtil.encryptAndSignature(jdPayNewConfig, reqNo, request);
            log.info("2.{}远程调用请求参数:{}", apiName, httpRequest);
            String httpResponse = jdPayHttpClient.execute(jdPayNewConfig, urlSuffix, httpRequest);
            log.info("3.{}远程调用返回参数:{}", apiName, httpResponse);
            // 验证和解析返回参数
            response = JdPayApiUtil.decryptAndVerifySign(jdPayNewConfig, httpResponse);
            log.info("4.{}耗时:{},接口返回参数:{}", apiName, (System.currentTimeMillis() - startTimestampMs), response);
        } catch (Exception e) {
            log.error("{}远程调用异常,接口参数:{}", apiName, request, e);
            throw e;
        }
        return response;
    }

}
