package com.izouma.wenlvju.service;

import com.alibaba.fastjson.JSON;
import com.izouma.wenlvju.domain.ArtType;
import com.izouma.wenlvju.domain.Setting;
import com.izouma.wenlvju.dto.PageQuery;
import com.izouma.wenlvju.repo.SettingRepo;
import com.izouma.wenlvju.utils.JpaUtils;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@AllArgsConstructor
public class SettingService {

    private SettingRepo settingRepo;

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

    public List<Setting> getTree(List<?> list1) {
        String s = JSON.toJSONString(list1);
        List<Setting> list = JSON.parseArray(s, Setting.class);
        Map<Long, Setting> dtoMap = new HashMap<>();
        for (Setting node : list) {
            dtoMap.put(node.getId(), node);
        }

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

}
