package com.om.utils;

import com.om.entity.dto.GuidDTO;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;

import org.springframework.stereotype.Component;

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

@Data
@ConfigurationProperties(prefix = "jwt")
@Component
public class JwtUtils {
    //密钥
    private String secret;

    // 过期时间 毫秒
    private Long expiration;


    /**
     * 从数据声明生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    public String generateToken(Map<String, Object> claims) {
        Date expirationDate = new Date(System.currentTimeMillis() + expiration);
        return Jwts.builder().setClaims(claims).setExpiration(expirationDate).signWith(SignatureAlgorithm.HS512, secret).compact();
    }

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    public Claims getClaimsFromToken(String token) {
        Claims claims;
        try {
            claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
        } catch (Exception e) {
            claims = null;
        }
        return claims;
    }

    /**
     * 从令牌中获取AdminId
     *
     * @param token 令牌
     * @return uid
     */
    public Integer getAdminIdFromToken(String token) {
        Integer aId;
        try {
            Claims claims = getClaimsFromToken(token);
            aId = claims.get("a_id", Integer.class);
        } catch (Exception e) {
            aId = null;
        }
        return aId;
    }

    /**
     * 从令牌中获取map
     *
     * @param token 令牌
     * @return id
     */
    public GuidDTO getGuidDTOFromToken(String token) {
        GuidDTO dto = new GuidDTO();

        try {
            Claims claims = getClaimsFromToken(token);
            Integer uId = claims.get("u_id", Integer.class);
            String deviceSn = claims.get("deviceSn", String.class);
            String appVersion = claims.get("appVersion", String.class);
            String clientNum = claims.get("clientNum", String.class);

            dto.setUserId(uId);
            dto.setDeviceSn(deviceSn);
            dto.setAppVersion(appVersion);
            dto.setClientNum(clientNum);

        } catch (Exception e) {
            dto = null;
        }
        return dto;
    }

    /**
     * 从令牌中获取id
     *
     * @param token 令牌
     * @return id
     */
    public Integer getUserIdFromToken(String token) {
        Integer uId;
        try {
            Claims claims = getClaimsFromToken(token);
            uId = claims.get("u_id", Integer.class);
        } catch (Exception e) {
            uId = null;
        }
        return uId;
    }

    /**
     * 判断令牌是否过期
     *
     * @param token 令牌
     * @return 是否过期
     */
    public Boolean isTokenExpired(String token) {
        Claims claims = getClaimsFromToken(token);
        Date expiration = claims.getExpiration();
        return expiration.before(new Date());
    }

    /**
     * 刷新令牌
     *
     * @param token 原令牌
     * @return 新令牌
     */
    public String refreshToken(String token) {
        String refreshedToken;
        try {
            Claims claims = getClaimsFromToken(token);
            claims.put(Claims.ISSUED_AT, new Date());
            refreshedToken = generateToken(claims);
        } catch (Exception e) {
            refreshedToken = null;
        }
        return refreshedToken;
    }

    /**
     * 管理员验证令牌
     *
     * @param token   令牌
     * @param adminId admin
     * @return 是否有效
     */
    public Boolean validateAdminToken(String token, Integer adminId) {
        Integer aId = getAdminIdFromToken(token);
        return (aId.equals(adminId) && !isTokenExpired(token));
    }

    /**
     * 用户验证令牌
     *
     * @param token  令牌
     * @param userId userId
     * @return 是否有效
     */
    public Boolean validateUserToken(String token, Integer userId) {
        Integer uId = getUserIdFromToken(token);
        return (uId.equals(userId) && !isTokenExpired(token));
    }
}

