package com.koobietech.eas.service.impl;

import com.koobietech.eas.common.exception.EasException;
import com.koobietech.eas.common.pojo.JwtUserPojo;
import com.koobietech.eas.common.service.RedisService;
import com.koobietech.eas.dao.pojo.UserDetailPojo;
import com.koobietech.eas.service.EasSysUserLoginRedisService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author lc
 */
@Service
public class EasSysUserLoginRedisServiceImpl implements EasSysUserLoginRedisService {

    @Resource
    private RedisService redisService;


    @Override
    public UserDetailPojo checkToken(JwtUserPojo jwtUserPojo) {
        String jwtKey = createJwtTokenKey(jwtUserPojo);
        //判断redis里面是否有这个key
        if (!redisService.hasKey(jwtKey)) {
            throw new EasException("token已过期");
        }
        return (UserDetailPojo) redisService.get(jwtKey);
    }

    @Override
    public void loginSaveCache(String redisTokenKey, UserDetailPojo userDetailPojoInRedis, Integer token_expires) {
        redisService.set(redisTokenKey, userDetailPojoInRedis, token_expires);
    }


    @Override
    public UserDetailPojo loginGetCache(String newRedisTokenKey) {
        //看看redis里面有没有这个key
        if (redisService.hasKey(newRedisTokenKey)) {
            //有的话，就从redis里面取出来
            return (UserDetailPojo) redisService.get(newRedisTokenKey);
        }
        return null;
    }

    @Override
    public String createJwtTokenKey(JwtUserPojo jwtUserPojo) {
        //根据jwtUserDto 生成jwtKey，格式为：eas_token_{id}_{username}_{type}
        return "eas_token_" + jwtUserPojo.getId() + "_" + jwtUserPojo.getUsername() + "_" + jwtUserPojo.getType();
    }

    @Override
    public String createJwtRefreshTokenKey(JwtUserPojo jwtUserPojo) {
        //根据jwtUserDto 生成jwtKey，格式为：eas_refresh_{id}_{username}_{type}
        return "eas_refresh_" + jwtUserPojo.getId() + "_" + jwtUserPojo.getUsername() + "_" + jwtUserPojo.getType();
    }

    @Override
    public Boolean loginDeleteCache(String newRedisRefreshTokenKey) {
        return redisService.del(newRedisRefreshTokenKey);
    }
}
