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

import com.brilliance.isc.bo.Pty;
import com.brilliance.isc.mda.dao.PtyMapper;
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 javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;

@Service
public class PtyCacheServiceImpl implements PtyCacheService {

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

    private static final String TYPE = "PTY";

    private static final long EXPIRETIMES = 240l;

    private static final TimeUnit EXPIRETYPE = TimeUnit.SECONDS;

    private static Pty ownPty = null;

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

    @Autowired
    private PtyMapper ptyMapper;

    @PostConstruct
    public void initOwnPty() {
        ownPty = ptyMapper.queryDetailByExtkey("EVERCNBJXXX");
        //验证环境 bic第8位都改成了0
        if (ownPty == null) {
            ownPty = ptyMapper.queryDetailByExtkey("EVERCNB0XXX");
        }
    }

    public Pty getOwnPty() {
        return ownPty;
    }

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

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