package com.tofly.common.oauth.util;

import com.tofly.common.core.constant.SecurityConstants;
import com.tofly.common.core.util.StringUtil;
import com.tofly.common.oauth.auth.ToflyUser;
import lombok.experimental.UtilityClass;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author Administrator
 * @date 2019/9/12  14:29
 */
@UtilityClass
public class SecurityUtils {
    /**
     * 获取Authentication
     */
    public Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 获取用户
     */
    public ToflyUser getUser(Authentication authentication) {
        Object principal = authentication.getPrincipal();
        if (principal instanceof ToflyUser) {
            return (ToflyUser) principal;
        }
        return null;
    }

    public String getTokenValue(){
        Authentication authentication = getAuthentication();
        if(authentication==null){
            return null;
        }
        if(authentication.getDetails() instanceof OAuth2AuthenticationDetails){
            return ((OAuth2AuthenticationDetails)authentication.getDetails()).getTokenValue();
        }
        return null;
    }

    /**
     * 获取用户
     */
    public ToflyUser getUser() {
        Authentication authentication = getAuthentication();
        if (authentication == null) {
            return null;
        }
        return getUser(authentication);
    }

    /**
     * 获取用户ID
     */
    public Long getUserId() {
       ToflyUser toflyUser=getUser();
       return toflyUser.getUserid();
    }

    /**
     * 获取用户部门ID
     */
    public Long getUserDeptId() {
        ToflyUser toflyUser=getUser();
        return toflyUser.getDepartmentId();

    }

    /**
     * 获取用户
     */
    public String getUserName() {
        Authentication authentication = getAuthentication();
        if (authentication == null) {
            return null;
        }
        return authentication.getName();
    }

    /**
     * 获取用户角色信息
     *
     * @return 角色集合
     */
    public List<Integer> getRoles() {
        Authentication authentication = getAuthentication();
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();

        List<Integer> roleIds = new ArrayList<>();
        authorities.stream()
                .filter(granted -> StringUtil.startWith(granted.getAuthority(), SecurityConstants.ROLE))
                .forEach(granted -> {
                    String id = StringUtil.removePrefix(granted.getAuthority(), SecurityConstants.ROLE);
                    roleIds.add(Integer.parseInt(id));
                });
        return roleIds;
    }
}
