package com.ningdatech.carapi.sys.manage;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ningdatech.basic.util.CollUtils;
import com.ningdatech.carapi.sys.entity.Menu;
import com.ningdatech.carapi.sys.entity.RoleMenu;
import com.ningdatech.carapi.sys.entity.vo.MenuRoleVO;
import com.ningdatech.carapi.sys.service.IRoleMenuService;
import com.ningdatech.carapi.sys.utils.TreeUtil;
import com.ningdatech.carapi.user.security.auth.model.UserInfoDetails;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @Classname MenuManage
 * @Description
 * @Date 2022/11/12 11:26
 * @Created by PoffyZhang
 */
@Component
@RequiredArgsConstructor
public class MenuManage {
    private final IRoleMenuService roleMenuService;

    public List<MenuRoleVO> buildUserMenu(List<Menu> list, UserInfoDetails loginUser) {
        if (Objects.isNull(loginUser) || Objects.isNull(loginUser.getRoleId())) {
            return Collections.emptyList();
        }
        //查出当前用户的角色菜单
        List<RoleMenu> roleMenus = roleMenuService.list(Wrappers.lambdaQuery(RoleMenu.class).eq(RoleMenu::getRoleId, loginUser.getRoleId()));
        //单一用户 menuId应该是唯一的 可以做成map
        Map<Long,RoleMenu> roleMenuMap = CollUtils.listToMap(roleMenus,r -> r.getMenuId());
        List<MenuRoleVO> menuRoles = CollUtils.convert(list, w -> BeanUtil.copyProperties(w, MenuRoleVO.class));
        return TreeUtil.buildUserTree(menuRoles, roleMenuMap);
    }
}
