package com.cool.store.vo.menu;

import com.cool.store.entity.SysMenuDO;
import com.cool.store.enums.MenuTypeEnum;
import com.google.common.collect.Lists;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.ListUtils;

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

/**
 * describe:
 *
 * @author zhouyiping
 * @date 2020/09/22
 */
@Data
public class MenuAuthTreeVO {

    @ApiModelProperty("请求地址(前端路由)")
    private String path;

    @ApiModelProperty("菜单编号")
    private String code;

    @ApiModelProperty("菜单名称")
    private String name;

    @ApiModelProperty("菜单id")
    private Long id;

    @ApiModelProperty("父级菜单")
    private Long parentId;

    @ApiModelProperty("图标'")
    private String icon;

    @ApiModelProperty("菜单类型 1菜单 2权限")
    private Integer menuType;

    @ApiModelProperty("子菜单")
    private List<MenuAuthTreeVO> children;

    public static List<MenuAuthTreeVO> dealMenuTree(Long rootId, List<SysMenuDO> menuList) {
        if(CollectionUtils.isEmpty(menuList)){
            return Lists.newArrayList();
        }
        Map<Long, List<SysMenuDO>> parentGroup = ListUtils.emptyIfNull(menuList).stream().collect(Collectors.groupingBy(SysMenuDO::getParentId));
        List<SysMenuDO> menuDOList = parentGroup.get(rootId);
        if (CollectionUtils.isEmpty(menuDOList)) {
            return Collections.emptyList();
        }
        List<MenuAuthTreeVO> voList = convertVO(menuDOList);
        List<MenuAuthTreeVO> treeVOList = new LinkedList<>(voList);
        for (MenuAuthTreeVO data : treeVOList) {
            getChild(data, parentGroup);
        }
        return treeVOList;
    }

    public static List<MenuAuthTreeVO> convertVO(List<SysMenuDO> menuList) {
        menuList = menuList.stream().sorted(Comparator.comparing(SysMenuDO::getSort)).collect(Collectors.toList());
        List<MenuAuthTreeVO> resultList = new ArrayList<>();
        for (SysMenuDO menu : menuList) {
            MenuAuthTreeVO vo = new MenuAuthTreeVO();
            vo.setId(menu.getId());
            vo.setParentId(menu.getParentId());
            vo.setName(menu.getName());
            vo.setCode(menu.getCode());
            vo.setPath(menu.getPath());
            vo.setIcon(menu.getIcon());
            vo.setMenuType(menu.getMenuType());
            resultList.add(vo);
        }
        return resultList;
    }

    public static void getChild(MenuAuthTreeVO data, Map<Long, List<SysMenuDO>> parentGroup) {
        List<SysMenuDO> menuList = parentGroup.get(data.getId());
        //属于菜单下时候
        if (CollectionUtils.isNotEmpty(menuList)) {
            List<MenuAuthTreeVO> voList = convertVO(menuList);
            data.setChildren(voList);
            voList.forEach(child -> {
                getChild(child, parentGroup);
            });
        }
    }

}
