package org.flowable.ui.common.security;

import cn.hutool.extra.spring.SpringUtil;
import com.jeeplus.common.TokenProvider;
import com.jeeplus.sys.feign.ITenantApi;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.service.dto.UserDTO;
import org.flowable.common.engine.api.FlowableIllegalStateException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import java.util.Set;

/**
 * 重写flowable 6.7.2版权权限
 */
public class SecurityUtils {

    static final String GROUP_PREFIX = "GROUP_";
    static final String TENANT_PREFIX = "TENANT_";
    private static SecurityScopeProvider securityScopeProvider = new FlowableSecurityScopeProvider ( );

    private SecurityUtils() {
    }

    public static GrantedAuthority createTenantAuthority(String tenantId) {
        return new SimpleGrantedAuthority ( "TENANT_" + tenantId );
    }

    public static GrantedAuthority createGroupAuthority(String groupId) {
        return new SimpleGrantedAuthority ( "GROUP_" + groupId );
    }

    public static void setSecurityScopeProvider(SecurityScopeProvider securityScopeProvider) {
        securityScopeProvider = securityScopeProvider;
    }

    public static String getCurrentUserId() {
        SecurityScope user = getCurrentSecurityScope ( );
        return user != null ? user.getUserId ( ) : null;
    }

    public static SecurityScope getCurrentSecurityScope() {
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken ( TokenProvider.getCurrentToken ( ) );
        SecurityScope securityScope = new SecurityScope ( ) {
            @Override
            public String getUserId() {
                return userDTO.getId ( );
            }

            @Override
            public Set <String> getGroupIds() {
                return null;
            }

            @Override
            public String getTenantId() {
                return SpringUtil.getBean ( ITenantApi.class ).getCurrentTenantId ( );
            }

            @Override
            public boolean hasAuthority(String s) {
                return false;
            }
        };
        return securityScope;
    }

    public static SecurityScope getSecurityScope(Authentication authentication) {
        return securityScopeProvider.getSecurityScope ( authentication );
    }

    public static SecurityScope getAuthenticatedSecurityScope() {
        SecurityScope currentSecurityScope = getCurrentSecurityScope ( );
        if ( currentSecurityScope != null ) {
            return currentSecurityScope;
        } else {
            throw new FlowableIllegalStateException ( "User is not authenticated" );
        }
    }
}
