

package com.nantian.sc.cloud.common.security.util;


import cn.hutool.core.util.StrUtil;
import com.nantian.sc.cloud.common.core.constant.SecurityConstants;
import com.nantian.sc.cloud.common.security.service.OAuthTokenUser;
import com.nantian.sc.cloud.common.security.service.ScUser;
import lombok.experimental.UtilityClass;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.common.OAuth2AccessToken;

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

/**
 * 安全工具类
 *
 * @author L.cm
 */
@UtilityClass
public class SecurityUtils {
    /**
     * 获取Authentication
     */
    public Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 获取用户
     *
     * @param authentication
     * @return ScUser
     * <p>
     */
    public ScUser getUser(Authentication authentication) {
        Object principal = authentication.getPrincipal();
        if (principal instanceof ScUser) {
            return (ScUser) principal;
        }
        return null;
    }

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


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

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

    /**
     * @param oAuth2AccessToken
     * @return com.nantian.sc.cloud.common.security.service.OAuthTokenUser
     * @Description: 根据OAuth2AccessToken获取用户基础信息
     * @Author: dengjian
     * @DATE: 2024/11/25 9:06
     */
    public OAuthTokenUser getUserByOAuth2AccessToken(OAuth2AccessToken oAuth2AccessToken) {
        Map<String, Object> additionalInformation = oAuth2AccessToken.getAdditionalInformation();
        if (null != additionalInformation) {
            return MapToEntityScUser(additionalInformation);
        }
        return null;
    }

    public OAuthTokenUser MapToEntityScUser(Map<String, Object> map) {
        try {
            Integer id = Integer.valueOf(map.get("user_id").toString());
            Integer tenantId = Integer.valueOf(map.get("tenant_id").toString());
            String userName = map.get("username").toString();
            String userRealName = map.get("user_real_name").toString();
            String enterpriseCode = map.get("enterprise_code") == null ? "" : map.get("enterprise_code").toString();
            Integer deptId = Integer.valueOf(map.get("dept_id").toString());
            String userDept = map.get("user_dept").toString();
            return new OAuthTokenUser(id, deptId, tenantId, enterpriseCode, userRealName, userDept, userName);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


}
