package com.app.util;

import cn.hutool.core.util.IdUtil;
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 lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.time.Instant;
import java.time.ZonedDateTime;
import java.util.Date;

@Slf4j
public class JwtUtil {

    private static ThreadLocal<JwtUser> localUser = new ThreadLocal();

    public static void setLocalUser(ThreadLocal<JwtUser> localUser) {
        JwtUtil.localUser = localUser;
    }

    public static ThreadLocal<JwtUser> getLocalUser() {
        return localUser;
    }

    /**
     * 加密算法
     */
    private static final Algorithm algorithm = Algorithm.HMAC512("auth_chm");

    public static final String ID = "ID";
    public static final long TOKEN_EXPIRE_TIME = 2 * 60 * 60; // token过期时间(秒)

    public static final class PlatformJWTConstant {
        public static final String ISSUER = "430-PLATFORM";
        public static final String SUBJECT = "PLATFORM";
        public static final String AUDIENCE = "PLATFORM";
    }

    public static final class WeixinMiniProgramJWTConstant {
        public static final String ISSUER = "430-PLATFORM";
        public static final String SUBJECT = "WEIXIN_MINI_PROGRAM";
        public static final String AUDIENCE = "WEIXIN_MINI_PROGRAM";
    }

    @Data
    public static final class JwtUser {
        private String id;
    }

    /**
     * 功能描述：平台生成Token
     *
     * @param accountId
     * @return
     */
    public static String createTokenByPlatform(String accountId) {
        Date now = Date.from(Instant.now());
        String token = JWT.create()
                .withIssuer(PlatformJWTConstant.ISSUER) // 用于说明该JWT是由谁签发的
                .withSubject(PlatformJWTConstant.SUBJECT) // 用于说明该JWT面向的对象
                .withAudience(PlatformJWTConstant.AUDIENCE) // 用于说明该JWT发送给的用户
                .withExpiresAt(Date.from(ZonedDateTime.now().plusMinutes(TOKEN_EXPIRE_TIME).toInstant())) // 数字类型，说明该JWT过期的时间
                .withNotBefore(now) // 生效时间
                .withIssuedAt(now) // 签发时间
                .withJWTId(IdUtil.simpleUUID()) // 说明标明JWT的唯一ID
                .withClaim(ID, accountId)
                .sign(algorithm);
        return token;
    }

    /**
     * 功能描述：解析验证token
     *
     * @param token
     * @return
     */
    public static Boolean validateTokenByPlatform(String token) {
        if (StringUtils.isEmpty(token)) {
            return Boolean.FALSE;
        }

        try {
            JWTVerifier verifier = JWT.require(algorithm)
                    .withIssuer(PlatformJWTConstant.ISSUER)
                    .withJWTId(getJwtIdByToken(token))
                    .acceptExpiresAt(System.currentTimeMillis() + TOKEN_EXPIRE_TIME * 1000) //JWT 正确的配置续期姿势
                    .build();

            DecodedJWT jwt = verifier.verify(token);

            JwtUser _jwtUser = new JwtUser();
            _jwtUser.setId(jwt.getClaim(ID).asString());
            localUser.set(_jwtUser);
            return Boolean.TRUE;
        } catch (Exception e) {
            log.error("validateTokenByPlatform {}", e.getMessage());
            return Boolean.FALSE;
        }
    }

    /**
     * 功能描述：微信小程序生成token
     * 注 : 这里的token会被缓存到redis中,用作为二次验证
     * redis里面缓存的时间应该和jwt token的过期时间设置相同
     *
     * @param guardianId 家长标识
     * @return 返回 jwt token
     */
    public static String createTokenByGuardian(String guardianId) {
        Date now = Date.from(Instant.now());
        String token = JWT.create()
                .withIssuer(WeixinMiniProgramJWTConstant.ISSUER) // 用于说明该JWT是由谁签发的
                .withSubject(WeixinMiniProgramJWTConstant.SUBJECT) // 用于说明该JWT面向的对象
                .withAudience(WeixinMiniProgramJWTConstant.AUDIENCE) // 用于说明该JWT发送给的用户
                .withExpiresAt(Date.from(ZonedDateTime.now().plusMinutes(TOKEN_EXPIRE_TIME).toInstant())) // 数字类型，说明该JWT过期的时间
                .withNotBefore(now) // 生效时间
                .withIssuedAt(now) // 签发时间
                .withJWTId(IdUtil.simpleUUID()) // 说明标明JWT的唯一ID
                .withClaim(ID, guardianId)
                .sign(algorithm);
        return token;
    }

    /**
     * 功能描述：解析验证token
     *
     * @param token
     * @return
     */
    public static Boolean validateTokenByWeixinMiniProgram(String token) {
        if (StringUtils.isEmpty(token)) {
            return Boolean.FALSE;
        }

        try {
            JWTVerifier verifier = JWT.require(algorithm)
                    .withIssuer(WeixinMiniProgramJWTConstant.ISSUER)
                    .withJWTId(getJwtIdByToken(token))
                    .acceptExpiresAt(System.currentTimeMillis() + TOKEN_EXPIRE_TIME * 1000) //JWT 正确的配置续期姿势
                    .build();

            verifier.verify(token);

            return Boolean.TRUE;
        } catch (Exception e) {
            log.error("validateTokenByWeixinMiniProgram {}", e.getMessage());
            return Boolean.FALSE;
        }
    }

    public static Boolean isExpired(String token) {
        return Boolean.FALSE;
    }

    /**
     * 功能描述：根据Token 获取业务标识
     *
     * @param token
     * @return
     * @throws JWTDecodeException
     */
    public static String getIDByToken(String token) throws JWTDecodeException {
        return JWT.decode(token).getClaim(ID).asString();
    }

    /**
     * 功能描述：根据Token 获取jwt-id
     *
     * @param token
     * @return
     * @throws JWTDecodeException
     */
    public static String getJwtIdByToken(String token) throws JWTDecodeException {
        return JWT.decode(token).getId();
    }

}
