package com.philisense.www.utils;

import com.philisense.www.pojos.entity.JwtUser;
import io.jsonwebtoken.*;
import io.jsonwebtoken.impl.DefaultClock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import java.io.Serializable;
import java.util.*;
import java.util.function.Function;

@Component
public class JwtTokenUtilBak implements Serializable {

    private static final long serialVersionUID = -3301605591108950415L;
    private Clock clock = DefaultClock.INSTANCE;

    @Value("${jwt.secret}")
    private String secret;

    @Value("${jwt.expiration}")
    private Long expiration;

    @Value("${jwt.header}")
    private String header;

    @Value("${jwt.tokenHead}")
    private String tokenHeader;

    @Autowired
    private RedisUtils redisUtils;

    public String getUsernameFromToken(String token) {
        return getClaimFromToken(token, Claims::getSubject);
    }

    public Date getIssuedAtDateFromToken(String token) {
        return getClaimFromToken(token, Claims::getIssuedAt);
    }

    public Date getExpirationDateFromToken(String token) {
        return getClaimFromToken(token, Claims::getExpiration);
    }

    public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
        final Claims claims = getAllClaimsFromToken(token);
        return claimsResolver.apply(claims);
    }

    public Claims getAllClaimsFromToken(String token) {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }

    private Boolean isTokenExpired(String token) {
        final Date expiration = getExpirationDateFromToken(token);
        return expiration.before(clock.now());
    }

    private Boolean isCreatedBeforeLastPasswordReset(Date created, Date lastPasswordReset) {
        return (lastPasswordReset != null && created.before(lastPasswordReset));
    }

    private Boolean ignoreTokenExpiration(String token) {
        // here you specify tokens, for that the expiration is ignored
        return false;
    }

    public String generateToken(JwtUser jwtUser) {
        String listroles = "";
        String listrolesvalue = "";
        for(GrantedAuthority auth: jwtUser.getAuthorities()){
            listroles += auth.getAuthority() + ",";
        }
        /*for(GrantedAuthority auth: jwtUser.getAuthoritiesValue()){
            listrolesvalue += auth.getAuthority() + ",";
        }*/

        Map<String, Object> claims = new HashMap<>();
        /*claims.put("username", jwtUser.getUsername());
        claims.put("id", jwtUser.getId());
        claims.put("usernameCn", jwtUser.getUsernameCn());
        claims.put("deptCode", jwtUser.getDeptCode());
        claims.put("dept", jwtUser.getDept());
        claims.put("orgCode", jwtUser.getOrgCode());
        claims.put("org", jwtUser.getOrg());
        claims.put("roles", StringUtils.isNotEmpty(listroles) ? listroles.substring(0, listroles.length() - 1) : "");
        claims.put("roleNames", StringUtils.isNotEmpty(listrolesvalue) ? listrolesvalue.substring(0, listrolesvalue.length() - 1) : "");
*/
        return doGenerateToken(claims, jwtUser.getUsername());
    }

    private String doGenerateToken(Map<String, Object> claims, String subject) {
        final Date createdDate = clock.now();
        final Date expirationDate = calculateExpirationDate(createdDate);

        return Jwts.builder()
                .setClaims(claims)
                .setSubject(subject)
                .setIssuedAt(createdDate)
                .setExpiration(expirationDate)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    public Boolean canTokenBeRefreshed(String token, Date lastPasswordReset) {
        final Date created = getIssuedAtDateFromToken(token);
        return !isCreatedBeforeLastPasswordReset(created, lastPasswordReset)
                && (!isTokenExpired(token) || ignoreTokenExpiration(token));
    }

    public String refreshToken(String token) {
        final Date createdDate = clock.now();
        final Date expirationDate = calculateExpirationDate(createdDate);

        final Claims claims = getAllClaimsFromToken(token);
        claims.setIssuedAt(createdDate);
        claims.setExpiration(expirationDate);

        return Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    public Boolean validateToken(String token, UserDetails userDetails) {
        JwtUser user = (JwtUser) userDetails;
        final Date created = getIssuedAtDateFromToken(token);
//        final Date expiration = getExpirationDateFromToken(token);
//        如果token存在，且token创建日期 > 最后修改密码的日期 则代表token有效
        /*return (!isTokenExpired(token)
                && !isCreatedBeforeLastPasswordReset(created, user.getLastPasswordResetDate())
        );*/
        return true;
    }

    private Date calculateExpirationDate(Date createdDate) {
        return new Date(createdDate.getTime() + expiration);
    }



    /**
     * 将token存储到redis
     */
    public void setExpire(String key, String val, long time) {
        redisUtils.setExpire(key, val, time);
    }

    /**
     * 移除
     */
    public void del(String key) {
        redisUtils.del(key);
    }

    /**
     * 判断是否有效
     * @param authToken
     * @return
     */
    public Boolean validateToken(String authToken) {

        Object o = redisUtils.get(authToken);
        if(null != o){
            return true;
        }
        return false;
    }
}
