package com.izouma.wenlvju.service;

import cn.hutool.core.collection.CollUtil;
import com.izouma.wenlvju.domain.ArtType;
import com.izouma.wenlvju.dto.PageQuery;
import com.izouma.wenlvju.repo.ArtTypeRepo;
import com.izouma.wenlvju.utils.JpaUtils;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

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

@Service
@AllArgsConstructor
public class ArtTypeService {

    private ArtTypeRepo artTypeRepo;

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

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

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

    private void sortMenu(List<ArtType> menus) {
        menus.sort(Comparator.comparing(ArtType::getCode));
        for (ArtType menu : menus) {
            if (menu.getChildren() != null) {
                sortMenu(menu.getChildren());
            }
        }
    }

    public List<Long> getIds(List<ArtType> artTypes, String code) {
        return artTypes.stream()
                .filter(at -> at.getCode().startsWith(code))
                .map(ArtType::getId)
                .collect(Collectors.toList());
    }

    public List<Long> getChild(List<Long> id, List<Long> result) {
        List<Long> list = artTypeRepo.findAllByParentIn(id)
                .stream()
                .map(ArtType::getId)
                .collect(Collectors.toList());
        if (CollUtil.isNotEmpty(list)) {
            result.addAll(list);
            this.getChild(list, result);

        }
        return result;
    }
}
