package com.rf.psychological.utils;

import ch.qos.logback.core.pattern.SpacePadder;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.rf.psychological.user.dao.model.UserEntity;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lpf
 * @description:
 * @date 2021/12/2820:18
 */
public class JWTUtil {

    //密钥签名
    private static final String SING = "xVWGEYTPF1hjnFt$HDZ0f^iet^^q@hZv";

    /**
     * 生成Token header.payload.sing
     */
    public static String getToken(Map<String, String> map) {

        Calendar instance = Calendar.getInstance();
        //5天后过期
        instance.add(Calendar.DATE, 5);
        //创建jwtBuilder
        JWTCreator.Builder builder = JWT.create();
        //将参数放进去
        map.forEach(builder::withClaim);
        String token = builder.withIssuedAt(new Date())//设置签发时间
                .withExpiresAt(instance.getTime())//指定过期时间
                .sign(Algorithm.HMAC256(SING));//添加签名
        return token;
    }

    public static String getTokenByUserInfo(UserEntity userEntity){
        HashMap<String, String> payload = new HashMap<>();
        payload.put("userPhone", userEntity.getPhone());
        payload.put("userId", userEntity.getId());
        payload.put("petName", userEntity.getPetName());
        payload.put("groupId", userEntity.getGId());
        payload.put("institutionNo", userEntity.getInstitutionNo());
        payload.put("type", userEntity.getRoleType());
        return  getToken(payload);
    }

    /**
     * 生成token 外部系统使用，仅两小时有效
     * @param userEntity
     * @return
     */
    public static String generateToken(UserEntity userEntity){
        HashMap<String, String> payload = new HashMap<>();
        payload.put("userPhone", userEntity.getPhone());
        payload.put("userId", userEntity.getId());
        payload.put("petName", userEntity.getPetName());
        payload.put("groupId", userEntity.getGId());
        payload.put("institutionNo", userEntity.getInstitutionNo());
        payload.put("type", userEntity.getRoleType());

        Calendar instance = Calendar.getInstance();
        //2小时后过期
        instance.add(Calendar.HOUR, 2);
        //创建jwtBuilder
        JWTCreator.Builder builder = JWT.create();
        //将参数放进去
        payload.forEach(builder::withClaim);
        String token = builder.withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(SING));
        return token;
    }

    /**
     * 验证token,并获取信息
     *
     * @return
     */
    public static DecodedJWT verify(String token) {
        return JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
    }



}
