package com.softwarebr.nunu.config;

import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
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 java.io.IOException;

/**
 * @author xu
 * @date 2019/10/23 10:59
 */
@Configuration
@Slf4j
public class WxPayConfig {

    @Autowired
    ConfigService<PayConfig> payConfigService;

    public String appWeiXinCertPath() throws IOException {

      /*  String newFilePath = FileUtil.file("").getCanonicalPath() + File.separator + "crt" + File.separator + "apiclient_cert.p12";
        InputStream inputStream = WxPayConfig.class.getClassLoader().getResourceAsStream("apiclient_cert.p12");
        FileUtil.writeFromStream(inputStream, newFilePath);*/
        return null;
    }

    @Bean
    public com.github.binarywang.wxpay.config.WxPayConfig config() throws IOException {
        PayConfig payConfig = payConfigService.get();
        com.github.binarywang.wxpay.config.WxPayConfig wxPayConfig = new com.github.binarywang.wxpay.config.WxPayConfig();
        wxPayConfig.setAppId(payConfig.getWxAppId());
        wxPayConfig.setMchId(payConfig.getWxMchId());
        wxPayConfig.setMchKey(payConfig.getWxMchKey());
        wxPayConfig.setKeyPath(appWeiXinCertPath());
        wxPayConfig.setSignType(payConfig.getWxSignType());
        wxPayConfig.setNotifyUrl(payConfig.getWxOAuthRedirectUrl());
        return wxPayConfig;
    }

    @Bean
    public WxPayService wxPayService(com.github.binarywang.wxpay.config.WxPayConfig payConfig) {
        WxPayService wxPayService = new WxPayServiceImpl();
        wxPayService.setConfig(payConfig);
        return wxPayService;
    }
}
