package com.inkasso.factoring.system.department.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.inkasso.factoring.system.department.dao.DepartmentMapper;
import com.inkasso.factoring.system.department.entity.Department;
import com.inkasso.factoring.system.department.service.IDepartmentService;
import com.inkasso.factoring.system.department.vo.DepartmentVo;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description :
 * @Author : L.Jia
 * @Date: 2024-01-23 11:51
 */

@Service
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements IDepartmentService {


    /**
     * 是排除区县级
     * @param flag
     * @return
     */
    @Override
    public List<DepartmentVo> findAll(Boolean flag) {
        //查询省
        List<Department> provinceList = list(new QueryWrapper<Department>().eq("parent_id", 1L));

        List<DepartmentVo> result = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(provinceList)) {
            provinceList.stream().forEach(province -> {
                DepartmentVo vo = new DepartmentVo(province);
                List<Department> cityList = list(new QueryWrapper<Department>().eq("parent_id", province.getId()));
                List<DepartmentVo> childrenList = cityList.stream().map(city -> new DepartmentVo(city)).collect(Collectors.toList());

                childrenList.stream().forEach(city -> {
                    List<Department> districtList = list(new QueryWrapper<Department>().eq("parent_id", city.getId()));
                    if(!(flag!=null && flag)){
                        List<DepartmentVo> childrenList1 = districtList.stream().map(district -> new DepartmentVo(district)).collect(Collectors.toList());
                        city.setChildren(childrenList1);
                    }
                });
                vo.setChildren(childrenList);
                result.add(vo);
            });
        }
        return result;
    }
}
