package org.wfc.user.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.wfc.common.core.constant.UserConstants;
import org.wfc.common.core.utils.StringUtils;
import org.wfc.user.api.domain.URole;
import org.wfc.user.api.domain.UUser;
import org.wfc.user.service.IUMenuService;
import org.wfc.user.service.IUPermissionService;
import org.wfc.user.service.IURoleService;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 用户权限处理
 * 
 * @author wfc
 */
@Service
public class UPermissionServiceImpl implements IUPermissionService
{
    @Autowired
    private IURoleService roleService;

    @Autowired
    private IUMenuService menuService;

    /**
     * 获取角色数据权限
     * 
     * @param user 用户
     * @return 角色权限信息
     */
    @Override
    public Set<String> getRolePermission(UUser user)
    {
        Set<String> roles = new HashSet<String>();
        // 管理员拥有所有权限
        if (user.isAdmin())
        {
            roles.add("super");
        }
        else
        {
            roles.addAll(roleService.selectRolePermissionByUserId(user.getUserId()));
        }
        return roles;
    }

    /**
     * 获取菜单数据权限
     * 
     * @param user 用户
     * @return 菜单权限信息
     */
    @Override
    public Set<String> getMenuPermission(UUser user)
    {
        Set<String> perms = new HashSet<String>();
        // 管理员拥有所有权限
        if (user.isAdmin())
        {
            perms.add("*:*:*");
        }
        else
        {
            List<URole> roles = user.getRoles();
            if (!CollectionUtils.isEmpty(roles))
            {
                // 多角色设置permissions属性，以便数据权限匹配权限
                for (URole role : roles)
                {
                    if (StringUtils.equals(role.getStatus(), UserConstants.ROLE_NORMAL))
                    {
                        Set<String> rolePerms = menuService.selectMenuPermsByRoleId(role.getRoleId());
                        role.setPermissions(rolePerms);
                        perms.addAll(rolePerms);
                    }
                }
            }
            else
            {
                perms.addAll(menuService.selectMenuPermsByUserId(user.getUserId()));
            }
        }
        return perms;
    }
}
