package com.ghy.common.adapay;

import com.ghy.common.adapay.model.Merchant;
import com.huifu.adapay.Adapay;
import com.huifu.adapay.model.MerConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.Assert;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Adapay 配置
 *
 * @author HH 2022/3/25
 */
@Configuration
@EnableConfigurationProperties(AdapayProperties.class)
public class AdapayConfig {

    private static final Logger logger = LoggerFactory.getLogger(AdapayConfig.class);

    /**
     * 商户配置
     */
    private static Set<Merchant> merchants;

    /**
     * deptId -> Merchant
     */
    private static Map<Long, Merchant> merchantMap;

    public static void initAdapay(AdapayProperties properties) throws Exception {
        Adapay.debug = properties.isDebug();
        Adapay.prodMode = properties.isProdMode();
        Assert.hasText(properties.getNotifyUrl(), "NotifyUrl is blank!");
        Assert.notEmpty(merchants, "Merchants is empty!");
        Map<String, MerConfig> configPathMap = new HashMap<>(merchants.size());
        for (Merchant merchant : merchants) {
            logger.info("Adapay load merchant : {}", merchant.getDeptId());
            check(merchant);
            MerConfig merConfig = new MerConfig();
            merConfig.setApiKey(merchant.getApiKey());
            merConfig.setApiMockKey(merchant.getMockApiKey());
            merConfig.setRSAPrivateKey(merchant.getRsaPrivateKey());
            configPathMap.put(merchant.getDeptId().toString(), merConfig);
        }
        Adapay.initWithMerConfigs(configPathMap);
    }

    private static void check(Merchant merchant) {
        Assert.notNull(merchant.getDeptId(), "DeptId is null!");
        Assert.hasText(merchant.getAppId(), "AppId is blank!");
        Assert.hasText(merchant.getApiKey(), "ApiKey is blank!");
        Assert.hasText(merchant.getMockApiKey(), "MockApiKey is blank!");
        Assert.hasText(merchant.getRsaPrivateKey(), "RsaPrivateKey is blank!");
    }

    public static void setMerchants(Set<Merchant> merchants) {
        AdapayConfig.merchants = merchants;
        AdapayConfig.merchantMap = merchants.stream().collect(Collectors.toMap(Merchant::getDeptId, x -> x));
    }

    public static String getAppId(Long deptId) {
        Merchant merchant = merchantMap.get(deptId);
        Assert.notNull(merchant, String.format("Merchant[%s] notfound!", deptId));
        return merchant.getAppId();
    }

    public static Set<Merchant> getMerchants() {
        return merchants;
    }
}