package com.bohuikeji.frame.module.admin.utils;


import com.bohuikeji.frame.module.admin.entity.sys.SysUser;
import com.bohuikeji.frame.module.admin.exception.WebVerifiedException;
import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;

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

/**
 * tokenTool
 * @author leopard
 *
 */
@Slf4j
public final class JwtTokenUtil {

    //私钥
    private static final String SECRET = "deliveryjwtsrcret";
    //发行人
    private static final String ISS = "delivery";

    // 过期时间是3600秒，既是1个小时
    //public static final long EXPIRATION = 3600L;

    // 选择了记住我之后的过期时间为7天
    public static final long EXPIRATION_REMEMBER = 3600L*24*60;
    //过期时间一年
    public static final Long API_YOUK_TEMP=3600L*24*365;

    public static final String[] type={"客户","管理员","派送员"};

    /**
     * 获取游客Token
     * @param request
     * @return
     */
    public static String crateToken(HttpServletRequest request){
        log.info("当前用户，获取游客token，IP=[{}]",request.getRemoteHost());
        return Jwts.builder()
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .claim("type","游客")
                .claim("ip",IpUtil.getIpAddr(request))
                .setIssuer(ISS)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_REMEMBER * 1000))
                .compact();
    }

    /**
     * 获取TOKEN
     * @param type 用户类型
     * @param userId 用户ID
     * @param failureTime 有效时间(秒)
     * @return
     */
    public static String createToken(String type,Integer userId,long failureTime){
        return Jwts.builder()
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .claim("type",type)
                .claim("userId",userId)
                .setIssuer(ISS)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() +(failureTime*1000)))
                .compact();

    }
    /**
     * 获取用户Token
     * @param type
     * @param userId
     * @return
     */
    public static String createToken(String type,Integer userId){
        return Jwts.builder()
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .claim("type",type)
                .claim("userId",userId)
                .setIssuer(ISS)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + API_YOUK_TEMP * 1000))
                .compact();

    }

    /**
     * 从token中获取用户名
     * @param token
     * @return
     */
    /*public static String getUsername(String token){
        return getTokenBody(token).getSubject();
    }*/

    /**
     * 从token中获取ID，同时做解密处理
     * @param token
     * @return
     */
    /*public static String getObjectId(String token){
        return RCUtils.decry(getTokenBody(token).getId());
    }*/


    /**
     * 是否已过期
     * @param token
     * @throws	 //过期无法判断，只能通过捕获ExpiredJwtException异常
     * @return
     */
    /*@Deprecated
    public static boolean isExpiration(String token){
        return getTokenBody(token).getExpiration().before(new Date());
    }*/

    /**
     * 获取token信息，同时也做校验处理
     * @param token
     * @throws	 //自定义UserLoginException异常处理
     * @return
     */
   /* public static Claims getTokenBody(String token){
        try{
            return Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token)
                    .getBody();
        }catch(ExpiredJwtException expired){
            //过期
            throw new UserLoginException(SystemCodeAndMsg.TOKEN_EXPIRED);
        }catch (SignatureException e){
            //无效
            throw new UserLoginException(SystemCodeAndMsg.INVALID_REQUEST);
        }catch(MalformedJwtException malformedJwt){
            //无效
            throw new UserLoginException(SystemCodeAndMsg.INVALID_REQUEST);
        }
    }*/
    private static Claims getClaims(String token){
        return Jwts.parser()
                .setSigningKey(SECRET)
                .parseClaimsJws(token)
                .getBody();
    }

    public static Integer verify(String token){
        Claims claims;
        Integer userId;
        //验证token
        try {claims=getClaims(token);}
        catch(Exception e){
            //log.error("token校验异常：",e);
            return -1;
        }
        try{
            if(!(boolean) claims.get("login")){
                return 0;
            }
        }catch(Exception e){
            if("游客".equals((String)claims.get("type"))){
                return 0;
            }
        }
        userId=(Integer) claims.get("userId");
        if(userId==null){
            return -1;
        }
        return userId;
    }
    public static String getType(String token){
        Claims claims;
        try {
            claims=getClaims(token);
        }
        catch(Exception e){
            return null;
        }
        return (String) claims.get("type");
    }
    /*public static SysUser verifyUser(String token){
        Claims claims;
        try {
            claims=Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token)
                    .getBody();
        }
        catch(Exception e){
            throw new WebVerifiedException("用户Token校验失败！");
        }
        SysUser user= (SysUser) claims.get("userInfo");
        if(user==null){
            throw new WebVerifiedException("用户信息为空！");
        }
        return user;

    }*/
}