package com.njcn.product.system.dept.service.impl;


import cn.hutool.core.text.StrPool;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.product.system.dept.mapper.DeptMapper;
import com.njcn.product.system.dept.pojo.dto.DeptDTO;
import com.njcn.product.system.dept.pojo.po.Dept;
import com.njcn.product.system.dept.pojo.vo.DeptTreeVO;
import com.njcn.product.system.dept.service.IDeptService;
import com.njcn.web.utils.RequestUtil;
import com.njcn.web.utils.WebUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

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<DeptDTO> getDeptDescendantIndexes(String id, List<Integer> type) {
        return this.baseMapper.getDeptDescendantIndexes(id, type);
    }

    @Override
    public List<DeptTreeVO> deptTree() {
        List<Integer> deptType = WebUtil.filterDeptType();
        String deptIndex = RequestUtil.getDeptIndex();
        List<DeptTreeVO> deptList = this.baseMapper.getDeptTree(deptIndex, deptType);
        return deptList.stream()
                .filter(deptVO -> deptVO.getId().equals(deptIndex))
                .peek(deptFirst -> {
                    if (!Objects.isNull(deptFirst.getPid())) {
                        deptFirst.setLevel(deptFirst.getPids().split(StrPool.COMMA).length - 1);
                    }
                    deptFirst.setChildren(getChildren(deptFirst, deptList));
                })
                .collect(Collectors.toList());
    }
    private List<DeptTreeVO> getChildren(DeptTreeVO deptFirst, List<DeptTreeVO> allDept) {
        return allDept.stream().filter(dept -> dept.getPid().equals(deptFirst.getId()))
                .peek(deptVo -> {
                    if (!Objects.isNull(deptVo.getPids())) {
                        deptVo.setLevel(deptVo.getPids().split(",").length - 1);
                    }
                    deptVo.setChildren(getChildren(deptVo, allDept));
                    if (deptVo.getType() == 0) {
                        deptVo.setName(deptVo.getAreaName());
                    }
                }).sorted(Comparator.comparing(DeptTreeVO::getSort)).collect(Collectors.toList());
    }


}
