package com.philisense.www.utils;

import com.alibaba.fastjson.JSONObject;
import com.philisense.www.constant.Constants;
import com.philisense.www.core.text.Convert;
import com.philisense.www.enums.ClientStatus;
import com.philisense.www.pojos.entity.JwtUser;
import com.philisense.www.utils.ip.AddressUtils;
import com.philisense.www.utils.ip.IpUtils;
import eu.bitwalker.useragentutils.UserAgent;
import io.jsonwebtoken.*;
import io.jsonwebtoken.impl.DefaultClock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;

/**
 * token验证处理
 *
 * @author
 */
@Component
public class JwtTokenUtils implements Serializable {

    private static final Logger log = LoggerFactory.getLogger(JwtTokenUtils.class);

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

    /**
     * 令牌自定义标识
     */
    @Value("${jwt.header}")
    private String header;

    /**
     * 令牌秘钥
     */
    @Value("${jwt.secret}")
    private String secret;

    /**
     * 令牌有效期（默认30分钟）
     */
    @Value("${jwt.expiration}")
    private Long expiration;

    /**
     * APP令牌有效期（默认30分钟）
     */
    @Value("${jwt.appExpiration}")
    private Long appExpiration;

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

    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;

    @Autowired
    private RedisUtils redisUtils;

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public JwtUser getJwtUser(HttpServletRequest request) {
        // 获取请求携带的令牌
        String token = getToken(request);
        if (StringUtils.isNotEmpty(token)) {
            try {
                Claims claims = parseToken(token);
                // 解析对应的权限以及用户信息
                String uuid = (String) claims.get(Constants.LOGIN_USER_KEY);
                String userKey = getTokenKey(uuid);
                String value = redisUtils.get(userKey);
                JwtUser jwtUser = null;
                if(StringUtils.isNotEmpty(value)) {
                    JSONObject jsonObject = JSONObject.parseObject(value);
                    jwtUser = JSONObject.parseObject(value, JwtUser.class);

                    // 获取当前用户角色
                    if(StringUtils.isNotNull(jsonObject.getJSONArray("authorities"))) {
                        jwtUser.setAuthorities(jsonObject.getJSONArray("authorities").stream().map(role ->  new SimpleGrantedAuthority(((JSONObject) role).getString("authority")))
                                .collect(Collectors.toList()));
                    }
                }
                return jwtUser;
            }
            catch (Exception e) {
                log.error("JwtTokenUtils.getJwtUser: {}", e.getMessage());
            }
        }
        return null;
    }

    /**
     * 设置用户身份信息
     */
    public void setJwtUser(JwtUser jwtUser) {
        if (StringUtils.isNotNull(jwtUser) && StringUtils.isNotEmpty(jwtUser.getToken())) {
            refreshToken(jwtUser);
        }
    }

    /**
     * 删除用户身份信息
     */
    public void delJwtUser(String token) {
        if (StringUtils.isNotEmpty(token)) {
            String userKey = getTokenKey(token);
            redisUtils.del(userKey);
        }
    }

    /**
     * 创建令牌
     *
     * @param jwtUser 用户信息
     * @return 令牌
     */
    public String generateToken(JwtUser jwtUser) {
        String token = UUID.randomUUID().toString();
        jwtUser.setToken(token);
        setUserAgent(jwtUser);
        refreshToken(jwtUser);

        Map<String, Object> claims = new HashMap<>();
        claims.put(Constants.LOGIN_USER_KEY, token);
        return createToken(claims, jwtUser.getUsername());
    }

    /**
     * 从数据声明生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private String createToken(Map<String, Object> claims, String subject) {
        final Date createdDate = clock.now();
        String token = Jwts.builder()
                .setClaims(claims)
                .setSubject(subject)
                .setIssuedAt(createdDate)
                .signWith(SignatureAlgorithm.HS512, secret).compact();
        return token;
    }

    /**
     * 刷新令牌有效期
     *
     * @param jwtUser 登录信息
     */
    public void refreshToken(JwtUser jwtUser) {
        Long expireTime = StringUtils.equals(Convert.toStr(ClientStatus.PC.ordinal()), Convert.toStr(jwtUser.getClient())) ? expiration : appExpiration;
        jwtUser.setLoginTime(System.currentTimeMillis());
        jwtUser.setExpireTime(jwtUser.getLoginTime() + expireTime * MILLIS_MINUTE);
        // 根据uuid将jwtUser缓存
        String userKey = getTokenKey(jwtUser.getToken());
        redisUtils.setExpire(userKey, JSONObject.toJSONString(jwtUser), expireTime);
    }

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    private Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * 设置用户代理信息
     *
     * @param jwtUser 登录信息
     */
    public void setUserAgent(JwtUser jwtUser) {
        UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        jwtUser.setIpaddr(ip);
        jwtUser.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
        jwtUser.setBrowser(userAgent.getBrowser().getName());
        jwtUser.setOs(userAgent.getOperatingSystem().getName());
    }

    /**
     * 验证令牌有效期，相差不足20分钟，自动刷新缓存
     *
     * @param jwtUser
     * @return 令牌
     */
    public void verifyToken(JwtUser jwtUser) {
        long expireTime = jwtUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN) {
            refreshToken(jwtUser);
        }
    }

    /**
     * 获取请求token
     *
     * @param request
     * @return token
     */
    private String getToken(HttpServletRequest request) {
        String token = request.getHeader(header);
        if (StringUtils.isNotEmpty(token) && token.startsWith(tokenHeader)) {
            token = token.replace(tokenHeader, "");
        }
        return token;
    }

    private String getTokenKey(String uuid) {
        return Constants.LOGIN_TOKEN_KEY + uuid;
    }
}
