package com.tykj.workflowcore.user.util;

import com.tykj.workflowcore.user.pojo.UserDetail;
import com.tykj.workflowcore.user.pojo.vo.JwtSecurityProperties;
import com.tykj.workflowcore.user.service.CenterUserService;
import io.jsonwebtoken.*;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.security.Key;
import java.time.Instant;
import java.util.*;

@Slf4j
@Component
public class JwtTokenUtils implements InitializingBean {
    @Autowired
    CenterUserService centerUserService;

    private static final String AUTHORITIES_KEY = "VHFBZ2MwbE43NVJFYXVFeFdJMzkxZ2wzNXpRY0N2UmM1T2dPdlYyRnM3T1ZBYmN6cVNtMHhQYTg1dk9zVEgzaGdtc3B0MWIzR3kwNmVGWnlYZ0d3R0ZSc2Z6NnNOdng5aXZBM1JUaURzc21CV2JnSTIxM083Tk8xYzAydmh3bzY==";
    private final JwtSecurityProperties jwtSecurityProperties;

    private Key key;

    public JwtTokenUtils(JwtSecurityProperties jwtSecurityProperties) {
        this.jwtSecurityProperties = jwtSecurityProperties;
    }

    @Override
    public void afterPropertiesSet() {
        byte[] keyBytes = Decoders.BASE64.decode(jwtSecurityProperties.getBase64Secret());
        this.key = Keys.hmacShaKeyFor(keyBytes);
    }

    /**
     * 创建token
     * @param claims
     * @return
     */
    public String createToken(Map<String, Object> claims) {
        return Jwts.builder()
                .claim(AUTHORITIES_KEY, claims)
                .setId(UUID.randomUUID().toString())
                .setIssuedAt(new Date())
                .setExpiration(new Date((new Date()).getTime() + jwtSecurityProperties.getTokenValidityInSeconds()))
                .compressWith(CompressionCodecs.DEFLATE)
                .signWith(SignatureAlgorithm.HS512, key)
                .compact();
    }

    public Date getExpirationDateFromToken(String token) {
        Date expiration;
        try {
            final Claims claims = getClaimsFromToken(token);
            expiration = claims.getExpiration();
        } catch (Exception e) {
            expiration = null;
        }
        return expiration;
    }

    /**
     * 获取用户并放入当前用户中
     * @param token
     * @return
     */
    public Authentication getAuthentication(String token) {
        //解析token
        Claims claims = Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token).getBody();
        HashMap map = (HashMap) claims.get(AUTHORITIES_KEY);
        //通过username获取用户信息
        UserDetail AuthUser = centerUserService.getUserDetail(map.get("username").toString());
        //将用户信息放入当前用户中
        Collection<? extends GrantedAuthority> authorities = AuthUser.getAuthorities();
        return new UsernamePasswordAuthenticationToken(AuthUser, token, authorities);
    }

    /**
     * 认证token是否正确
     * @param authToken
     * @return
     */
    public boolean validateToken(String authToken) {
        try {
            Jws<Claims> claimsJws = Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(authToken);
            return Date.from(Instant.now()).before(claimsJws.getBody().getExpiration());
        } catch (io.jsonwebtoken.security.SecurityException | MalformedJwtException e) {
            log.info("Invalid JWT signature.");
            e.printStackTrace();
        } catch (ExpiredJwtException e) {
            log.info("Expired JWT token.");
            e.printStackTrace();
        } catch (UnsupportedJwtException e) {
            log.info("Unsupported JWT token.");
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            log.info("JWT token compact of handler are invalid.");
            e.printStackTrace();
        }
        return false;
    }

    private Claims getClaimsFromToken(String token) {
        Claims claims;
        try {
            claims = Jwts.parserBuilder().setSigningKey(key).build()
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            claims = null;
        }
        return claims;
    }

}