package com.njcn.product.cnuser.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.text.StrPool;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.common.pojo.enums.common.DataStateEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.common.pojo.response.HttpResult;

import com.njcn.product.cnuser.user.mapper.DeptMapper;
import com.njcn.product.cnuser.user.pojo.po.Dept;
import com.njcn.product.cnuser.user.pojo.vo.DeptAllTreeVO;
import com.njcn.product.cnuser.user.service.IDeptService;
import com.njcn.web.factory.PageFactory;
import com.njcn.web.utils.RequestUtil;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestParam;

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

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hongawen
 * @since 2021-12-13
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements IDeptService {






    @Override
    public List<DeptAllTreeVO> loginDeptTree(String deptIndex) {
        List<DeptAllTreeVO> deptList = this.baseMapper.getAllDeptTree(deptIndex, Stream.of(0).collect(Collectors.toList()));
        return deptList.stream()
                .filter(deptVO -> deptVO.getId().equals(deptIndex))
                .peek(deptFirst -> deptFirst.setChildren(getChildrens(deptFirst, deptList)))
                .collect(Collectors.toList());
    }

    /**
     * 递归查找所有部门的下级部门
     */
    private List<DeptAllTreeVO> getChildrens(DeptAllTreeVO deptFirst, List<DeptAllTreeVO> allDept) {
        return allDept.stream().filter(dept -> dept.getPid().equals(deptFirst.getId()))
                .peek(deptVo -> {
                    deptVo.setChildren(getChildrens(deptVo, allDept));
                }).sorted(Comparator.comparing(DeptAllTreeVO::getSort)).collect(Collectors.toList());
    }


}
