package com.tofly.qualitycontrol.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.tofly.qualitycontrol.common.QualityControlConstant;
import com.tofly.qualitycontrol.entity.PlanAuditor;
import com.tofly.qualitycontrol.entity.PlanProcess;
import com.tofly.qualitycontrol.exception.QualityControlBusinessException;
import com.tofly.qualitycontrol.mapper.PlanAuditorMapper;
import com.tofly.qualitycontrol.service.IPlanAuditorService;
import com.tofly.qualitycontrol.vo.PlanAuditHistoryVO;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

import static com.tofly.qualitycontrol.util.QualityControlUtil.getVO;

/**
 * @author B
 */
@Service
@RequiredArgsConstructor
public class PlanAuditorServiceImpl extends ServiceImpl<PlanAuditorMapper,PlanAuditor> implements IPlanAuditorService, QualityControlConstant {

	@Override
	public Integer getMaxLevel(Long id) {
		return baseMapper.getMaxLevel(id);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean insertBatch(List<PlanAuditor> planAuditorList) {
		Long currentId = baseMapper.getCurrentId();

		if (CollectionUtils.isEmpty(planAuditorList)) {
			throw new QualityControlBusinessException("审核人员信息不能为空");
		}
		int size = planAuditorList.size();

		for (PlanAuditor planAuditor : planAuditorList) {
			planAuditor.setId(currentId++);
		}

		Boolean flag1 = true;

		if (size <= 500) {
			flag1 = baseMapper.insertBatch(planAuditorList);

		} else {
			int times = (int) Math.ceil(size / 500.0);

			for (int i = 0;i < times;i++) {
				Boolean flag2 = baseMapper.insertBatch(planAuditorList.subList(i * 500,Math.min((i + 1) * 500,size)));

				if (!flag2) {
					throw new QualityControlBusinessException("批量添加失败");
				}
			}
		}
		return flag1;
	}

	@Override
	public List<PlanAuditHistoryVO> getExamine(Long id) {
		List<PlanAuditor> list = list(Wrappers.<PlanAuditor>lambdaQuery().eq(PlanAuditor::getPlanId,id).orderByAsc(PlanAuditor::getId));
		List<PlanAuditHistoryVO> voList = Lists.newArrayList();
		if (CollectionUtils.isNotEmpty(list)) {
			list.forEach(l -> voList.add(getVO(l,PlanAuditHistoryVO.class)));
		}
		return voList;
	}

}
