package org.springblade.common.config;

import com.alipay.api.*;
import org.springblade.common.constant.AlipayUrlConstants;
import org.springblade.modules.finance.pay.entity.AlipayProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Objects;

/**
 * 支付宝客户端自动配置
 *
 * @author xuwei
 *
 */
@Configuration
@EnableConfigurationProperties(AlipayProperties.class)
public class ApilayAutoConfiguration {

    private static final String ERROR_MSG_APPID_NULL = "alipay application's appid cann't be null";

    private static final String ERROR_MSG_PRIVATE_KEY_NULL = "alipay application's privateKey cann't be null";

    private static final String ERROR_MSG_ALIPAY_PUBLIC_KEY_NULL = "alipay's publicKey cann't be null";

    /**
     * 构造支付宝客户端
     *
     * @param properties
     *            支付宝配置
     * @return 支付宝客户端
     */
    @Bean
    public AlipayClient alipayClient(AlipayProperties properties) throws AlipayApiException {
		AlipayConfig alipayConfig = new AlipayConfig();
        String gatewayUrl = AlipayUrlConstants.gateway(properties.isDev());
        String appId = Objects.requireNonNull(properties.getAppId(), ERROR_MSG_APPID_NULL);
        String privateKey = Objects.requireNonNull(properties.getPrivateKey(), ERROR_MSG_PRIVATE_KEY_NULL);
        String format = AlipayConstants.FORMAT_JSON;
        String charset = AlipayConstants.CHARSET_UTF8;
        String alipayPublicKey = Objects.requireNonNull(properties.getAlipayPublicKey(),
                ERROR_MSG_ALIPAY_PUBLIC_KEY_NULL);
        String signType = AlipayConstants.SIGN_TYPE_RSA.equals(properties.getSignType()) ? AlipayConstants.SIGN_TYPE_RSA
                : AlipayConstants.SIGN_TYPE_RSA2;
		alipayConfig.setServerUrl(gatewayUrl);
		alipayConfig.setAppId(appId);
		alipayConfig.setPrivateKey(privateKey);
		alipayConfig.setFormat(format);
		alipayConfig.setAlipayPublicKey(alipayPublicKey);
		alipayConfig.setCharset(charset);
		alipayConfig.setSignType(signType);
		//设置应用公钥证书路径//appCertPublicKey_2021003125657245
		alipayConfig.setAppCertPath(properties.getAppCertPath());
		//设置支付宝公钥证书路径//alipayCertPublicKey_RSA2
		alipayConfig.setAlipayPublicCertPath(properties.getAliPayRootCertPath());
		//设置支付宝根证书路径
		alipayConfig.setRootCertPath(properties.getAliPayRootCertPath());
		//return new DefaultAlipayClient(gatewayUrl, appId, privateKey, format, charset, alipayPublicKey, signType);
		return new DefaultAlipayClient(alipayConfig);
    }
}
