package cn.reghao.oss.console.account.service;

import cn.reghao.oss.console.account.db.query.RoleQuery;
import cn.reghao.oss.console.account.model.po.Menu;
import cn.reghao.oss.console.account.model.po.Role;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author reghao
 * @date 2021-04-04 23:36:10
 */
@Service
public class HomeService {
    private final RoleQuery roleQuery;

    public HomeService(RoleQuery roleQuery) {
        this.roleQuery = roleQuery;
    }

    /**
     * 用户拥有的角色可访问的资源
     *
     * @param
     * @return
     * @date 2021-09-10 下午6:27
     */
    public List<Menu> userMenus(Set<String> roles) {
        List<Menu> menus = new ArrayList<>();
        roles.forEach(name -> {
            Role role = roleQuery.findByName(name);
            menus.addAll(role.getMenus().stream().filter(Menu::getEnabled).collect(Collectors.toSet()));
        });

        return menus;
    }

    /**
     * 根据 menu 集合生成页面侧边栏的树形菜单
     *
     * @param
     * @return
     * @date 2021-09-10 下午6:24
     */
    public Map<Integer, Menu> treeMenu(List<Menu> menus) {
        // id -> menu
        Map<Integer, Menu> keyMenu = new HashMap<>(16);
        menus.forEach(menu -> keyMenu.put(menu.getId(), menu));

        // 树形菜单数据
        Map<Integer, Menu> treeMenu = new HashMap<>(16);
        keyMenu.forEach((id, menu) -> {
            Menu parentMenu = keyMenu.get(menu.getPid());
            if (parentMenu != null) {
                Map<Integer, Menu> childMenus = parentMenu.getChildren();
                if (childMenus == null) {
                    childMenus = new HashMap<>();
                    parentMenu.setChildren(childMenus);
                }
                childMenus.put(menu.getPos(), menu);
            } else {
                treeMenu.put(menu.getPos(), menu);
            }
        });

        return treeMenu;
    }
}
