package com.chushang.security.utils;

import com.chushang.security.context.SecurityContextHolder;
import com.chushang.common.core.constant.SecurityConstants;
import com.chushang.common.core.constant.TokenConstants;
import com.chushang.common.core.util.ServletUtils;
import com.chushang.common.core.util.StringUtils;
import com.chushang.security.auth.AuthUtil;
import com.chushang.security.entity.vo.LoginUser;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import javax.servlet.http.HttpServletRequest;
import java.util.Set;

/**
 * 权限获取工具类
 *
 * @author ruoyi
 */
public class SecurityUtils<T>
{
    public static final String PA_SA = "%s:%s";
    /**
     * 获取用户ID
     */
    public static Long getUserId()
    {
        return SecurityContextHolder.getUserId();
    }

    public static boolean isAdmin(){
        Long userId = SecurityContextHolder.getUserId();

        LoginUser<?, ?> loginUser = getLoginUser();
        Set<String> roles = loginUser.getRoles();
        // 包含 admin 的账号 或者 id == 1 的就是 admin -- 必须是 admin 的才是超管权限
        boolean flag = roles.contains(AuthUtil.SUPER_ADMIN);

        return (userId != null && 1 == userId) || flag;
    }

    /**
     * 获取用户名称
     */
    public static String getUsername()
    {
        return SecurityContextHolder.getUserName();
    }

    /**
     * 获取登录用户信息
     */
    public static LoginUser getLoginUser()
    {
        return SecurityContextHolder.get(SecurityConstants.LOGIN_USER, LoginUser.class);
    }

    /**
     * 获取请求token
     */
    public static String getToken()
    {
        return getToken(ServletUtils.getRequest());
    }

    /**
     * 根据request获取请求token
     */
    public static String getToken(HttpServletRequest request)
    {
        // 从header获取token标识
        String token = request.getHeader(TokenConstants.AUTHENTICATION);
        return replaceTokenPrefix(token);
    }

    /**
     * 裁剪token前缀
     */
    public static String replaceTokenPrefix(String token)
    {
        // 如果前端设置了令牌前缀，则裁剪掉前缀
        if (StringUtils.isNotEmpty(token) && token.startsWith(TokenConstants.PREFIX))
        {
            token = token.replaceFirst(TokenConstants.PREFIX, "");
        }
        return token;
    }

    public static String encryptPassword(String password, String salt)
    {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.encode(String.format(PA_SA, password, salt));
    }

    /**
     * 判断密码是否相同
     * @param rawPassword 真实密码
     * @param salt 盐
     * @param encodedPassword 加密后字符
     * @return 结果
     */
    public static boolean matchesPassword(String rawPassword,String salt ,String encodedPassword)
    {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.matches(String.format(PA_SA, rawPassword, salt), encodedPassword);
    }
}
