package com.xy.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xy.entity.SysRoleMenu;
import com.xy.mapper.SysRoleMenuMapper;
import com.xy.service.SysRoleMenuService;
import com.xy.vo.RoleMenuVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/***
 * 角色菜单表
 * @author 谭斌
 * @date 2022/12/13 9:21
 */
@Service
public class SysRoleMenuServiceImpl extends ServiceImpl<SysRoleMenuMapper, SysRoleMenu> implements SysRoleMenuService {

    /**
     * 更新角色菜单权限
     *
     * @param roleMenuVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveRoleMenus(RoleMenuVo roleMenuVo) {
        Long roleId = roleMenuVo.getId();
        List<Long> menuIds = roleMenuVo.getMenuIds();
        Long sysId = roleMenuVo.getSysId();
        //移除旧的权限
        remove(Wrappers.<SysRoleMenu>query().lambda().eq(SysRoleMenu::getRoleId, roleId));

        if (CollectionUtil.isEmpty(menuIds)) {
            return Boolean.TRUE;
        }
        //封装角色菜单权限
        List<SysRoleMenu> roleMenuList = menuIds.stream().map(menuId -> {
            SysRoleMenu roleMenu = new SysRoleMenu();
            roleMenu.setRoleId(roleId);
            roleMenu.setMenuId(menuId);
            roleMenu.setSysId(sysId);
            return roleMenu;
        }).collect(Collectors.toList());
        //批量保存
        return saveBatch(roleMenuList);
    }

    @Override
    public List<Long> getRoleMenus(Long roleId) {
        List<SysRoleMenu> sysRoleMenus = this.list(Wrappers.<SysRoleMenu>lambdaQuery().eq(SysRoleMenu::getRoleId, roleId));
        return sysRoleMenus.stream().map(SysRoleMenu::getMenuId).collect(Collectors.toList());
    }
}
