package com.mosty.common.token;

import cn.hutool.json.JSON;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import com.mosty.common.base.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;

import java.util.Date;

import static com.mosty.common.base.constant.SystemConfigConstants.TOKEN_ISSUER;
import static com.mosty.common.base.constant.SystemConfigConstants.TOKEN_KEY;

/**
 * token工具类
 *
 * @author kevin
 * @date 2022/3/21 11:03 PM
 * @since 1.0.0
 */
@Slf4j
public class JWTUtil {
    public JWTUtil() {
    }

    public static DecodedJWT verify(String token) {
        try {
            // 这里不判断token过期状态
//            Algorithm algorithm = Algorithm.HMAC256(TOKEN_KEY);
//            JWTVerifier verifier = JWT.require(algorithm).withIssuer(new String[]{TOKEN_ISSUER}).build();
//            DecodedJWT decodedJWT = verifier.verify(token);
//
//            Date expiresAt = decodedJWT.getExpiresAt();
//            if (expiresAt.before(new Date())) {
//                log.info("token已过期");
//            }
//
//            return expiresAt.after(new Date()) ? decodedJWT : null;
            if(StringUtils.isNotEmpty(token)){
                Algorithm algorithm = Algorithm.HMAC256(TOKEN_KEY);
                JWTVerifier verifier = JWT.require(algorithm).withIssuer(new String[]{TOKEN_ISSUER}).build();
                return verifier.verify(token);
            }
            return null;
        } catch (TokenExpiredException expiredException) {
            log.warn("token过期：{}", expiredException.getMessage());
            throw new BusinessException(HttpStatus.UNAUTHORIZED.value(), "token过期，请重新登陆", null);
        } catch (Exception var11) {
            var11.printStackTrace();
            log.error("解签失败: {}", var11.getMessage());
            return null;
        }
    }

    /**
     * token 泛解析用户信息
     *
     * @param token jwt token
     * @return 用户信息
     */
    public static UserInfo getUserInfo(String token) {
        DecodedJWT jwt = verify(token);
        if (jwt == null) {
            return null;
        }
        return new UserInfo(
                jwt.getClaim("userId").asLong(),
                jwt.getClaim("userName").asString(),
                jwt.getClaim("phone").asString(),
                jwt.getClaim("userLoginName").asString(),
                jwt.getClaim("inDustRialId").asString(),
                jwt.getClaim("idEntityCard").asString(),
                jwt.getClaim("isVirtualUser").asString(),
                jwt.getClaim("level").asString(),
                jwt.getClaim("deptId").asLong(),
                jwt.getClaim("deptName").asString(),
                jwt.getClaim("deptCode").asString(),
                jwt.getClaim("fxjDeptId").asLong(),
                jwt.getClaim("fxjDeptName").asString(),
                jwt.getClaim("fxjDeptCode").asString(),
                jwt.getClaim("dszDeptId").asLong(),
                jwt.getClaim("dszDeptName").asString(),
                jwt.getClaim("dszDeptCode").asString(),
                jwt.getClaim("deptLevel").asString(),
                jwt.getClaim("deptBizType").asString(),
                JSONObject.parseObject(jwt.getClaim("permissions").asString(), UserPermissionsInfo.class)
        );
    }

    public static void main(String[] args) {
        UserInfo res = getUserInfo("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhZG1pbiIsImlzcyI6Inprai1mcG0tc3RvcmVhZG1pbiIsImV4cCI6MTYyODMzMTE1NCwiaWF0IjoxNjI3ODk5MTU0LCJ1c2VySWQiOjUzfQ.hJ25t46zntTUknwjsB0UJzOIFcM5n7IG0DDA6RVP8jM");
        System.out.println(res);
    }

}
