package com.izouma.wenlvju.service;

import com.izouma.wenlvju.domain.Collaborate;
import com.izouma.wenlvju.dto.PageQuery;
import com.izouma.wenlvju.exception.BusinessException;
import com.izouma.wenlvju.repo.CollaborateRepo;
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 CollaborateService {

    private CollaborateRepo collaborateRepo;

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

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