package com.ruoyi.system.service.system.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.google.common.collect.Lists;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.domain.system.SysRoleMenu;
import com.ruoyi.system.domain.system.enums.PermissionTypeEnum;
import com.ruoyi.system.mapper.system.SysRoleMenuMapper;
import com.ruoyi.system.service.system.SysMenuPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * * Author: brenda
 * * 2024/6/17
 **/
@Service
public class SysMenuPermissionServiceImpl implements SysMenuPermissionService {

    @Autowired
    private SysRoleMenuMapper sysRoleMenuMapper;


    @Override
    public List<Long> getUserMenuIds(SysUser user, String range) {
        Set<Long> set = new HashSet<>();
        List<SysRoleMenu> userMenus = sysRoleMenuMapper.listByTypeAndForeignIdAndRange(PermissionTypeEnum.PERSONAL.getCode(), user.getUserId(), range);
        if(CollectionUtils.isNotEmpty(userMenus)){
            set.addAll(userMenus.stream().map(SysRoleMenu::getMenuId).collect(Collectors.toSet()));
        }
        if(user.getDept() != null){
            List<SysRoleMenu> deptMenus = sysRoleMenuMapper.listByTypeAndForeignIdAndRange(PermissionTypeEnum.DEPT.getCode(), user.getDeptId().toString(), range);
            if(CollectionUtils.isNotEmpty(deptMenus)){
                set.addAll(deptMenus.stream().map(SysRoleMenu::getMenuId).collect(Collectors.toSet()));
            }
        }
        if(CollectionUtils.isNotEmpty(user.getRoles())){
            for(SysRole sysRole : user.getRoles()){
                List<SysRoleMenu> roleMenus = sysRoleMenuMapper.listByTypeAndForeignIdAndRange(PermissionTypeEnum.ROLE.getCode(), sysRole.getRoleId().toString(), range);
                if(CollectionUtils.isNotEmpty(roleMenus)){
                    set.addAll(roleMenus.stream().map(SysRoleMenu::getMenuId).collect(Collectors.toSet()));
                }
            }
        }
        return Lists.newArrayList(set);
    }
}
