package com.leromro.framework.config;

import cn.hutool.core.io.FileUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import java.io.File;
import java.io.InputStream;

import com.leromro.common.utils.MyImgUtil;
import com.leromro.framework.config.properties.AliAdminPayProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AliConfig {

    @Autowired
    private AliAdminPayProperties adminPayProperties;


    @Bean
    public CertAlipayRequest aliTakePayClient() {
        CertAlipayRequest payConfig = new CertAlipayRequest();
        payConfig.setAppId(this.adminPayProperties.getAppId());
        payConfig.setPrivateKey(this.adminPayProperties.getPrivateKey());
        payConfig.setServerUrl(this.adminPayProperties.getServerUrl());
        payConfig.setSignType(this.adminPayProperties.getSignType());
        payConfig.setFormat("json");
        payConfig.setCharset("UTF8");
        try {
            InputStream certPathStream = getClass().getResourceAsStream("/appCertPublicKey_2021004131699060.crt");
            if (certPathStream != null) {
                File certPath = FileUtil.writeBytes(MyImgUtil.readInputStream(certPathStream), "appCertPublicKey_2021004131699060.crt");
                payConfig.setCertPath(certPath.getPath());
                InputStream alipayPublicCertStream = getClass().getResourceAsStream("/alipayCertPublicKey_RSA2.crt");
                File alipayPublicFile = FileUtil.writeBytes(MyImgUtil.readInputStream(alipayPublicCertStream), "alipayCertPublicKey_RSA2.crt");
                payConfig.setAlipayPublicCertPath(alipayPublicFile.getPath());
                InputStream rootCertStream = getClass().getResourceAsStream("/alipayRootCert.crt");
                File rootCertFile = FileUtil.writeBytes(MyImgUtil.readInputStream(rootCertStream), "alipayRootCert.crt");
                payConfig.setRootCertPath(rootCertFile.getPath());
            }
//            // 使用绝对路径指定证书文件
//            String certBasePath = "D:\\pay\\alipay\\";
//
//            payConfig.setCertPath(certBasePath + "appCertPublicKey_2021004131699060.crt");
//            payConfig.setAlipayPublicCertPath(certBasePath + "alipayCertPublicKey_RSA2.crt");
//            payConfig.setRootCertPath(certBasePath + "alipayRootCert.crt");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return payConfig;
    }

    @Bean
    public AlipayClient aliPayService(@Qualifier("aliTakePayClient") CertAlipayRequest payConfig) throws AlipayApiException {
        return new DefaultAlipayClient(payConfig);
    }
}