package com.koobietech.eas.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import com.koobietech.eas.dao.constant.UserType;
import com.koobietech.eas.common.exception.EasException;
import com.koobietech.eas.common.pojo.JwtUserPojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Calendar;

@Component
public class JwtManager {

    @Value("${eas.jwt-secret-key}")
    private String SECRET;

    @Value("${eas.jwt-expires-date}")
    private int expires;

    /**
     * 创建 token
     * @param userDto
     * @return
     */
    public String createJwt(JwtUserPojo userDto){
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, expires);
        String sign = JWT.create()
                .withClaim("user", userDto.getUsername())
                .withClaim("id", userDto.getId())
                .withClaim("type", userDto.getType().toString())
                .withExpiresAt( calendar.getTime() )
                .sign(Algorithm.HMAC256(SECRET));
        return sign;
    }

    /**
     * 创建 token
     * @param userDto
     * @return
     */
    public String createJwt(JwtUserPojo userDto, Integer expires){
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, expires);
        String sign = JWT.create()
                .withClaim("user", userDto.getUsername())
                .withClaim("id", userDto.getId())
                .withClaim("type", userDto.getType().toString())
                .withExpiresAt( calendar.getTime() )
                .sign(Algorithm.HMAC256(SECRET));
        return sign;
    }

    /**
     * 解密 Token
     * @param token
     * @return
     */
    public JwtUserPojo decodeJwt(String token){
        JwtUserPojo jwtUserPojo = new JwtUserPojo();
        JWTVerifier build = JWT.require(Algorithm.HMAC256(SECRET)).build();
        try {
            DecodedJWT verify = build.verify(token);
            jwtUserPojo.setId(verify.getClaim("id").asLong());
            jwtUserPojo.setUsername(verify.getClaim("user").asString());
            jwtUserPojo.setType(UserType.valueOf(verify.getClaim("type").asString()));
        } catch ( JWTVerificationException e){
            throw new EasException("token 不正确!");
        }
        return jwtUserPojo;
    }

}
