package cn.com.ty.lift.system.user.service.impl;

import cn.com.ty.lift.common.utils.ProjectUtils;
import cn.com.ty.lift.system.user.dao.entity.Menu;
import cn.com.ty.lift.system.user.dao.entity.RoleMenu;
import cn.com.ty.lift.system.user.dao.mapper.RoleMenuMapper;
import cn.com.ty.lift.system.user.service.IMenuService;
import cn.com.ty.lift.system.user.service.IRoleMenuService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author huangyuan
 * @date 2019-12-01
 * @description 角色菜单实现类
 */
@Service
public class RoleMenuService extends ServiceImpl<RoleMenuMapper, RoleMenu> implements IRoleMenuService {

    @Resource
    private RoleMenuMapper roleMenuMapper;

    @Resource
    private IMenuService menuService;

    @Override
    public boolean saveRoleMenu(Long roleId, String menuIds) {
        List<RoleMenu> needSaveRoleMenuList = new ArrayList<>();
        List<Long> menuIdList = ProjectUtils.getLongIdFromIds(menuIds);
        if (menuIdList.size() > 0) {
            for (Long menuId : menuIdList) {
                RoleMenu roleMenu = new RoleMenu();
                roleMenu.setRoleId(roleId);
                roleMenu.setMenuId(menuId);
                needSaveRoleMenuList.add(roleMenu);
            }
        }
        if (needSaveRoleMenuList.size() > 0) {
            return this.saveBatch(needSaveRoleMenuList);
        }
        return true;
    }

    @Override
    public int deleteRoleMenu(Long roleId) {
        return roleMenuMapper.deleteByRoleId(roleId);
    }

    @Override
    public List<Menu> getMenuTree(Long roleId) {
        List<RoleMenu> roleMenuList = this.list(new QueryWrapper<RoleMenu>()
                .eq("role_id", roleId)
        );
        if (roleMenuList != null && roleMenuList.size() > 0) {
            List<Long> menuIds = roleMenuList.stream().map(RoleMenu::getMenuId).collect(Collectors.toList());
            if (menuIds.size() > 0) {
                //获取所有菜单
                List<Menu> menuList = (List<Menu>) menuService.listByIds(menuIds);
                //将菜单转化为树
                return menuService.getMenuTree(menuList);
            }
        }
        return null;
    }
}
