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

import com.brilliance.isc.bo.Ptm;
import com.brilliance.isc.common.util.Utils;
import com.brilliance.isc.mda.dao.PtmMapper;
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.List;
import java.util.concurrent.TimeUnit;

@Service
public class PtmCacheServiceImpl implements PtmCacheService {

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

    private static final String TYPE = "PTM";

    private static final long EXPIRETIMES = 60l;

    private static final TimeUnit EXPIRETYPE = TimeUnit.SECONDS;

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

    @Autowired
    private PtmMapper ptmMapper;

    @Override
    public List<Ptm> getPtmListByPtainr(String ptainr) {
        String conditionSql = Utils.sdbEtyGenSql("PTM", "WHERE PTAINR = '" + ptainr + "'");
        String key = generatekey(conditionSql);
        List<Ptm> ptmList = (List<Ptm>) redisTemplate.opsForValue().get(key);
        if (ptmList == null) {
            log.debug("Redis中不存在key："+key+"或者已经过期，查数据库");
            ptmList = ptmMapper.getPtmByConditionSql(conditionSql);
            redisTemplate.opsForValue().set(key, ptmList, EXPIRETIMES, EXPIRETYPE);
            return ptmList;
        } else {
            log.debug("Redis中存在key："+key+"直接返回");
            return ptmList;
        }
    }

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