package cn.reghao.autodop.dmaster.rbac.service;

import cn.reghao.autodop.dmaster.rbac.db.query.RoleQuery;
import cn.reghao.autodop.dmaster.rbac.model.po.Menu;
import cn.reghao.autodop.dmaster.rbac.model.po.Role;
import org.springframework.stereotype.Service;

import java.util.*;

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

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

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

        return menus;
    }

    /**
     * 根据 menu 集合生成页面侧边栏的树形菜单
     *
     * @param
     * @return
     * @date 2021-09-10 下午6:24
     */
    @Override
    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;
    }
}
