package org.example.Auth.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.example.Entity.System.LoginUserInfo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.nio.file.LinkOption;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class JwtUtils {
    private final SecretKey secretKey;
    private final long expiration;

    // 使用构造函数注入配置
    public JwtUtils(@Value("${jwt.expiration}") long expiration) {
        // 生成安全的 512 位密钥
        this.secretKey = Keys.secretKeyFor(SignatureAlgorithm.HS512);
        this.expiration = expiration;
    }

    // 生成安全的 HS512 密钥
    private static final Key SECRET_KEY = Keys.secretKeyFor(SignatureAlgorithm.HS512);
    private static final long EXPIRATION_TIME = 1000 * 60 * 60 * 24; // 24小时

    public static String generateToken(Map<String,Object> user) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("UserId", user.get("UserId"));
        claims.put("UserCode", user.get("LoginAccount"));
        claims.put("UserName", user.get("EmpLoyeeName"));
        claims.put("LoginOs", "web");
        claims.put("ServerId", 0);
        claims.put("AppIndex", user.get("AppIndex"));
        claims.put("ClientId", user.get("p_emp_clientid"));
        claims.put("AttendanceTime", user.get("p_emp_AttendanceTime"));
        claims.put("SeriesId",user.getOrDefault("p_emp_SeriesId",0));

        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .signWith(SECRET_KEY, SignatureAlgorithm.HS512)
                .compact();
    }

    public static boolean validateToken(String token) {
        try {
            Claims claims = Jwts.parserBuilder()
                    .setSigningKey(SECRET_KEY)
                    .build()
                    .parseClaimsJws(token)
                    .getBody();

            Date expirationDate = claims.getExpiration();
            Date now = new Date();

            return expirationDate != null && expirationDate.after(now);
        } catch (Exception e) {
            return false;
        }
    }

    // 从令牌中获取用户名
    public static String getUsernameFromToken(String token) {
        return Jwts.parserBuilder()
                .setSigningKey(SECRET_KEY)
                .build()
                .parseClaimsJws(token)
                .getBody()
                .getSubject();
    }
    // 新增公共方法：从 Token 中获取 claims
    public Claims getClaimsFromToken(String token) {
        return Jwts.parserBuilder()
                .setSigningKey(secretKey)
                .build()
                .parseClaimsJws(token)
                .getBody();
    }
}