package com.huimv.beeboxs.common.token;

import io.jsonwebtoken.*;
import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

public class TokenSign {

    /**
     * 过期时间60分钟
     */
    private static final long EXPIRE_TIME= 24 * 60 * 60 * 1000;

    /**
     * 私钥，使用它生成token，最好进行下加密
     */
    private static final String TOKEN_SECRET="Token";
    private static final String APP_SECRET = "ukc8BDbRigUDaY6pZFfWus2jZWLPHO";
    private static final int REFRESH_TIME = 300;


    /**
     * 产生token
     * @return
     */
    public static String sign(String userName, Integer id, String farmIds){

        String JwtToken = Jwts.builder()
                //头部信息
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                .setSubject("hm-user")
                .setIssuedAt(new Date())
                //过期时间
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE_TIME))
                //token主体部分,存储用户信息
                .claim("userName", userName)
                .claim("id",id)
                .claim("farmIds",farmIds)
                .signWith(SignatureAlgorithm.HS256, APP_SECRET)
                .compact();

        return JwtToken;
    }


    /**
     * token校验是否正确
     * @param token
     * @return
     */

    public static boolean verify(String token){

        if (StringUtils.isBlank(token)) {
            return false;
        }
        try {
            Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(token);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;

    }


    /**
     * 根据token获取会员id
     *
     * @param request
     * @return
     */
    public static Integer getMemberIdByJwtToken(HttpServletRequest request) {
        String jwtToken = request.getHeader("accessToken");
        if (StringUtils.isBlank(jwtToken)) {
            return null;
        }
        Claims claims = getClaims(jwtToken);
        return (Integer) claims.get("id");
    }

    public static String getFarmIds(HttpServletRequest request) {
        String jwtToken = request.getHeader("accessToken");
        if (StringUtils.isBlank(jwtToken)) {
            return null;
        }
        Claims claims = getClaims(jwtToken);
        return (String) claims.get("farmIds");
    }

    /**
     * 获取claims对象
     *
     * @param jwtToken
     * @return
     */
    public static Claims getClaims(String jwtToken) {
        try {
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
            return claimsJws.getBody();
        }catch (ExpiredJwtException e){
            return null;
        }


    }
    /**
     * 是否过期
     *
     * @param claims
     * @return -1：有效，0：有效，1：过期，2：被篡改
     */
    public static int verifyToken(Claims claims) {
        if (claims == null) {
            return 1;
        }
        try {
            claims.getExpiration()
                    .before(new Date());
            // 需要自动刷新TOKEN
            if ((claims.getExpiration().getTime() - System.currentTimeMillis()) < REFRESH_TIME * 1000) {
                return -1;
            } else {
                return 0;
            }
        } catch (ExpiredJwtException ex) {
            return 1;
        } catch (Exception e) {
            return 2;
        }
    }


}