package com.ankaibei.workFlow.webadmin.ankaibei.utils;

import com.ankaibei.workFlow.webadmin.ankaibei.entity.LoginTokenEntity;
import com.ankaibei.workFlow.webadmin.ankaibei.mapper.LoginTokenMapper;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.*;

/**
 * <p>Title: JwtUtil</p>
 * <p>Description: </p>
 *
 * @author liuwq
 * @date 2021年12月3日
 */
@Component
public class JwtUtil {

    //加盐加密
    private final static String TOKEN_SECRET = "hhhqsdcdjaljdjajdajdwijiajdiavbnko";

    private static JwtUtil JwtUtils;

    @Resource
    private LoginTokenMapper loginTokenMapper;

    @PostConstruct
    public void init() {
        JwtUtils = this;
        JwtUtils.loginTokenMapper = this.loginTokenMapper;
    }

    /**
     * token的生成
     *
     * @param
     * @param subjectSNO 用户账号
     * @param map
     * @return token
     */
    public static String getToken(String subjectSNO, Map<String, Object> map) {
        String token = "";
        token = JWT.create().withAudience(subjectSNO)
                .withClaim("userAcct", subjectSNO)//用户账号
                .withClaim("userId", (Integer) map.get("userId")) //用户id
                .sign(Algorithm.HMAC256(String.valueOf(UUID.randomUUID())));
        return token;
    }

    /**
     * 验证,并获取payload中的存储键值对信息
     *
     * @param token
     * @return
     * @throws Exception
     */
    public static Map<String, Claim> verifyToken(String token) {
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).build();
        DecodedJWT decodedJWT = null;
        try {
            decodedJWT = jwtVerifier.verify(token);
        } catch (JWTVerificationException e) {
            throw new RuntimeException("Token已过期，请重新登录");
        }
        return decodedJWT.getClaims();
    }

    /**
     * 验证token, 返回 true / false
     *
     * @param token
     * @return
     * @throws Exception
     */
    public static Boolean checkToken(String token) {
        try {
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).build();
            DecodedJWT decodedJWT = jwtVerifier.verify(token);
            if (decodedJWT == null) {
                return false;
            }
        } catch (JWTVerificationException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }


    /**
     * 在没有进行验证token的情况下,
     * <p>
     * 根据参数名称,从token中获取荷载部分的参数的value值,
     *
     * @param token
     * @param paramName
     * @return
     * @author zhou haijun
     */
    public static <T> T getValueOfPayloadByTokenAndParamName(String token, String paramName, Class<T> t) {
        T as = JWT.decode(token).getClaim(paramName).as(t);
        return as;
    }

    /**
     * 获取当前网络ip
     *
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ipAddress = request.getHeader("x-forwarded-for");
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
                //根据网卡取本机配置的IP
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                ipAddress = inet.getHostAddress();
            }
        }
        //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if (ipAddress != null && ipAddress.length() > 15) { //"***.***.***.***".length() = 15
            if (ipAddress.indexOf(",") > 0) {
                ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
            }
        }
        return ipAddress;
    }

    /**
     * 生成token信息
     *
     * @param loginAcct 账号
     * @return TokenVo
     */
    public static String createTokenVo(String loginAcct, Integer userId) {

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userId", userId);
        String token = JwtUtil.getToken(loginAcct, map);
        Map<String, Object> result = new HashMap<>(16);
        return token;
    }

    /**
     * 获取当天最大毫秒值
     *
     * @param
     * @return ResMsg
     */
    public static long getDayMaxTime() {
        Calendar todayEnd = Calendar.getInstance();
        todayEnd.set(Calendar.HOUR_OF_DAY, 23);
        todayEnd.set(Calendar.MINUTE, 59);
        todayEnd.set(Calendar.SECOND, 59);
        todayEnd.set(Calendar.MILLISECOND, 999);
        return todayEnd.getTime().getTime() - System.currentTimeMillis();
    }

    public static Boolean findLoginToken(String token) {
        Integer userId = null;
        try {
            userId = getValueOfPayloadByTokenAndParamName(token, "userId", Integer.class);
        } catch (Exception e) {
            return false;
        }
        Optional<LoginTokenEntity> byId = JwtUtils.loginTokenMapper.findById(userId);
        LoginTokenEntity loginTokenEntity = byId.orElse(null);
        if (StringUtils.isEmpty(loginTokenEntity)) {
            return false;
        }
        return loginTokenEntity.getUserToken().equals(token);
    }


}
