package com.bootdo.datas.service.impl;

import com.bootdo.datas.dao.DataPartDao;
import com.bootdo.datas.domain.DataPartDO;
import com.bootdo.datas.service.DataPartService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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


@Service
public class DataPartServiceImpl implements DataPartService {
	@Autowired
	private DataPartDao dataPartDao;
	
	@Override
	public DataPartDO get(Long partId){
		return dataPartDao.get(partId);
	}
	
	@Override
	public List<DataPartDO> list(Map<String, Object> map){
		return dataPartDao.list(map);
	}
	
	@Override
	public int count(Map<String, Object> map){
		return dataPartDao.count(map);
	}
	
	@Override
	public int save(DataPartDO dataPart){
		return dataPartDao.save(dataPart);
	}

	@Override
	public int update(DataPartDO dataPart) {
		return dataPartDao.update(dataPart);
	}

	@Override
	public int remove(Long partId) {
		// 递归删除
		recursion(partId);
		return dataPartDao.remove(partId);
	}

	/**
	 * 遍历删除父类的子集 子集的子集等
	 *
	 * @param partId
	 */
	private void recursion(Long partId) {
		Map<String, Object> map = new HashMap<>(3);
		map.put("parentId", partId);
		List<DataPartDO> list = list(map);
		List<Long> collect = list.stream().map(DataPartDO::getPartId).collect(Collectors.toList());
		if (CollectionUtils.isNotEmpty(collect)) {
			this.batchRemove(collect.toArray(new Long[collect.size()]));
			for (Long aLong : collect) {
				recursion(aLong);
			}
		}
	}
	
	@Override
	public int batchRemove(Long[] partIds){
		return dataPartDao.batchRemove(partIds);
	}
	
}
