package com.xunmei.system.service.impl;

import com.xunmei.system.api.domain.Role;
import com.xunmei.system.api.domain.User;
import com.xunmei.system.service.IMenuService;
import com.xunmei.system.service.IPermissionService;
import com.xunmei.system.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service
public class PermissionServiceImpl implements IPermissionService {

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IMenuService menuService;

    @Override
    public Set<String> getRolePermission(User user) {
        Set<String> roles = new HashSet<>();
        //管理员拥有所有权限
        if(user.isAdmin()){
            roles.add("admin");
            return roles;
        }
        Set<String> rel = roleService.selectRolePermissionByUserId(user.getId());
        roles.addAll(rel);
        return roles;
    }

    /**
     * 获取菜单数据权限
     * @param user 用户
     * @return 菜单权限信息
     */
    @Override
    public Set<String> getMenuPermission(User user) {
        Set<String> perms = new HashSet<>();
        //管理员拥有权限
        if(user.isAdmin()){
            perms.add("*:*:*");
            return perms;
        }
        List<Role> roles = user.getRoles();
        if(!roles.isEmpty() && roles.size() > 1){
            for (Role role : roles) {
                Set<String> rolePerms = menuService.selectMenuPermsByRoleId(role.getId());
                role.setPermissions(rolePerms);
                perms.addAll(rolePerms);
            }
        }else
        {
            perms.addAll(menuService.selectMenuPermsByUserId(user.getId()));
        }

        return perms;
    }
}
