package com.quantgroup.asset.distribution.service.aid.impl;

import com.quantgroup.asset.distribution.service.aid.IAidFundInfoConfigService;
import com.quantgroup.asset.distribution.service.jpa.entity.AidFundInfoConfig;
import com.quantgroup.asset.distribution.service.jpa.repository.IAidFundInfoConfigRepository;
import com.quantgroup.asset.distribution.service.redis.IRedisService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author : Hyuk
 * @description : AidFundInfoConfigServiceImpl
 * @date : 2020/6/9 8:21 下午
 */
@Slf4j
@Service
public class AidFundInfoConfigServiceImpl implements IAidFundInfoConfigService {

    @Autowired
    private IAidFundInfoConfigRepository aidFundInfoConfigRepository;
    @Autowired
    private IRedisService<AidFundInfoConfig> redisService;

    private static final String AID_FUND_INFO_CONFIG_KEY_PREFIX = "ASSET_DISTRIBUTION:AID_FUND_INFO_CONFIG:AMV8N:";

    @Override
    public AidFundInfoConfig findAidFundInfo(String fundId, String fundProductId) {
        String redisKey = getAidFundInfoConfigKey(fundId, fundProductId);
        AidFundInfoConfig aidFundInfoConfig = redisService.getEntity(redisKey);
        if (aidFundInfoConfig == null) {
            List<AidFundInfoConfig> aidFundInfoConfigs = aidFundInfoConfigRepository.findByFundIdAndFundProductIdAndEnableIsTrue(fundId, fundProductId);
            if (CollectionUtils.isNotEmpty(aidFundInfoConfigs)) {
                aidFundInfoConfig = aidFundInfoConfigs.get(0);
                redisService.setEntityEx(redisKey, aidFundInfoConfig, 5, TimeUnit.MINUTES);
            }
        }
        return aidFundInfoConfig;
    }

    @Override
    public void clearAidFundInfoCache(String fundId, String fundProductId) {
        redisService.del(getAidFundInfoConfigKey(fundId, fundProductId));
    }

    /**
     * 获取AidFundInfoConfig缓存key
     * @param fundId
     * @param fundProductId
     * @return
     */
    private String getAidFundInfoConfigKey(String fundId, String fundProductId) {
        StringBuilder sb = new StringBuilder(AID_FUND_INFO_CONFIG_KEY_PREFIX);
        sb.append(fundId).append(":").append(fundProductId);
        return sb.toString();
    }
}
