package com.izouma.wenlvju.service.performance;

import com.izouma.wenlvju.domain.performance.Participant;
import com.izouma.wenlvju.dto.PageQuery;
import com.izouma.wenlvju.exception.BusinessException;
import com.izouma.wenlvju.repo.performance.ParticipantRepo;
import com.izouma.wenlvju.utils.JpaUtils;
import com.izouma.wenlvju.utils.ObjUtils;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@AllArgsConstructor
public class ParticipantService {

    private ParticipantRepo participantRepo;

    public Page<Participant> all(PageQuery pageQuery) {
        return participantRepo.findAll(JpaUtils.toSpecification(pageQuery, Participant.class), JpaUtils.toPageRequest(pageQuery));
    }

    public void batchSave(List<Participant> participants) {
        participants.forEach(participant -> {
            if (participant.getId() != null) {
                Participant orig = participantRepo.findById(participant.getId())
                        .orElseThrow(new BusinessException("无记录"));
                ObjUtils.merge(orig, participant);
                participantRepo.save(orig);
            } else {
                participantRepo.save(participant);
            }
        });
    }
}
