package com.njzscloud.supervisory.wxPay.config;

import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.service.ProfitSharingService;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StreamUtils;

/**
 * @author ljw
 */
@Configuration
@ConditionalOnClass(WxPayService.class)
@EnableConfigurationProperties(WxPayProperties.class)
@AllArgsConstructor
public class WxPayConfiguration {

    private final WxPayProperties properties;

    @Bean
    @ConditionalOnMissingBean
    public WxPayService wxService() {
        WxPayConfig config = new WxPayConfig();
        config.setAppId(StringUtils.trimToNull(this.properties.getAppId()));
        config.setMchId(StringUtils.trimToNull(this.properties.getMchId()));
        config.setMchKey(StringUtils.trimToNull(this.properties.getApiKey()));
        String keyPath = StringUtils.trimToNull(this.properties.getPrivateKeyPath());
        config.setKeyPath(keyPath);

        // 优先支持以 classpath: 开头的 p12 证书路径，直接加载为内存字节，避免路径解析兼容性问题
       if (StringUtils.isNotBlank(keyPath) && keyPath.startsWith("classpath:")) {
           String classpathLocation = keyPath.substring("classpath:".length());
           try {
               ClassPathResource resource = new ClassPathResource(classpathLocation.startsWith("/") ? classpathLocation.substring(1) : classpathLocation);
               if (resource.exists()) {
                   byte[] keyBytes = StreamUtils.copyToByteArray(resource.getInputStream());
                   config.setKeyContent(keyBytes);
               }
           } catch (Exception ignored) {
               // 忽略此处异常，保持 SDK 以文件路径方式继续尝试读取
           }
       }
        // 可以指定是否使用沙箱环境
        // config.setUseSandboxEnv(false);
        WxPayService wxPayService = new WxPayServiceImpl();
        wxPayService.setConfig(config);
        return wxPayService;
    }

    @Bean
    @ConditionalOnMissingBean
    public ProfitSharingService profitSharingService(WxPayService wxPayService) {
        return wxPayService.getProfitSharingService();
    }
}
