package com.brilliance.isc.common.cache.adr;

import com.brilliance.isc.bo.Adr;
import com.brilliance.isc.mda.dao.AdrMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class AdrCacheServiceImpl implements AdrCacheService {

    private static Logger log = LoggerFactory.getLogger(AdrCacheServiceImpl.class);

    private static final String TYPE = "ADR";

    private static final long EXPIRETIMES = 360l;

    private static final TimeUnit EXPIRETYPE = TimeUnit.SECONDS;

    @Autowired
    @Qualifier("jacksonRedisTemplate")
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private AdrMapper adrMapper;

    @Override
    public Adr getAdrByInr(String inr) {
        String key = generatekey(inr);
        Adr adr = (Adr) redisTemplate.opsForValue().get(key);
        if (adr == null) {
            log.debug("Redis中不存在key：" + key + "或者已经过期，查数据库");
            adr = adrMapper.selectByInr(inr);
            redisTemplate.opsForValue().set(key, adr, EXPIRETIMES, EXPIRETYPE);
            return adr;
        } else {
            log.debug("Redis中存在key：" + key + "直接返回");
            return adr;
        }
    }

    @Override
    public Adr selectByPtaInr(String ptainr) {
        String key = generatekey("PTAINR_" + ptainr);
        Adr adr = (Adr) redisTemplate.opsForValue().get(key);
        if (adr == null) {
            log.debug("Redis中不存在key：" + key + "或者已经过期，查数据库");
            adr = adrMapper.selectByPtaInr(ptainr);
            redisTemplate.opsForValue().set(key, adr, EXPIRETIMES, EXPIRETYPE);
            return adr;
        } else {
            log.debug("Redis中存在key：" + key + "直接返回");
            return adr;
        }
    }

    public String generatekey(String inr) {
        return TYPE + "_" + inr;
    }
}
