package com.koobietech.eas.service.impl;

import com.koobietech.eas.common.exception.EasException;
import com.koobietech.eas.common.pojo.JwtUserDto;
import com.koobietech.eas.common.service.RedisService;
import com.koobietech.eas.dao.adminLoginPojo.UserDetail;
import com.koobietech.eas.service.LoginRedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class LoginRedisServiceImpl implements LoginRedisService {

    @Resource
    private RedisService redisService;


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

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


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

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

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

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