package com.hs.api.common.utils;

import com.hs.api.model.SysUser;
import com.hs.api.model.TokenResult;
import com.hs.api.model.TokenProperties;
import com.hs.common.utils.JWTUtil;
import com.hs.common.utils.RedisUtil;

public class TokenUtil {
    public final static long TOKEN_TIME_OUT = 2L * 60 * 60;
    public final static long OLD_TOKEN_DURATION = 5L * 60;
//    public final static String CHECK_TOKEN_URL = "http://192.192.192.97:8001/api/tokenapi/GetUser?token=";

    /**
     * 获取token，并将token存入redis
     *
     * @param secret 密码
     * @param user 用户信息
     * @return token
     */
    public static String getToken(String secret,SysUser user) {
        String time = String.valueOf(System.currentTimeMillis());
        String token = JWTUtil.create(secret,time,String.valueOf(user.getId()));
        RedisUtil.set(token,user,TOKEN_TIME_OUT);
        return token;
    }

    /**
     * 将token存入redis
     *
     * @param token
     * @param tr 返回结果
     */
    public static void setToken(String token,TokenResult tr) {
        SysUser user = new SysUser();
        user.setId(1111L);
        user.setState(Short.parseShort("1"));

        RedisUtil.set(token,user,TOKEN_TIME_OUT);
    }

    /**
     * 刷新token，并将旧token设置过期时间为5分钟
     *
     * @param oldToken 旧的token
     * @return 新的token
     */
    public static String refresh(String oldToken) {
        String token = null;
        SysUser user = (SysUser)RedisUtil.get(oldToken);
        if(checkToken(oldToken)){
            RedisUtil.expire(oldToken,OLD_TOKEN_DURATION);
            token = getToken(user.getPassword(),user);
        }
        return token;
    }

    /**
     * 校验token
     *
     * @param token token
     * @return 返回校验结果
     */
    public static boolean checkToken(String token) {
        SysUser user = (SysUser)RedisUtil.get(token);
        boolean result = user != null && JWTUtil.verifier(token,user.getPassword());
        if(result){
            RedisUtil.expire(token,TOKEN_TIME_OUT);
        }
        return result;
    }

    /**
     * 校验token
     *
     * @param token token
     * @param tp 配置对象
     * @return 返回校验结果
     */
    public static boolean checkToken(String token,TokenProperties tp) {
        TokenUtil tu = new TokenUtil();
        SysUser user = (SysUser)RedisUtil.get(token);
        String url = tp.getUrl() + token;
        boolean result = false;
        result = user != null || HttpClientUtil.tokenCheck(url);
        if(result){
            RedisUtil.expire(token,TOKEN_TIME_OUT);
        }
        return result;
    }
}
