package com.supServer.project.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.supServer.framework.web.domain.AjaxResult;
import com.supServer.project.entity.BizCategory;
import com.supServer.project.entity.vo.BizCategoryVo;
import com.supServer.project.mapper.BizCategoryMapper;
import com.supServer.project.service.BizCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigInteger;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class BizCategoryServiceImpl implements BizCategoryService {

    @Autowired
    private BizCategoryMapper bizCategoryMapper;


    @Override
    public AjaxResult listTree(BizCategoryVo vo) {
        List<BizCategory> list=bizCategoryMapper.listTree(vo);
        if (CollectionUtil.isEmpty(list)) {
            return AjaxResult.success(list);
        }
        // 2 组装成父子的树形结构
        List<BizCategory> level1Menus = list.stream().filter(bizCategory ->
                bizCategory.getParentCode().equals(BigInteger.ZERO)
        ).map((menu) -> {
            menu.setChildren(getChildrens(menu, list));
            return menu;
        }).collect(Collectors.toList());
        return AjaxResult.success(level1Menus);
    }


    /**
     * 递归查找所有菜单的子菜单
     *
     * @param root
     * @param all
     * @return
     */
    private List<BizCategory> getChildrens (BizCategory root, List<BizCategory> all) {
        List<BizCategory> children = all.stream().filter(bizCategory -> {
            return bizCategory.getParentCode().equals(root.getCode());
        }).map(bizCategory -> {
            // 1 找到子菜单
            bizCategory.setChildren(getChildrens(bizCategory, all));
            return bizCategory;
        }).collect(Collectors.toList());
        return children;
    }
}
