package cn.com.ty.lift.ud.pay.alipay;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;

import lombok.Data;

/**
 * 支付宝配置信息
 * @author sKing
 * 2020年5月15日
 */
@Data
@Component
//@PropertySource(value = "alipay/alipay-online.properties")//正式环境
//@PropertySource(value = "alipay/alipay_pc.properties")
@PropertySource(value = "alipay/alipay-app.properties")
//@PropertySource(value = "alipay/alipay-test.properties")//本地测试正式环境
@ConfigurationProperties(prefix = "alipay")
public class AlipayConfig {
    
    private final Logger logger = LoggerFactory.getLogger(AlipayConfig.class);

    /**
     * 应用私钥
     */
    private String appPrivateKey;

    /**
     * 应用APPID
     */
    private String appid;

    /**
     * 应用公钥证书文件绝对路径
     */
    private String appCertPath;

    /**
     * 支付宝公钥证书文件绝对路径
     */
    private String alipayCertPath;

    /**
     * 支付宝CA根证书文件绝对路径
     */
    private String alipayRootCertPath;
    

    /**
     * 支付宝网关
     */
    private String openApiDomain;

    /**
     * 支付回调地址
     */
    private String alipayNotifyUrl;

    /**
     * 字符集
     */
    private String charset;

    /**
     * 签名类型
     */
    private String signType;

    /**
     * 格式
     */
    private String format;
    
    /**
     * 公司名称
     */
    private String subjectName;
    
    @Bean
    public AlipayClient alipayClient() {
        // 构建公共的证书请求对象
        CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
        certAlipayRequest.setServerUrl(this.getOpenApiDomain());
        certAlipayRequest.setAppId(this.getAppid());
        certAlipayRequest.setPrivateKey(this.getAppPrivateKey());
        certAlipayRequest.setFormat(this.getFormat());
        certAlipayRequest.setCharset(this.getCharset());
        certAlipayRequest.setSignType(this.getSignType());
        certAlipayRequest.setCertPath(this.getAppCertPath());
        certAlipayRequest.setAlipayPublicCertPath(this.getAlipayCertPath());
        certAlipayRequest.setRootCertPath(this.getAlipayRootCertPath());
        try {
            // alipayClient 只需要初始化一次，后续调用不同的 API 都可以使用同一个 alipayClient 对象。
            return new DefaultAlipayClient(certAlipayRequest);
        } catch (AlipayApiException e) {
            logger.error("====使用CertAlipayRequest构建DefaultAlipayClient发生异常====");
            logger.error(e.getMessage());
            return new DefaultAlipayClient(this.getOpenApiDomain(), this.getAppid(), this.getAppPrivateKey());
        }
    }

}
