package com.izouma.zhirongip.service;

import com.izouma.zhirongip.domain.Navigation;
import com.izouma.zhirongip.dto.PageQuery;
import com.izouma.zhirongip.repo.NavigationRepo;
import com.izouma.zhirongip.utils.JpaUtils;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@AllArgsConstructor
public class NavigationService {

    private final NavigationRepo navigationRepo;

    public Page<Navigation> all(PageQuery pageQuery) {
        return navigationRepo.findAll(JpaUtils.toSpecification(pageQuery, Navigation.class), JpaUtils.toPageRequest(pageQuery));
    }

    public List<Navigation> getTree(List<Navigation> list) {

        Map<Long, Navigation> dtoMap = new HashMap<>();
        for (Navigation node : list) {
            dtoMap.put(node.getId(), node);
        }

        List<Navigation> resultList = new ArrayList<>();
        for (Map.Entry<Long, Navigation> entry : dtoMap.entrySet()) {
            Navigation node = entry.getValue();
            if (node.getParent() == null) {
                // 如果是顶层节点，直接添加到结果集合中
                resultList.add(node);
            } else {
                // 如果不是顶层节点，找其父节点，并且添加到父节点的子节点集合中
                if (dtoMap.get(node.getParent()) != null) {
                    dtoMap.get(node.getParent()).getChildren().add(node);
                }
            }
        }
        this.sortMenu(resultList);
        return resultList;
    }

    private void sortMenu(List<Navigation> menus) {
        menus.sort(Comparator.comparingInt(Navigation::getSort));
        for (Navigation menu : menus) {
            if (menu.getChildren() != null) {
                sortMenu(menu.getChildren());
            }
        }
    }

    public List<Navigation> getChildren(Long parent) {
        return navigationRepo.findAllByParent(parent);
    }
}
