package cn.quant.baa.pay.service;

import cn.quant.baa.pay.acquirer.AcquirerProperties;
import cn.quant.baa.pay.acquirer.AcquirerPropertiesSource;
import cn.quant.baa.pay.component.ModelBuilder;
import cn.quant.baa.pay.config.LocalCacheConfiguration;
import cn.quant.baa.pay.model.web.MerchantAcquirerProperties;
import cn.quant.baa.pay.model.web.MerchantChannelRequestData;
import cn.quant.baa.pay.model.web.MerchantChannelResponseData;
import cn.quant.spring.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Map;

/**
 * Created by Administrator on 2021/8/23 0023.
 */
@Service
public class MerchantStorageService {
    @Autowired
    private AcquirerPropertiesSource acquirerPropertiesSource;

    @Autowired
    private ModelBuilder modelBuilder;

    @Autowired
    private CacheManager cacheManager;

    @Cacheable(cacheManager = LocalCacheConfiguration.LOCAL_CACHE_MANAGER
            , cacheNames = LocalCacheConfiguration.LOCAL_CACHE_ACQUIRER
            , key = "'MerchantChannel$'+#requestData.persistentKey")
    public Map<String, MerchantChannelResponseData> getChannels(MerchantChannelRequestData requestData) {
        String mchId = requestData.getMchId();
        String channel = requestData.getChannel();
        Map<String, Collection<AcquirerProperties>> profiles;

        if (StringUtils.isEmpty(channel)) {
            profiles = acquirerPropertiesSource.get(mchId);
        } else {
            profiles = acquirerPropertiesSource.get(mchId, channel);
        }

        Map<String, MerchantChannelResponseData> response = modelBuilder.toModel(profiles, requestData.getAccess());
        return response;
    }

    @Cacheable(cacheManager = LocalCacheConfiguration.LOCAL_CACHE_MANAGER
            , cacheNames = LocalCacheConfiguration.LOCAL_CACHE_ACQUIRER
            , key = "'MerchantChannel$'+#id")
    public MerchantAcquirerProperties getChannel(Long id) {
        AcquirerProperties profile = acquirerPropertiesSource.get(id);
        return modelBuilder.toModel(profile);
    }
}
