package com.tuoheng.miniprogram.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tuoheng.common.core.utils.JsonResult;
import com.tuoheng.miniprogram.dao.DeptMapper;
import com.tuoheng.miniprogram.entity.Dept;
import com.tuoheng.miniprogram.service.IDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * @Author ChengWang
 * @Date 2022/11/21
 */
@Service
public class DeptServiceImpl implements IDeptService {

    @Autowired
    private DeptMapper deptMapper;

    /**
     * 获取部门列表(树形)
     * @return
     */
    @Override
    public JsonResult treeList() {
        List<Dept> list = deptMapper.selectList(new LambdaQueryWrapper<Dept>()
                .eq(Dept::getMark, 1));
        // 获取所有一级节点
        //预设id值为2
        List<Dept> result = list.stream().
                filter(dept -> dept.getPid().equals("1"))
                .peek(dept -> dept.setItemList(getChildren(dept, list))).sorted(Comparator.comparingInt(dept -> (dept.getSort() == null ? 0 : dept.getSort())))
                .collect(Collectors.toList());
        return JsonResult.success(result);
//        List<Dept> deptList = new ArrayList<>();
//        List<Dept> deptTreeVoList = new ArrayList<>();
//        Map<String, Dept> deptVoMap = new HashMap<>();
//        for (Dept dept : list) {
//            deptVoMap.put(dept.getId(),dept);
//        }
//        for (Dept dept : list) {
//            Dept child = dept;
//            if("0".equals(child.getPid())){
//                deptTreeVoList.add(dept);
//            }else {
//                Dept parent = deptVoMap.get(child.getPid());
//                parent.getItemList().add(child);
//            }
//        }
//        return JsonResult.success(deptTreeVoList);
        }

    @Override
    public JsonResult test(String id) {
        List<String> list = deptMapper.selectAllChildListById(id);

        return JsonResult.success(list);
    }


    /**
     * 递归获取部门的子集
     *
     * @author zhu_zishuang
     * @date 3/13/21
     */
    private List<Dept> getChildren(Dept rootDept, List<Dept> list) {
        return list.stream().filter(dept ->
                dept.getPid().equals(rootDept.getId())
        ).peek(dept -> {
            // 设置子集
            dept.setItemList(getChildren(dept, list));
        }).sorted(Comparator.comparingInt(dept -> (dept.getSort() == null ? 0 : dept.getSort()))).collect(Collectors.toList());
    }
}
