package com.tykj.dev.device.user.config.url;

import com.tykj.dev.device.user.subject.dao.RoleDao;
import com.tykj.dev.device.user.subject.entity.Permissions;
import com.tykj.dev.device.user.subject.entity.Role;
import com.tykj.dev.device.user.subject.entity.RolePermissions;
import com.tykj.dev.device.user.subject.service.PermissionsService;
import com.tykj.dev.device.user.subject.service.RolePermissionsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

/**
 * <p> 获取访问该url所需要的用户角色权限信息 </p>
 *
 * @author : zhengqing
 * @description : 执行完之后到 `UrlAccessDecisionManager` 中认证权限
 * @date : 2019/10/15 14:36
 */
@Component
public class UrlFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {


    @Autowired
    RoleDao roleDao;

    @Autowired
    RolePermissionsService rolePermissionsService;

    @Autowired
    PermissionsService permissionsService;

    /***
     * 返回该url所需要的用户权限信息
     *
     * @param object: 储存请求url信息
     * @return: null：标识不需要任何权限都可以访问
     */
    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        // 获取当前请求url
        String requestUrl = ((FilterInvocation) object).getRequestUrl();
        // TODO 忽略url请放在此处进行过滤放行
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        if ("/userLogin".equals(requestUrl) || "/swagger-ui.html".equals(requestUrl)) {
            return null;
        }

        // 数据库中所有url
        List<Permissions> permissionList = permissionsService.findAll();
        List<String> roles = new LinkedList<>();
        for (Permissions permission : permissionList) {
            // 获取该url所对应的权限
//            matcher.matches(request)
            if (antPathMatcher.match(permission.getUrl(), requestUrl)) {
                List<RolePermissions> permissions = rolePermissionsService.findAllByPermissionsId(permission.getPermissionsId());

                if (!CollectionUtils.isEmpty(permissions)) {
                    permissions.forEach(
                            per -> {
                                Integer roleId = per.getRoleId();
                                Role role = roleDao.findById(roleId).get();
                                roles.add(role.getRoleName());
                            }
                    );
                }
                // 保存该url对应角色权限信息

            }
        }
        if (roles.size() == 0) {
            //公共url
            return SecurityConfig.createList("未登陆");
        } else {
            return SecurityConfig.createList(roles.toArray(new String[0]));
        }
        // 如果数据中没有找到相应url资源则为非法访问，要求用户登录再进行操作

    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return FilterInvocation.class.isAssignableFrom(aClass);
    }
}
