package com.miaxis.common.config;

import com.miaxis.common.utils.uuid.CommonUtils;
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.WechatPay2Validator;
import org.apache.http.client.HttpClient;
import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

import java.io.File;
import java.io.FileReader;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.X509EncodedKeySpec;


@Configuration
public class BeanConfig {


    @Autowired
    private WxpayConfig wxpayConfig;
    @Autowired
    private AutoUpdateCertificatesVerifier verifier;

    /**
     * 腾讯云 COS
     * @return
     */




    /**
     * 微信支付 httpclient 对象
     * @return
     * @throws Exception
     */
    @Bean
    public HttpClient wxpayConfigBean() throws Exception{
        File file = new ClassPathResource("wechatpay/apiclient_key.pem").getFile();
        String realPath =file.getAbsolutePath();
        PrivateKey privateKey = CommonUtils.getPrivateKey(realPath);
        // 初始化httpClient
        HttpClient httpClient = WechatPayHttpClientBuilder.create()
                .withMerchant(wxpayConfig.getMerchantId(), wxpayConfig.getSerialNumber(), privateKey)
                .withValidator(new WechatPay2Validator(verifier)).build();
        return httpClient;

    }


    /**
     * 创建微信公钥 对象
     * @return
     * @throws Exception
     */
    @Bean
    public RSAPublicKey readPublicKey() throws Exception {
        KeyFactory factory = KeyFactory.getInstance("RSA");

        File file = new ClassPathResource("wechatpay/public.pem").getFile();
        try (FileReader keyReader = new FileReader(file);
             PemReader pemReader = new PemReader(keyReader)) {

            PemObject pemObject = pemReader.readPemObject();
            byte[] content = pemObject.getContent();
            X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(content);
            return (RSAPublicKey) factory.generatePublic(pubKeySpec);
        }
    }




}
