package com.eitc.common.utils;

import com.alibaba.fastjson2.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.Verification;
import com.eitc.common.constant.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.Map;

/**
 * @author mtx
 */
@Slf4j
public class JWTUtil {

    /**
     * 生成token header payload sign
     */
    public static String getToken(Map<String, String> map, String secreKey) {
        Calendar instance = Calendar.getInstance();
        // 七天后过期
        instance.add(Calendar.MINUTE, 60*24*30);
        //创建jwtbuilder
        JWTCreator.Builder builder = JWT.create();
        map.forEach(builder::withClaim);
        //设置过期时间
        return builder.withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(secreKey));
    }

    /**
     * 验证token 合法性
     *
     * @param token
     */
    public static DecodedJWT verify(String token, String secretKey) {
        Algorithm hmac256 = Algorithm.HMAC256(secretKey);
        Verification require = JWT.require(hmac256);
        JWTVerifier build = require.build();
        DecodedJWT verify = build.verify(token);
        log.info("【验证Token】verify：{}", JSON.toJSONString(verify));
        return verify;
    }

    public static String getRequestToken() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert attributes != null;
        HttpServletRequest request = attributes.getRequest();
        return request.getHeader(Constants.TOKEN);
    }

    /**
     * APP用户表ID
     *
     * @return id
     */
    public static String getAppUserId() {
        String requestToken = getRequestToken();
        DecodedJWT jwt = JWT.decode(requestToken);
        return jwt.getClaim("id").asString();
    }

    /**
     * 手机号
     *
     * @return 手机号
     */
    public static String getAppPhoneNumber() {
        String requestToken = getRequestToken();
        DecodedJWT jwt = JWT.decode(requestToken);
        return jwt.getClaim("phoneNumber").asString();
    }

}
