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

import com.brilliance.isc.bo.Pta;
import com.brilliance.isc.mda.dao.PtaMapper;
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 PtaCacheServiceImpl implements PtaCacheService {

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

    private static final String TYPE = "PTA";

    private static final long EXPIRETIMES = 300l;

    private static final TimeUnit EXPIRETYPE = TimeUnit.SECONDS;

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

    @Autowired
    private PtaMapper ptaMapper;

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

    @Override
    public Pta selectByPtyInrAndUsg(String ptyinr, String usg) {
        String key = generatekey(ptyinr + "_" + usg);
        Pta pta = (Pta) redisTemplate.opsForValue().get(key);
        if (pta == null) {
            log.debug("Redis中不存在key：" + key + "或者已经过期，查数据库");
            pta = ptaMapper.selectByPtyInrAndUsg(ptyinr, usg);
            redisTemplate.opsForValue().set(key, pta, EXPIRETIMES, EXPIRETYPE);
            return pta;
        } else {
            log.debug("Redis中存在key：" + key + "直接返回");
            return pta;
        }
    }

    @Override
    public Pta selectByPtyextkeyAndUsg(String ptyextkey, String usg) {
        String key = generatekey(ptyextkey + "_" + usg);
        Pta pta = (Pta) redisTemplate.opsForValue().get(key);
        if (pta == null) {
            log.debug("Redis中不存在key：" + key + "或者已经过期，查数据库");
            pta = ptaMapper.selectByPtyextkeyAndUsg(ptyextkey, usg);
            redisTemplate.opsForValue().set(key, pta, EXPIRETIMES, EXPIRETYPE);
            return pta;
        } else {
            log.debug("Redis中存在key：" + key + "直接返回");
            return pta;
        }
    }

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