package com.cmeeting.ad.util;

import cn.hutool.core.util.StrUtil;
import com.cmeeting.ad.entity.RobotSecurityUser;
import com.cmeeting.exception.RobotBaseException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

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

/**
 * @Classname JwtUtil
 * @Description JWT工具类
 * @Author robot
 * @Date 2019-05-07 09:23
 * @Version 1.0
 */
@Component
public class JwtUtil {

    /**
     * 用户名称
     */
    private static final String USERNAME = Claims.SUBJECT;

    /**
     * 密钥
     */
    private static final String SECRET = "badou1001";

    @Value("${jwt.header}")
    private String tokenHeader;

    @Value("${jwt.tokenHead}")
    private String authTokenStart;

    /**
     * 生成令牌
     *
     * @return 令牌
     */
    public String generateToken(RobotSecurityUser robotSecurityUser) {
        Map<String, Object> claims = new HashMap<>(1);
        claims.put(USERNAME, robotSecurityUser.getUsername());
        claims.put("time", System.currentTimeMillis());
        return generateToken(claims);
    }

    public String generateToken(String username, String applicationId) {
        Map<String, Object> claims = new HashMap<>(1);
        claims.put(USERNAME, username);
        claims.put("applicationId", applicationId);
        claims.put("time", System.currentTimeMillis());
        return generateToken(claims);
    }


    /**
     * 从数据声明生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private String generateToken(Map<String, Object> claims) {
        return Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS512, SECRET).compact();
    }

    /**
     * 获取请求token
     *
     * @param request
     * @return
     */
    public String getToken(HttpServletRequest request) {
        String token = request.getHeader(tokenHeader);
        if (StrUtil.isNotBlank(token) && token.length() > authTokenStart.length()) {
            token = token.substring(authTokenStart.length()).trim();
        }
        return token;
    }

}
