package cn.fateverse.admin;

import cn.fateverse.admin.entity.Menu;
import cn.fateverse.admin.mapper.BackMenuMapper;
import cn.fateverse.common.core.utils.convert.TreeUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import lombok.Data;
import org.junit.jupiter.api.Test;
import org.springframework.beans.BeanUtils;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Clay
 * @date 2024/2/19 14:10
 */
@SpringBootTest(classes = AdminApplication.class)
public class ApplicationTest {

    @Resource
    private BackMenuMapper backMenuMapper;

    private Long d = 1L;
    private Long m = 100L;
    private Long b = 1000L;

    private List<Menu> backList = new ArrayList<>();


    @Test
    public void test() {
        List<Menu> menuList = backMenuMapper.selectAll();
        System.out.println(menuList.size());
//        List<MenuBack> menuBackList = TreeUtil.build(menuList, MenuBack.class, (config) -> {
//            config.setIdField("menuId");
//        });
        Map<Long, List<Menu>> listMap = menuList.stream().collect(Collectors.groupingBy(Menu::getParentId));

        getChildren(listMap, 0L, 0L);


        System.out.println(backList.size());
        for (Menu menu : backList) {
            backMenuMapper.insert(menu);
        }
    }


    private void getChildren(Map<Long, List<Menu>> listMap, Long parentId, Long newParentId) {
        if (!listMap.containsKey(parentId)) {
            return;
        }
        List<Menu> collect = listMap.get(parentId).stream()
                .filter(Objects::nonNull)
                .sorted(Comparator.comparing(menu -> {
                    if (null == menu.getOrderNum()) {
                        return 0;
                    } else {
                        return Convert.toInt(menu.getOrderNum());
                    }
                })).collect(Collectors.toList());
        collect
                .forEach(menu -> {
                    Menu newMenu = new Menu();
                    BeanUtils.copyProperties(menu, newMenu);
                    switch (newMenu.getMenuType()) {
                        case "D":
                            newMenu.setMenuId(d++);
                            break;
                        case "M":
                            newMenu.setMenuId(m++);
                            break;
                        case "B":
                            newMenu.setPath(null);
                            newMenu.setMenuId(b++);
                            break;
                    }
                    newMenu.setParentId(newParentId);
                    backList.add(newMenu);
                    getChildren(listMap, menu.getMenuId(), newMenu.getMenuId());
                });
    }



}
