package com.ai.da.common.security.jwt;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.ai.da.common.constant.CommonConstant;
import com.ai.da.common.security.config.SecurityProperties;
import com.ai.da.model.vo.AuthPrincipalVo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;

/**
 * @author: dangweijian
 * @description: JWT工具
 * @create: 2020-07-09 09:27
 **/
@Slf4j
@Component
public class JWTTokenHelper {

    @Resource
    private SecurityProperties securityProperties;

    private static final String ISSUER = "DWJ";
    private static final String AUTHORITIES = "authorities";
    private static final String CHANGE_MAILBOX = "changeMailbox";

    public String createToken(AuthPrincipalVo principal) {
        String token = Jwts.builder()
                .setId(String.valueOf(principal.getId()))
                .setSubject(JSONObject.toJSONString(principal))
                .setIssuedAt(new Date())
                .setIssuer(ISSUER)
                .claim(AUTHORITIES, JSON.toJSONString(new ArrayList<>()))//自定义属性  权限
                .setExpiration(new Date(System.currentTimeMillis() + securityProperties.getJwtExpiration()))
                .signWith(SignatureAlgorithm.HS512, securityProperties.getJwtSecret())
                .compact();
        token = securityProperties.getJwtTokenPrefix() + token;
        return token;
    }

    public boolean validateToken(String token) {
        Claims claims = parser(token);
        if (MapUtil.isEmpty(claims)) {
            return false;
        }
        return true;
    }

    public AuthPrincipalVo parserToUser(String token) {
        String subject = parser(token).getSubject();
        if (StrUtil.isNotEmpty(subject)) {
            return JSONObject.parseObject(subject, AuthPrincipalVo.class);
        }
        return null;
    }

    public Claims parser(String token) {
        token = token.replaceAll(securityProperties.getJwtTokenPrefix(), "");
        return Jwts.parser().setSigningKey(securityProperties.getJwtSecret()).parseClaimsJws(token).getBody();
    }

    public String createToken(Long userId, String userEmail){
        String token = Jwts.builder()
                .setId(String.valueOf(userId))
                .setSubject(userEmail + "_" + userId)
                .setIssuedAt(new Date())
                .setIssuer(ISSUER)
                .claim(CHANGE_MAILBOX, JSON.toJSONString(new ArrayList<>()))//自定义属性  权限
                .setExpiration(new Date(System.currentTimeMillis() + CommonConstant.CHANGE_MAILBOX_LINK_VALIDITY))
                .signWith(SignatureAlgorithm.HS256, securityProperties.getJwtSecret())
                .compact();
        return token;
    }

    public String parseToEmailAndId(String token) {
        return parser(token).getSubject();
    }
}
