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

import com.brilliance.isc.bo.Atpbch;
import com.brilliance.isc.bo.Bch;
import com.brilliance.isc.common.cache.pty.PtyCacheServiceImpl;
import com.brilliance.isc.common.context.SettleContext;
import com.brilliance.isc.common.context.SettleSession;
import com.brilliance.isc.mda.dao.AtpbchMapper;
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.Component;

import java.util.concurrent.TimeUnit;

@Component
public class AtpbchCacheServiceImpl implements AtpBchCacheService {

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

    private static final String TYPE = "ATPBCH";

    private static final long EXPIRETIMES = 240l;

    private static final TimeUnit EXPIRETYPE = TimeUnit.SECONDS;


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

    @Autowired
    private AtpbchMapper atpbchMapper;

    @Override
    public Atpbch getAtpBchByBchAndFrm(String branch,String frm) {
        String key = generatekey(branch,frm);
        Atpbch atpbch = (Atpbch) redisTemplate.opsForValue().get(key);
        if (atpbch == null) {
            log.debug("Redis中不存在key：" + key + "或者已经过期，查数据库");
            atpbch = atpbchMapper.selectByBranchAndInifrm(branch,frm);
            redisTemplate.opsForValue().set(key, atpbch, EXPIRETIMES, EXPIRETYPE);
            return atpbch;
        } else {
            log.debug("Redis中存在key：" + key + "直接返回");
            return atpbch;
        }
    }

    /**
     * 为注册类获取交易，二期时，重用非收单交易的注册类
     * @return
     */
    @Override
    public String getSdTransNameForRegister() {

        if(!SettleContext.getUserSession().isSdhTransaction()){
            return SettleContext.getTransName();
        }
        String transName = SettleContext.getTransName().toUpperCase();
        String busType = transName.substring(0,2);
        //一期保函保持现状
        if("-GI-NI-HI-GC-NC-NE-GE".indexOf(busType) > 0){
            return transName;
        }
        //二期因为收单交易复用非收单交易，获取注册类时的交易码
        SettleSession settleSession = SettleContext.getUserSession();
        Bch bch =settleSession.getBch();
        String inifrm = settleSession.getTransName();
        String branch="";
        if(bch!=null){
            branch=bch.getBranch();
         }
        Atpbch atpbch = getAtpBchByBchAndFrm(branch,inifrm);
        return atpbch.getFrmtyp();
    }

    public String generatekey(String branch,String frm) {
        return TYPE + "_" + branch+"_"+frm;
    }
}
