package cn.iocoder.yudao.util;


import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
import com.wechat.pay.contrib.apache.httpclient.auth.Verifier;
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.cert.CertificatesManager;
import com.wechat.pay.contrib.apache.httpclient.exception.HttpCodeException;
import com.wechat.pay.contrib.apache.httpclient.exception.NotFoundException;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.PrivateKey;

/**
 * @Author:
 * @Description:
 **/
@Component
@Data
@Slf4j
public class WechatPayConfig {
    /**
     * 应用编号
     */
    private String appId="wxe6518d72cb71a852";
    /**
     * 商户号
     */
    private String mchId="1625105516";
    /**
     * 服务商商户号
     */
    private String slMchId="1652687637";
    /**
     * APIv2密钥
     */
    private String apiKey="";
    /**
     * APIv3密钥
     */
    private String apiV3Key="9FA68244F52293311637F7AE2C516CA2";
    /**
     * 支付通知回调地址
     */
    private String notifyUrl="https://www.nuoyunr.com/admin-api/rescuePayApi/payNotify";
    private String jcNotifyUrl="https://www.nuoyunr.com/admin-api/payApi/payNotify";
    /**
     * 退款回调地址
     */
    private String refundNotifyUrl="https://www.nuoyunr.com/jdcJc/notify/refundNotify";
    /**
     * 汽修通知回调地址
     */
    private String repairNotifyUrl="https://www.nuoyunr.com/userClient/pay/payNotify";
    /**
     * API 证书中的 key.pem
     */
    private String keyPemPath="apiclient_key.pem";

    /**
     * 商户序列号
     */
    private String serialNo="1CF257917547049CDEED041FF683E29FABAF99CB";
    private String appSecret="ab94673dd0cca78abd0a453d0aac9f98";
    /**
     * 微信支付V3-url前缀
     */
    private String baseUrl;

    private String jxAppId = "wx684fc832e96cee65";
    private String jxAppSecret = "d1fecac806c5f3cd9aca9f3d5c3759c7";


    private String jcAppId = "wx5eeea06aeaae4f89";
    private String jcAppSecret = "42207958589342d9d1d287b9cb53e289";
    private String jcRefundNotifyUrl="https://www.nuoyunr.com/admin-api/payApi/refundNotify";

    private String repairAppId="wxee677d54037bc5ac";


    private String repairAppSecret="774bcddc165287da47b0b72b31f1c0a0";
    /**
     * 获取商户的私钥文件
     * @param keyPemPath
     * @return
     */
    public PrivateKey getPrivateKey(String keyPemPath){
        log.info("进入获取");
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(keyPemPath);
        if(inputStream==null){
            log.info("私钥文件不存在");
            throw new RuntimeException("私钥文件不存在");
        }
        log.info("存在");
        return PemUtil.loadPrivateKey(inputStream);
    }

    /**
     * 获取证书管理器实例
     * @return
     */
    @Bean
    public  Verifier getVerifier() throws GeneralSecurityException, IOException, HttpCodeException, NotFoundException {

        log.info("获取证书管理器实例");

        //获取商户私钥
        PrivateKey privateKey = getPrivateKey(keyPemPath);

        //私钥签名对象
        PrivateKeySigner privateKeySigner = new PrivateKeySigner(serialNo, privateKey);

        //身份认证对象
        WechatPay2Credentials wechatPay2Credentials = new WechatPay2Credentials(mchId, privateKeySigner);

        // 使用定时更新的签名验证器，不需要传入证书
        CertificatesManager certificatesManager = CertificatesManager.getInstance();
        certificatesManager.putMerchant(mchId,wechatPay2Credentials,apiV3Key.getBytes(StandardCharsets.UTF_8));

        return certificatesManager.getVerifier(mchId);
    }


    /**
     * 获取支付http请求对象
     * @param verifier
     * @return
     */
    @Bean(name = "wxPayClient")
    public CloseableHttpClient getWxPayClient(Verifier verifier)  {

        //获取商户私钥
        PrivateKey privateKey = getPrivateKey(keyPemPath);

        WechatPayHttpClientBuilder builder = WechatPayHttpClientBuilder.create()
                .withMerchant(mchId, serialNo, privateKey)
                .withValidator(new WechatPay2Validator(verifier));

        // 通过WechatPayHttpClientBuilder构造的HttpClient，会自动的处理签名和验签，并进行证书自动更新
        return builder.build();
    }

    /**
     * 获取HttpClient，无需进行应答签名验证，跳过验签的流程
     */
    @Bean(name = "wxPayNoSignClient")
    public CloseableHttpClient getWxPayNoSignClient(){

        //获取商户私钥
        PrivateKey privateKey = getPrivateKey(keyPemPath);

        //用于构造HttpClient
        WechatPayHttpClientBuilder builder = WechatPayHttpClientBuilder.create()
                //设置商户信息
                .withMerchant(mchId, serialNo, privateKey)
                //无需进行签名验证、通过withValidator((response) -> true)实现
                .withValidator((response) -> true);

        // 通过WechatPayHttpClientBuilder构造的HttpClient，会自动的处理签名和验签，并进行证书自动更新
        return builder.build();
    }
}

