package com.softwarebr.nunu.config;

import cn.hutool.core.io.FileUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.softwarebr.nunu.util.UUIDGenerator;
import com.softwarebr.nunu.config.domain.ConfigService;
import com.softwarebr.nunu.domain.PayConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;

/**
 * @author xu
 * @date 2019/10/31 10:13
 */
@Configuration
@Slf4j
public class AliPayConfig {

    private static final String crtPath;
    static {
        String path = null;
        try {
            path = FileUtil.file("").getCanonicalPath() + File.separator + "crt" + File.separator;
        } catch (IOException e) {
        }
        crtPath = path;
        FileUtil.del(crtPath);
        FileUtil.file(crtPath).mkdir();
    }

    @Autowired
    ConfigService<PayConfig> payConfigConfigService;

    @Bean
    public AlipayClient appAlipayClient() throws AlipayApiException, IOException {
        PayConfig payConfig = this.payConfigConfigService.get();
        if(StringUtils.isEmpty(payConfig.getAppApAlipayPublicCertContent())){
            return null;
        }

        String alipayPublicCertPath = crtPath + genFileName("crt");
        String rootCertPath = crtPath + genFileName("crt");
        String certPath = crtPath + genFileName("crt");

        FileUtil.writeString(payConfig.getAppApAlipayPublicCertContent(), alipayPublicCertPath, Charset.forName("UTF-8"));
        log.info("证书alipayPublicCertPath加载完成，加载地址：{}", alipayPublicCertPath);
        FileUtil.writeString(payConfig.getAppApRootCertContent(), rootCertPath, Charset.forName("UTF-8"));
        log.info("证书rootCertPath加载完成，加载地址：{}", rootCertPath);
        FileUtil.writeString(payConfig.getAppApCertContent(), certPath, Charset.forName("UTF-8"));
        log.info("证书certPath加载完成，加载地址：{}", certPath);

        CertAlipayRequest request = new CertAlipayRequest();
        request.setServerUrl(payConfig.getApServerUrl());
        request.setAppId(payConfig.getAppApAppId());
        request.setPrivateKey(payConfig.getAppApPrivateKey());
        request.setFormat("json");
        request.setCharset("utf-8");
        request.setSignType("RSA2");

        request.setCertPath(certPath);
        request.setAlipayPublicCertPath(alipayPublicCertPath);
        request.setRootCertPath(rootCertPath);

        return new DefaultAlipayClient(request);
    }

    private String genFileName(String format){
        return UUIDGenerator.generateShortUuid() + "." + format;
    }

}
