package com.fzm.mall.pay.util;

import com.fzm.mall.pay.config.WeChatPayConfig;
import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.auth.AutoUpdateCertificatesVerifier;
import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Validator;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.PrivateKey;

/**
 * @author wangp
 * @date 2021/4/15 15:37
 * @description 微信支付http工具类
 * @since JDK 1.8
 */
@Slf4j
@Component
public class WxPayHttpUtil {

    @Autowired
    private WeChatPayConfig config;

    private static CloseableHttpClient httpClient = null;
    private static RequestConfig requestConfig = null;

    /*@PostConstruct
    public void setup() {
        // 加载商户私钥（privateKey：私钥字符串）
        PrivateKey merchantPrivateKey = PemUtil
                .loadPrivateKey(new ByteArrayInputStream(config.getPrivateKey().getBytes(StandardCharsets.UTF_8)));

        // 加载平台证书（mchId：商户号,mchSerialNo：商户证书序列号,apiV3Key：V3秘钥）
        AutoUpdateCertificatesVerifier verifier = new AutoUpdateCertificatesVerifier(
                new WechatPay2Credentials(config.getMchId(), new PrivateKeySigner(config.getMchSerialNo(), merchantPrivateKey)),
                config.getApiV3Key().getBytes(StandardCharsets.UTF_8));

        // 初始化httpClient，通过WechatPayHttpClientBuilder构造的HttpClient，会自动的处理签名和验签，并进行证书自动更新
        httpClient = WechatPayHttpClientBuilder.create()
                .withMerchant(config.getMchId(), config.getMchSerialNo(), merchantPrivateKey)
                .withValidator(new WechatPay2Validator(verifier)).build();

        requestConfig = RequestConfig.custom()
                //设置连接超时
                .setConnectTimeout(35000)
                //设置从连接池获取连接实例的超时
                .setConnectionRequestTimeout(35000)
                //设置读取超时
                .setSocketTimeout(60000)
                .build();
    }*/

    public static String weChatPayHttpRequest(HttpRequestBase base) {
        String result = null;
        base.setConfig(requestConfig);

        try (CloseableHttpResponse response = httpClient.execute(base)) {
            result = EntityUtils.toString(response.getEntity());
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) { //处理成功
                log.info("success,return body = " + result);
            } else if (statusCode == 204) { //处理成功，无返回Body
                log.info("success");
                return "204";
            } else {
                log.info("failed,resp code = " + statusCode + ",return body = " + result);
                throw new IOException("request failed");
            }
        } catch (IOException e) {
            log.info(e.getMessage());
        }

        return result;
    }
}
