package com.izouma.wenlvju.service;

import com.alibaba.fastjson.JSON;
import com.izouma.wenlvju.domain.ArtType;
import com.izouma.wenlvju.domain.Menu;
import com.izouma.wenlvju.dto.ArtTypeDTO;
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 Page<ArtTypeDTO> all2(PageQuery pageQuery) {
//        Map<String, Object> query = pageQuery.getQuery();
//        query.put("level", 3);
//        Page<ArtType> all = artTypeRepo.findAll(JpaUtils.toSpecification(pageQuery, ArtType.class), JpaUtils.toPageRequest(pageQuery));
//        Map<Long, ArtType> artTypeMap = artTypeRepo.findAllByLevelIsNot(3)
//                .stream()
//                .collect(Collectors.toMap(ArtType::getId, artType -> artType));
//        return null;
//    }

    public List<ArtType> getTree(List<?> list1) {
        String s = JSON.toJSONString(list1);
        List<ArtType> list = JSON.parseArray(s, ArtType.class);
        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());
            }
        }
    }
}
