package com.supServer.project.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
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.apache.commons.lang3.StringUtils;
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> res;
        List<BizCategory> list = CollUtil.newArrayList();
        if (ObjectUtil.isNull(vo) || StringUtils.isBlank(vo.getName())){
            List<BizCategory> bizCategories = bizCategoryMapper.listTree(vo);
            list.addAll(bizCategories);
        }else {
            //一级目录
            List<BizCategory> oneLevels = bizCategoryMapper.oneLevels(vo);
            if(CollUtil.isNotEmpty(oneLevels)){
                list.addAll(oneLevels);
                //一级目录id集合
                List<BigInteger> oneCodes = oneLevels.stream().map(BizCategory::getCode).distinct().collect(Collectors.toList());
                //根据一级目录id集合 查找二级目录
                List<BizCategory> twoLevels = bizCategoryMapper.twoLevels(oneCodes);
                if (CollUtil.isNotEmpty(twoLevels)){
                    list.addAll(twoLevels);
                    //二级目录id集合
                    List<BigInteger> twoCodes = twoLevels.stream().map(BizCategory::getCode).distinct().collect(Collectors.toList());
                    //三级目录
                    List<BizCategory> threeLevels = bizCategoryMapper.twoLevels(twoCodes);
                    if (CollUtil.isNotEmpty(threeLevels)) list.addAll(threeLevels);
                }

            }
        }
        //配置
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        // 自定义属性名 都要默认值的
        treeNodeConfig.setIdKey("code");
        treeNodeConfig.setParentIdKey("parentCode");
        treeNodeConfig.setWeightKey("level");
        treeNodeConfig.setNameKey("name");
        treeNodeConfig.setChildrenKey("children");
        //转换器
        List<Tree<String>> treeNodes = TreeUtil.build(list, "0", treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId(treeNode.getCode().toString());
                    tree.setParentId(treeNode.getParentCode().toString());
                    tree.setWeight(treeNode.getLevel());
                    tree.setName(treeNode.getName());
                    tree.putExtra("showStatus",treeNode.getShowStatus());
                    tree.putExtra("catId",treeNode.getCatId());
                    tree.putExtra("sort",treeNode.getSort());
                    tree.putExtra("mark",treeNode.getMark());
                    tree.putExtra("userId",treeNode.getUserId());
                    tree.putExtra("createTime",treeNode.getCreateTime());
                    tree.putExtra("updateTime",treeNode.getUpdateTime());
                    tree.putExtra("userName",treeNode.getUserName());
                });
        String jsonStr = JSONUtil.toJsonStr(treeNodes);
        JSONArray jsonArray = JSONUtil.parseArray(jsonStr);
        res =  JSONUtil.toList(jsonArray, BizCategory.class);
        return AjaxResult.success(res);

//        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;
    }
}
