package com.mvc.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.mvc.model.external.AuthModel;
import com.mvc.service.external.RefreshTokenService;

import java.util.*;

public class JwtUtil {
    public static List<AuthModel> tokenList = new ArrayList<>();

    /**
     * 过期
     */
    private static final long EXPIRE_TIME = 30 * 60 * 1000;//30分钟有效期
    //private static final long EXPIRE_TIME = 1 * 60 * 1000;//测试1分钟

    /**
     * jwt密钥
     */
    private static final String SECRET = "dxchjb_xzeai";

    /**
     * 生成jwt字符串
     *
     * @param userId
     * @param info,Map的value只能存放值的类型为：Map，List，Boolean，Integer，Long，Double，String and Date
     * @return
     */
    public static String sign(String userId, Map<String, Object> info) {
        try {
            Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            return JWT.create()
                    //将userId保存到token里面
                    .withAudience(userId)
                    //存放自定义数据
                    .withClaim("info", info)
                    //token过期时间
                    .withExpiresAt(date)
                    //token的密钥
                    .sign(algorithm);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 生成授权对象
     *
     * @param userId
     * @param info
     * @return
     */
    public static AuthModel signAuthModel(String userId, Map<String, Object> info) {
        AuthModel authModel = new AuthModel();
        try {
            Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            String token = JWT.create()
                    //将userId保存到token里面
                    .withAudience(userId)
                    //存放自定义数据
                    .withClaim("info", info)
                    //五分钟后token过期
                    .withExpiresAt(date)
                    //token的密钥
                    .sign(algorithm);
            authModel.setAccessToken(token);
            authModel.setRefreshToken(RefreshTokenService.sign(userId, info));
            authModel.setExpiresTime(DateUtil.formateDate(date, DateUtil.PATTERN_DATA_NORMAL));
            authModel.setExpiredFlag(0);
            addToken(authModel);
            return authModel;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据token获取userId
     *
     * @param token
     * @return
     */
    public static String getUserId(String token) {
        try {
            String userId = JWT.decode(token).getAudience().get(0);
            return userId;
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 根据token获取自定义数据info
     *
     * @param token
     * @return
     */
    public static Map<String, Object> getInfo(String token) {
        if (token == null) {
            return null;
        }
        try {
            return JWT.decode(token).getClaim("info").asMap();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 校验token
     *
     * @param token
     * @return
     */
    public static boolean checkSign(String token) {
        try {
            //判断是否已经被登记过期了
            Optional<AuthModel> optional = tokenList.stream().filter(s->s.getAccessToken().equals(token)).findFirst();
            if(optional.isPresent()){
                if(optional.get().getExpiredFlag()==1){
                    return false;
                }
            }

            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            JWTVerifier verifier = JWT.require(algorithm)
                    //.withClaim("username, username)
                    .build();
            verifier.verify(token);
            return true;
        } catch (JWTVerificationException e) {
            return false;
            //throw new RuntimeException("token 无效，请重新获取");
        }
    }

    /**
     * 登记当前发出的token
     * @param authModel
     */
    private static void addToken(AuthModel authModel) {
        if (tokenList.size() > 200) {
            tokenList.remove(0);
        }
        tokenList.add(authModel);
    }

    /**
     * 设置Token过期
     *
     * @param token
     */
    public static void setTokenExpired(String token) {
        for (AuthModel model : tokenList) {
            if (model.getAccessToken().equals(token) || model.getRefreshToken().equals(token)) {
                model.setExpiredFlag(1);
            }
        }
    }
}
