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

import cn.hutool.core.collection.CollUtil;
import com.brilliance.isc.bo.Ety;
import com.brilliance.isc.bo.Pty;
import com.brilliance.isc.common.context.SettleContext;
import com.brilliance.isc.mda.dao.EtyMapper;
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.List;
import java.util.Optional;
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;

    @Autowired
    private EtyMapper etyMapper;

    private List<Ety> etyList;
    @PostConstruct
    public void initOwnPty() {
        etyList = etyMapper.selectAll();
        if(CollUtil.isEmpty(etyList)){
            throw new RuntimeException("ETY,ETG实体信息表中应至少有一条实体信息配置！");
        }
    }

    public Pty getOwnPty() {
        String etgextkey = SettleContext.getUserEtg().getExtkey();
        Optional<Ety> op = etyList.stream().filter(e->etgextkey.equalsIgnoreCase(e.getEtg())).findFirst();
        if(op.isPresent()){
            Ety ety = op.get();
            return ptyMapper.queryOwnPty(ety.getOwnbic(),ety.getEtg());
        }
        throw new RuntimeException("请检查PTY表是否正确配置了ETG["+etgextkey+"]对应信息!");
    }

    @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;
    }
}
