package cn.quantgroup.xyqb.service.merchant.impl;

import cn.quantgroup.xyqb.entity.Merchant;
import cn.quantgroup.xyqb.entity.MerchantConfig;
import cn.quantgroup.xyqb.repository.IMerchantConfigRepository;
import cn.quantgroup.xyqb.repository.IMerchantRepository;
import cn.quantgroup.xyqb.service.merchant.IMerchantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

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

/**
 * Created by Miraculous on 2017/1/3.
 */
@Service
public class MerchantServiceImpl implements IMerchantService {

    private static final ConcurrentHashMap<String, Merchant> MERCHANT_NAME_MAP = new ConcurrentHashMap<>();
    private static final ConcurrentHashMap<Long, Merchant> MERCHANT_ID_MAP = new ConcurrentHashMap<>();
    private static final ConcurrentHashMap<String, MerchantConfig> MERCHANT_ID_CONFIG_MAP = new ConcurrentHashMap<>();

    @Autowired
    private IMerchantRepository merchantRepository;
    @Autowired
    private IMerchantConfigRepository merchantConfigRepository;

    @PostConstruct
    private void init() {
        List<Merchant> merchantList = merchantRepository.findAll();
        List<MerchantConfig> merchantConfigList = merchantConfigRepository.findAll();
        merchantList.forEach(m -> {
            MERCHANT_NAME_MAP.put(m.getName(), m);
            MERCHANT_ID_MAP.put(m.getId(), m);
        });

        merchantConfigList.forEach(m -> MERCHANT_ID_CONFIG_MAP.put(m.getMerchantId() + "_" + m.getConfigName(), m));

    }

    @Override
    public MerchantConfig findConfigByMerchantIdAndConfigName(Long merchantId, String configName) {
        String key = merchantId + "_" + configName;
        return MERCHANT_ID_CONFIG_MAP.getOrDefault(key, null);
    }

    @Override
    public Merchant findMerchantById(Long merchantId) {
        return MERCHANT_ID_MAP.getOrDefault(merchantId, null);
    }

    @Override
    public Merchant findMerchantByName(String name) {
        if (StringUtils.isEmpty(name)) {
            return null;
        }
        return MERCHANT_NAME_MAP.getOrDefault(name, null);
    }

}
