package org.jeecg.config.shiro.util;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;

@Slf4j
@Component
public class ShopTokenUtil {


    @Value("${shop.user.partner.token-key}")
    private String partnerTokenKey;
    @Value("${shop.user.partner.token-expire}")
    private int partnerTokenExpire;




    public String createPartnerCustomerUserToken(String uid) {
        Date now = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);
        calendar.add(Calendar.HOUR, partnerTokenExpire);
        Date exp = calendar.getTime();
        return JWT.create().withAudience(uid)
                .withIssuedAt(now)
                .withExpiresAt(exp)
                .withClaim("uid", uid)
                .sign(Algorithm.HMAC256(partnerTokenKey));
    }

    public boolean verifyPartnerCustomerUserToken(String token) {
        try {
            if (StrUtil.isBlank(token)) {
                return false;
            }
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(partnerTokenKey)).build();
            jwtVerifier.verify(token);
            return true;
        } catch (Exception e) {
            log.warn("CustomerUserToken验证失败，token={}，message={}", token, e.getMessage());
            return false;
        }
    }
    
    public String getUid(String token) {
        // token 必须是有效的
        return JWT.decode(token).getClaim("uid").asString();
    }
    
    
    public long getRemainingSeconds(String token) {
        // token 必须是有效的
        Date issuedAt = JWT.decode(token).getIssuedAt();
        Date expiresAt = JWT.decode(token).getExpiresAt();
        return DateUtil.between(issuedAt, expiresAt, DateUnit.SECOND, true);
    }
    
}
