package com.ytpm.calculator.monitor;

import com.ytpm.agent.enums.UserStatusEnum;
import com.ytpm.app.model.YtDyzUser;
import com.ytpm.calculator.dao.AppUserMapper;
import com.ytpm.risk.enums.BannedTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * redis 监听器
 */
@Slf4j(topic = "RedisKeyExpire")
@Component
@RefreshScope
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    @Resource
    private AppUserMapper appUserMapper;

    /**
     * Creates new {@link } for {@code __keyevent@*__:expired} messages.
     *
     * @param listenerContainer must not be {@literal null}.
     */
    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }
 
    /**
     * 监听redis过期的 key 进行处理
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        String key = String.valueOf(message);
        log.error("App-Service 发现预定风控用户：{}",key);
        if(key.startsWith("lock_")){
            String[] arr = key.split("_");
            lockUser(arr[1], UserStatusEnum.RISK.getCode());
        }
        /**
         * 用户解锁
         */
        if(key.startsWith("unlock_")){
            String[] arr = key.split("_");
            YtDyzUser dyzUser = new YtDyzUser();
            dyzUser.setUserId(arr[1]);
            dyzUser.setUserStatus(1);
            appUserMapper.updateUser(dyzUser);
        }
    }

    /**
     * 锁定用户
     */
     private void lockUser(@RequestParam("userId")String userId, @RequestParam("userStatus")Integer userStatus){
        YtDyzUser dyzUser = appUserMapper.selectPrimaryKey(userId);
        YtDyzUser newUser = new YtDyzUser();
        newUser.setUserId(userId);
        newUser.setUserStatus(userStatus);
        newUser.setRiskReason(BannedTypeEnum.CHANNEL.getDesc()+"禁止登录");
        if(Objects.nonNull(dyzUser)){
            appUserMapper.updateUser(newUser);
        }
    }
}