package com.jeequan.jeepay.agent.mq;

import com.jeequan.jeepay.components.mq.model.CleanAgentLoginAuthCacheMQ;
import com.jeequan.jeepay.core.cache.RedisUtil;
import com.jeequan.jeepay.core.constants.CS;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.List;

/**
* 接收MQ消息
* 业务： 清除服务商的登录信息
* @author terrfly
* @date 2021/7/27 9:23
*/
@Slf4j
@Component
public class CleanAgentLoginAuthCacheMQReceiver implements CleanAgentLoginAuthCacheMQ.IMQReceiver {

    @Override
    public void receive(CleanAgentLoginAuthCacheMQ.MsgPayload payload) {

        log.info("成功接收删除商户用户登录的订阅通知, msg={}", payload);

        if (CleanAgentLoginAuthCacheMQ.CLEAN_CACHE_TYPE_LOGIN_TOKEN.equals(payload.getCleanCacheType())) {

            // 字符串转List<String>
            List<String> userIdList = payload.getList();
            // 删除redis用户缓存
            if(userIdList == null || userIdList.isEmpty()){
                log.info("用户ID为空");
                return ;
            }
            for (String sysUserId : userIdList) {
                Collection<String> cacheKeyList = RedisUtil.keys(CS.getCacheKeyToken(Long.valueOf(sysUserId), "*"));
                if(cacheKeyList == null || cacheKeyList.isEmpty()){
                    continue;
                }
                for (String cacheKey : cacheKeyList) {
                    // 删除用户Redis信息
                    RedisUtil.del(cacheKey);
                    continue;
                }
            }
            log.info("无权限登录用户信息已清除");
        }

        // 清除登录失败次数限制缓存
        else if (CleanAgentLoginAuthCacheMQ.CLEAN_CACHE_TYPE_LOGIN_ERR.equals(payload.getCleanCacheType())) {

            // 字符串转List<String>
            List<String> list = payload.getList();

            // 删除redis用户缓存
            if(CollectionUtils.isEmpty(list)){
                log.info("登录用户名list为空");
                return ;
            }
            for (String loginUserName : list) {
                RedisUtil.del(CS.getCacheKeyLoginErr(CS.SYS_ROLE_TYPE.AGENT, loginUserName));
            }

            log.info("登录限制已清除");
        }
    }
}
