package com.energy.manage.service.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;

import java.util.HashMap;
import java.util.Map;

public class JwtUtil {

    /**
     * 生成token
     *
     * @param userId
     * @return
     */
    public static String getLoginToken(Integer userId, String userName, String phone, String password,Integer userRoleId) {
        String sign = JWT.create()
                .withClaim("userId", userId)
                .withClaim("userName", userName)
                .withClaim("userPhone", phone)
                .withClaim("userPassword", password)
                .withClaim("userRoleId", userRoleId)
                .sign(Algorithm.HMAC256(password));
        return sign;
    }

    /**
     * 生成tokenV2
     *
     * @param loginUser
     * @return
     */
//    public static String getLoginTokenV2(LoginUser loginUser) {
//        String sign = JWT.create()
//                .withClaim("loginUser", JSONObject.toJSONString(loginUser))
//                .sign(Algorithm.HMAC256(loginUser.getUserPassword()));
//        return sign;
//    }

//    public static void main(String[] args) {
//        System.out.println(getLoginToken(1L,"jialx","13800138000", "123456"));
//    }

    /**
     * 获取token信息
     *
     * @param token
     * @return
     */
    public static Map<String, String> getJwtMap(String token) throws JWTDecodeException {
        Map<String, String> map = new HashMap<>();
        map.put("userId", String.valueOf(JWT.decode(token).getClaim("userId").asLong()));
        map.put("userName", JWT.decode(token).getClaim("userName").asString());
        map.put("userPhone", JWT.decode(token).getClaim("userPhone").asString());
        map.put("userPassword", JWT.decode(token).getClaim("userPassword").asString());
        map.put("userRoleId", String.valueOf(JWT.decode(token).getClaim("userRoleId").asInt()));
        return map;
    }

//    public static LoginUser getJwtMapV2(String token) throws JWTDecodeException {
//        String jsonLoginUser = String.valueOf(JWT.decode(token).getClaim("loginUser").asString());
//        return JSON.parseObject(jsonLoginUser, LoginUser.class);
//    }




}
