package com.ycwl.basic.utils;

import com.ycwl.basic.exception.CheckTokenException;
import com.ycwl.basic.model.jwt.JwtInfo;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.Objects;

;

/**
 * @author yangchen
 */
@SuppressWarnings("ALL")
@Slf4j
@Component
public class JwtTokenUtil {

    @Getter
    @Value("${jwt.expire:15}")
    private int expire;

    private static String PRI_KEY = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAKOpJ+Ob4VI6sipH47lNQF94YVjNvf/NS8x8gsq/qYG8JOM016prGpHBF6fZOv1yKDnBwJRwC+2oBm3PmybXUZiKIYScoLIFcoV9GbuZZ1ktEWpzUSbN4ZHMj2ylkVHi07HlR4L3PzJlbzC410yg2ZS2WKoanJRHUAmrcN4bvXvBAgMBAAECgYBw7LLdVh1uw5lTmy8CGM+mEEX7JFtJObpnajJE+2JWZh99tmRo7mXy1C0iX71YS4B9+baLtZRFc36cHneLoV5mqhWOf84W/zha+z5dlh1ErSLL6t8YKpJ2GQUMu9Y90VHf5eyhUTu0W7bc+Nvr3GSzaDpMy4fm0XjrazIBuYDvAQJBAOShdiZJnKPBLP98XsVD8L3EB1Tpe3qFviYHhvnhaafMmoY8AR3OqMAIn8jLUiUsIdiOpWL2tNFfCkk0kwLpb2kCQQC3QKXKQjY1j8YGrSQw8YFry5qFcdHP+ybw8lc090wHZjFYlpLSjL6AoTwt+bMyArr2WWCN9G/tU5aVLajZc/aZAkByMtAQGc664L+4MYgo4mG6d9Ltr930eh9bYYEjCVu76+/3QruQBuy1Vtlw81XpqVySjdXAU9hHiEBcBn20A6OZAkAW65IQ8ykel+X3zc4aBQrf9a5VBIBumAYt2tHHgSrUPhbr8qFYjlwBcKk7QuED302NJG6sMqeRMoRCElztHdD5AkAWZCbWQQtFmgWB9fZQxKT94c+zL7HJwgcmtmQq8JHgcoOE1jgi5bVksm8vhDeATOAUEAt0Dt+vwTPaPvFL5JdW";
    private static String PUB_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCjqSfjm+FSOrIqR+O5TUBfeGFYzb3/zUvMfILKv6mBvCTjNNeqaxqRwRen2Tr9cig5wcCUcAvtqAZtz5sm11GYiiGEnKCyBXKFfRm7mWdZLRFqc1EmzeGRzI9spZFR4tOx5UeC9z8yZW8wuNdMoNmUtliqGpyUR1AJq3DeG717wQIDAQAB";

    /**
     * 生成 token
     *
     * @param jwtInfo
     * @param otherInfo
     * @param expireTime 会增加一个 expire 作为 token 的过期时间
     * @return
     * @throws Exception
     */
    public String generateToken(JwtInfo jwtInfo) throws Exception {
        // 过期时间，默认 15 天
        return generateToken(jwtInfo, expire);
    }

    public static String generateToken(JwtInfo jwtInfo, int expire) throws Exception {
        LocalDateTime expireTime = LocalDateTime.now().plusDays(expire);
        byte[] bytes = RsaKeyUtil.toBytes(PRI_KEY);
        String token = JwtAnalysisUtil.generateToken(jwtInfo, bytes, expireTime);
        return token;
    }


    /**
     * 解析Token
     *
     * @param token
     * @return
     * @throws Exception
     */
    public static JwtInfo parsingToken(String token) throws CheckTokenException {
        try {
            JwtInfo infoFromToken = JwtAnalysisUtil.getInfoFromToken(token, RsaKeyUtil.toBytes(PUB_KEY));
            return infoFromToken;
        } catch (Exception e) {
            e.printStackTrace();
            throw new CheckTokenException("token is invalid");
        }
    }

    public static JwtInfo getWorker() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();

        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            if (request.getCookies() != null) {
                for (Cookie cookie : request.getCookies()) {
                    if (("token").equals(cookie.getName())) {
                        token = cookie.getValue();
                    }
                }
                if(StringUtils.isEmpty(token)){
                    throw new CheckTokenException("用户未登录或登录状态已过期");
                }
            }else {
                throw new CheckTokenException("用户未登录或登录状态已过期");
            }
        }
        return parsingToken(token);
    }

    public static void main(String[] args) throws Exception {
        JwtInfo jwtInfo = new JwtInfo();
        jwtInfo.setUserId(3936940597855784960L);
        jwtInfo.setName("微信用户");
        System.out.println(generateToken(jwtInfo, 86400));
    }
}
