package com.chushang.security.service;

import com.chushang.common.core.constant.CacheConstants;
import com.chushang.common.core.constant.SecurityConstants;
import com.chushang.common.core.util.*;
import com.chushang.security.utils.SecurityUtils;
import com.chushang.security.entity.vo.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBucket;
import org.redisson.api.RKeys;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * token验证处理
 *
 * @author ruoyi
 */
@Component
@Slf4j
public class TokenService
{
    @Autowired
    private RedissonClient redissonClient;

    // 1秒
    protected static final long MILLIS_SECOND = 1000;
    // 1分钟
    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;
    // 1个小时
    protected static final long MILLIS_HOUR = 60 * MILLIS_MINUTE;

    /**
     * 创建令牌
     */
    public Map<String, Object> createToken(LoginUser loginUser)
    {
        String token = IdUtils.getId(31);
        Long userId = loginUser.getUserId();
        String username = loginUser.getUsername();
        String tokenKey = token + "#" + userId;
        loginUser.setToken(tokenKey);
        loginUser.setIpaddr(IPUtils.clientIp(ServletUtils.getRequest()));

        refreshToken(loginUser);

        // Jwt存储信息
        Map<String, Object> claimsMap = new HashMap<>();
        claimsMap.put(SecurityConstants.USER_KEY, tokenKey);
        claimsMap.put(SecurityConstants.DETAILS_USER_ID, userId);
        claimsMap.put(SecurityConstants.DETAILS_USERNAME, username);

        // 接口返回信息
        Map<String, Object> rspMap = new HashMap<>();
        rspMap.put("access_token", JwtUtils.createToken(claimsMap));
        // 默认15天
        rspMap.put("expires_in", 15 * 24 * MILLIS_HOUR );
        return rspMap;
    }

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser()
    {
        return getLoginUser(ServletUtils.getRequest());
    }

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser(HttpServletRequest request)
    {
        // 获取请求携带的令牌
        String token = SecurityUtils.getToken(request);
        return getLoginUser(token);
    }

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser(String token)
    {
        try
        {
            if (StringUtils.isNotEmpty(token))
            {
                String userKey = JwtUtils.getUserKey(token);

                String tokenKey = getTokenKey(userKey);

                RBucket<LoginUser> bucket = redissonClient.getBucket(tokenKey);

                return bucket.get();
            }
        }
        catch (Exception ignored)
        {
        }
        return null;
    }

    /**
     * 设置用户身份信息
     */
    public void setLoginUser(LoginUser loginUser)
    {
        if (StringUtils.isNotNull(loginUser) && StringUtils.isNotEmpty(loginUser.getToken()))
        {
            refreshToken(loginUser);
        }
    }

    /**
     * 删除用户缓存信息
     */
    public void delLoginUser(String token)
    {
        if (StringUtils.isNotEmpty(token))
        {
            String userKey = JwtUtils.getUserKey(token);
            redissonClient.getBucket(getTokenKey(userKey)).delete();
        }
    }

    /**
     * 验证令牌有效期，相差不足 过期时间, 自动刷新缓存
     */
    public void verifyToken(LoginUser loginUser)
    {
        // 过期时间
        long expireTime = loginUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= 15 * 24 * MILLIS_HOUR)
        {
            refreshToken(loginUser);
        }
    }

    /**
     * 刷新令牌有效期
     *
     * @param loginUser 登录信息
     */
    public void refreshToken(LoginUser loginUser)
    {
        long expireTime = 15 * 24 * MILLIS_HOUR ;
        if (log.isDebugEnabled())
            log.debug("TokenService refreshToken");
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + expireTime);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(loginUser.getToken());

        RKeys rKeys = redissonClient.getKeys();
        // 扫描全部的 登录token, 如果登录token 不等于需要刷新的token, 则将此token 进行删除
        Iterable<String> keysByPattern = rKeys.getKeysByPattern(CacheConstants.LOGIN_TOKEN_KEY + "*" + "#" + loginUser.getUserId());

        for (String key : keysByPattern) {
            if (!key.equals(userKey)) {
                rKeys.delete(key);
            }
        }

        redissonClient.getBucket(userKey)
                        .set(loginUser, expireTime / 1000, TimeUnit.SECONDS);
    }

    private String getTokenKey(String token)
    {
        return CacheConstants.LOGIN_TOKEN_KEY + token;
    }

    /**
     * 根据 用户ID 进行用户强退
     */
    public void forcedRetreat(Long userId){
        RKeys rKeys = redissonClient.getKeys();
        long l = rKeys.deleteByPattern(CacheConstants.LOGIN_TOKEN_KEY + "*" + "#" + userId);
        if (log.isDebugEnabled()){
            log.debug("强退 {} 个用户, userId : {}.",l, userId );
        }
    }

    public void forcedRetreatByTokenKey(String tokenKey){
        RKeys rKeys = redissonClient.getKeys();
        long l = rKeys.deleteByPattern(CacheConstants.LOGIN_TOKEN_KEY + tokenKey);
        if (log.isDebugEnabled()){
            log.debug("强退 {} 个用户, userId : {}.",l, tokenKey.split("#")[1] );
        }
    }
}
