package com.platform.utils;

import com.alibaba.fastjson.JSON;
import com.platform.entity.SysDeptEntity;
import com.platform.service.impl.SysDeptServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author abnerhou
 * @date 2020/10/12 17:08
 * @desciption
 */
@Service
@Slf4j
public class DepartmentUtils {

    @Autowired
    private SysDeptServiceImpl sysDeptService;


    public List<Long> getAllSubDeptIds(Long deptId) {
        if (null == deptId) {
            log.info("部门ID为空");
            return new ArrayList<>();
        }
        List<Long> allDeptIdList = new ArrayList<>();
        int leve = 0;
        leve = findDeptIdByParent(deptId, 0, allDeptIdList);
        log.info("获取到当前部门以及所有子部门(10层嵌套以内)的id为:{}，部门层级为:{}",
                JSON.toJSONString(allDeptIdList) , leve);
        return allDeptIdList;
    }

    private int findDeptIdByParent(long deptId, int level, List<Long> deptIdList) {

        if (level > 10) {
            log.info("嵌套层数超过了10层");
            return level;
        }
        deptIdList.add(deptId);
        //获取所有子部门的id
        List<Long> subDeptIdList = sysDeptService.queryDetpIdList(deptId);
        if (CollectionUtils.isEmpty(subDeptIdList)) {
            //自己算一层，没有子部门，要先加上自己这一层
            return level + 1;
        }
        int maxLevel = 0;
        for(Long id : subDeptIdList){
            //遍历所有子部门的子部门，并记下子部门中嵌套最深的层数
            int tmpLevel = findDeptIdByParent(id, level, deptIdList);
            if(tmpLevel > maxLevel){
                maxLevel = tmpLevel;
            }
        }
        //添加子部门的id
        deptIdList.addAll(subDeptIdList);
        //叠加子部门的最大层级
        level += maxLevel;
        //加上自己这一层
        level += 1;
        return level;
    }
}
