package com.liquidnet.service.dragon.utils;

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 org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.FileInputStream;
import java.net.URL;
import java.security.PrivateKey;

public class PayWepayUtils {
    private CloseableHttpClient httpClient;
    //    private static PayUtils instance = new PayUtils();

    private String merchantId = "1551961491";
    private String merchantSerialNumber = "6D25ECC819EAE0BCEA7DB18F143F0752431D9295";
    private String appId = "wx3498304dda39c5a1";

    public PayWepayUtils() {
        System.out.println("1");
        try {
            URL path = PayWepayUtils.class.getClassLoader().getResource("payCert/wepay/wepay_apiclient_key.pem");
            PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(
                    new FileInputStream(path.getPath())
            );

            CloseableHttpClient httpClientTemp = WechatPayHttpClientBuilder.create()
                    .withMerchant(merchantId, merchantSerialNumber, merchantPrivateKey)
                    .withValidator(response -> true) // NOTE: 设置一个空的应答签名验证器，**不要**用在业务请求
                    .build();

            URIBuilder uriBuilder = new URIBuilder("https://api.mch.weixin.qq.com/v3/certificates");
            HttpGet httpGet = new HttpGet(uriBuilder.build());
            httpGet.addHeader("Accept", "application/json");
            CloseableHttpResponse response = httpClientTemp.execute(httpGet);
            String bodyAsString = EntityUtils.toString(response.getEntity());

            AutoUpdateCertificatesVerifier verifier = new AutoUpdateCertificatesVerifier(
                    new WechatPay2Credentials(merchantId, new PrivateKeySigner(merchantSerialNumber, merchantPrivateKey)),
                    bodyAsString.getBytes("utf-8"));

            WechatPayHttpClientBuilder builder = WechatPayHttpClientBuilder.create()
                    .withMerchant(merchantId, merchantSerialNumber, merchantPrivateKey)
                    .withValidator(new WechatPay2Validator(verifier));

            httpClient = builder.build();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//    private static PayUtils getInstance() {
//        return instance;
//    }


    public CloseableHttpClient getHttpClient() {
        return httpClient;
    }
}
