package cn.reghao.oss.console.account.db.query;

import cn.reghao.oss.console.account.db.repository.MenuRepository;
import cn.reghao.oss.console.account.model.po.Menu;
import org.springframework.stereotype.Service;

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

/**
 * @author reghao
 * @date 2021-07-12 15:32:26
 */
@Service
public class MenuQueryImpl implements MenuQuery {
    private final MenuRepository menuRepository;

    public MenuQueryImpl(MenuRepository menuRepository) {
        this.menuRepository = menuRepository;
    }

    @Override
    public List<Menu> findAll() {
        return menuRepository.findAll();
    }

    @Override
    public Menu findById(int id) {
        return menuRepository.getOne(id);
    }

    @Override
    public List<Menu> getSortedMenusByStatus(Boolean isEnabled) {
        List<Menu> menuList = menuRepository.findByEnabled(isEnabled);
        Map<Integer, List<Menu>> map =  menuList.stream().collect(Collectors.groupingBy(Menu::getPid));
        List<Menu> list = new ArrayList<>();
        map.forEach((pid, menus) -> {
            list.addAll(menus.stream()
                    .sorted(Comparator.comparing(Menu::getPos))
                    .collect(Collectors.toList()));
        });

        return list;
    }

    @Override
    public Map<Integer, String> getSortedChildGroupByPid(int pid) {
        List<Menu> menus = menuRepository.findByPid(pid);
        menus.sort(Comparator.comparingInt(Menu::getPos));
        Map<Integer, String> map = new HashMap<>();
        menus.forEach(menu -> map.put(menu.getPos(), menu.getName()));
        return map;
    }

    @Override
    public Set<Menu> getMenus(List<Integer> menuIds) {
        return new HashSet<>(menuRepository.findAllById(menuIds));
    }
}
