package com.njzscloud.common.security.util;

import cn.hutool.extra.spring.SpringUtil;
import com.njzscloud.common.security.contant.Constants;
import com.njzscloud.common.security.support.ITokenService;
import com.njzscloud.common.security.support.Token;
import com.njzscloud.common.security.support.UserDetail;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * 获取认证信息工具
 */
public class SecurityUtil {
    /**
     * 获取当前登录主体信息
     *
     * @return UserAuthPrincipal
     */
    @SuppressWarnings("unchecked")
    public static <T extends UserDetail> T loginUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        T userDetail = null;
        if (authentication != null) userDetail = (T) authentication.getPrincipal();
        return userDetail == null ? (T) Constants.ANONYMOUS_USER : userDetail;
    }

    /**
     * 是否是管理员
     *
     * @return true/false
     */
    public static boolean isAdmin() {
        UserDetail userDetail = SecurityUtil.loginUser();
        return userDetail.getRoles().contains(Constants.ROLE_ADMIN);
    }

    /**
     * 获取当前登录用户 ID
     *
     * @return 用户 ID
     */
    public static Long currentUserId() {
        UserDetail userDetail = SecurityUtil.loginUser();
        return userDetail.getUserId();
    }

    /**
     * 保存用户信息和 TOKEN
     *
     * @param userDetail 用户信息
     */
    public static void registrationToken(UserDetail userDetail) {
        SpringUtil.getBean(ITokenService.class).saveToken(userDetail);
    }

    /**
     * 解析 TOKEN
     *
     * @param tokenStr TOKEN 字符串
     * @return Token
     * @see Token
     */
    public static UserDetail parseToken(String tokenStr) {
        return SpringUtil.getBean(ITokenService.class).loadUser(tokenStr);
    }

    /**
     * 解析 TOKEN
     *
     * @param token TOKEN
     * @see Token
     */
    public static void removeToken(Token token) {
        SpringUtil.getBean(ITokenService.class).removeToken(token);
    }


    public static void removeToken(Long userId) {
        SpringUtil.getBean(ITokenService.class).removeToken(userId);
    }
}
