package cn.wisenergy.chnmuseum.party.auth.util;

import cn.wisenergy.chnmuseum.party.common.util.DateUtil80;
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.interfaces.DecodedJWT;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;

@Component
public class JwtTokenUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(JwtTokenUtil.class);

    private static String jwtTokenSecret;
    private static String jwtTokenIssuer;
    private static String jwtTokenExpiration;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Value("${jwt.secret}")
    public void setJwtTokenSecret(String jwtTokenSecret) {
        JwtTokenUtil.jwtTokenSecret = jwtTokenSecret;
    }

    @Value("${jwt.issuer}")
    public void setJwtTokenIssuer(String jwtTokenIssuer) {
        JwtTokenUtil.jwtTokenIssuer = jwtTokenIssuer;
    }

    @Value("${jwt.expiration}")
    public void setJwtTokenExpiration(String jwtTokenExpiration) {
        JwtTokenUtil.jwtTokenExpiration = jwtTokenExpiration;
    }

    /**
     * 校验token是否正确
     *
     * @param token 密钥
     * @return 是否正确
     */
    public static String verify(String token, String username) {
        try {
            Algorithm algorithm = Algorithm.HMAC512(jwtTokenSecret);
            JWTVerifier verifier = JWT.require(algorithm).withIssuer(jwtTokenIssuer).withSubject(username).build();
            DecodedJWT jwt = verifier.verify(token);
            return jwt.getClaim("user_id").asString();
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            return null;
        }
    }

    /**
     * 获得token中的信息无需secret解密也能获得
     *
     * @return token中包含的用户名
     */
    public static String getUsername(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getSubject();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 获得token中的信息无需secret解密也能获得
     *
     * @return token中包含的用户名
     */
    public static String getEmployeeId(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("user_id").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 生成签名,60min后过期
     *
     * @param username 用户名
     * @return 加密的token
     */
    public static String sign(String username, String employeeId) throws UnsupportedEncodingException {
        LocalDateTime currentTime = DateUtil80.getDateTimeOfTimestamp(System.currentTimeMillis());
        Algorithm algorithm = Algorithm.HMAC512(jwtTokenSecret);
        // 附带username信息
        return JWT.create().withIssuer(jwtTokenIssuer)
                // 创建时间
                .withIssuedAt(DateUtil80.getCurrDateTime()).withSubject(username).withClaim("user_id", employeeId)
                .withExpiresAt(DateUtil80.asDate(currentTime.plusMinutes(240))).sign(algorithm);
    }

    /**
     * 生成签名,30day后过期
     *
     * @param username 用户名
     * @return 加密的token
     */
    public static String signByRememberMe(String username, Integer userId) throws UnsupportedEncodingException {
        LocalDateTime currentTime = DateUtil80.getDateTimeOfTimestamp(System.currentTimeMillis());
        Algorithm algorithm = Algorithm.HMAC512(jwtTokenSecret);
        // 附带username信息
        return JWT.create().withIssuer(jwtTokenIssuer)
                // 创建时间
                .withIssuedAt(DateUtil80.getCurrDateTime()).withSubject(username).withClaim("userId", userId)
                .withExpiresAt(DateUtil80.asDate(currentTime.plusSeconds(Integer.parseInt(jwtTokenExpiration))))
                .sign(algorithm);
    }

}