package com.gci.boot.modules.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gci.boot.modules.system.entity.SysDepart;
import com.gci.boot.modules.system.mapper.SysDepartMapper;
import com.gci.boot.modules.system.service.ISysDepartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * <p>
 * 组织机构表 服务实现类
 * </p>
 *
 * @author chenzhiwei
 * @since 2023-08-31
 */
@Service
public class SysDepartServiceImpl extends ServiceImpl<SysDepartMapper, SysDepart> implements ISysDepartService {

    @Autowired
    private SysDepartMapper sysDepartMapper;

    @Override
    public void deleteWithChildren(String id){
        SysDepart depart = getById(id);
        if(depart != null) {
            deleteChildren(depart);
            removeById(depart.getId());
        }
    }

    @Override
    public void deleteBatchWithChildren(List<String> ids){
        List<SysDepart> list = lambdaQuery().in(SysDepart::getId, ids).list();
        if(list.size()>0) {
            list.forEach(d -> deleteChildren(d));
            removeByIds(list.stream().map(SysDepart::getId).collect(Collectors.toList()));
        }
    }

    @Override
    public List<SysDepart> getDepartByUserId(String userId) {
        return sysDepartMapper.getDepartByUserId(userId);
    }

    private void deleteChildren(SysDepart depart){
        if(depart != null){
            List<SysDepart> list = lambdaQuery().eq(SysDepart::getParentId, depart.getId())
                    .list();
            if(list.size()>0) {
                list.forEach(d->deleteChildren(d));
                removeByIds(list.stream().map(SysDepart::getId).collect(Collectors.toList()));
            }
        }
    }
}
