package com.cyksj.config.zfb;

import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.mapper.channel.ShopConfigMapper;
import com.cyksj.model.entity.ShopConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/*
 *项目名: netflix
 *文件名: AliPayClientFactory
 *创建者: JavaZou
 *创建时间:2022/11/2 11:18
 */
@Component
public class AliPayClientFactory {
	/**
	 * 支付宝证书路径
	 */
	private static final String ALIPAY_CERT_PATH = "cert/alipay";

	/**
	 * 应用公钥证书名字
	 */
	private static final String ALIPAY_APP_PUBLIC_CERT_NAME = "appCertPublicKey.crt";

	/**
	 * 支付宝公钥证书名字
	 */
	private static final String ALIPAY_PUBLIC_CERT_NAME = "alipayCertPublicKey_RSA2.crt";

	/**
	 * 支付宝根证书名字
	 */
	private static final String ALIPAY_ROOT_CERT_NAME = "alipayRootCert.crt";

	private static Map<String, AlipayClient> alipayClientMap = new ConcurrentHashMap<>();

	@Autowired
	private ShopConfigMapper shopConfigMapper;

	/**
	 * 初始化
	 */
	@PostConstruct
	public void initAliPayClient() {
		List<ShopConfig> zfbShopConfig = shopConfigMapper.selectList(Wrappers.lambdaQuery(ShopConfig.class)
				.eq(ShopConfig::getType, "zfb"));
		zfbShopConfig.forEach(config -> {
			AlipayConfig alipayConfig = new AlipayConfig();
			//网关地址
			alipayConfig.setServerUrl(BaseZfbConfig.url);
			alipayConfig.setAppId(config.getAppId());
			alipayConfig.setPrivateKey(config.getAppPrivateKey());
			alipayConfig.setFormat(BaseZfbConfig.format);
			alipayConfig.setCharset(BaseZfbConfig.charset);
			alipayConfig.setSignType(BaseZfbConfig.signType);
			if (config.getIsCert()) {
				String shopId = config.getAppId();
				// 设置应用公钥证书路径
				alipayConfig.setAppCertPath(String.format("%s/%s/%s", ALIPAY_CERT_PATH, shopId, ALIPAY_APP_PUBLIC_CERT_NAME));
				// 设置支付宝公钥证书路径
				alipayConfig.setAlipayPublicCertPath(String.format("%s/%s/%s", ALIPAY_CERT_PATH, shopId, ALIPAY_PUBLIC_CERT_NAME));
				// 设置支付宝根证书路径
				alipayConfig.setRootCertPath(String.format("%s/%s/%s", ALIPAY_CERT_PATH, shopId, ALIPAY_ROOT_CERT_NAME));
			}
			AlipayClient alipayClient = null;
			try {
				alipayClient = new DefaultAlipayClient(alipayConfig);
			} catch (Exception e) {
				return;
			}
			alipayClientMap.putIfAbsent(config.getAppId(), alipayClient);
		});
	}

	public static AlipayClient getAlipayClient(String shopId) {
		AlipayClient alipayClient = alipayClientMap.get(shopId);
		if (alipayClient == null) {
			throw BusinessRuntimeException.getInstance("未配置该支付宝商户");
		}
		return alipayClient;
	}
}
