package com.izouma.wenlvju.service.performance;

import com.izouma.wenlvju.domain.performance.PerformanceSchedule;
import com.izouma.wenlvju.dto.PageQuery;
import com.izouma.wenlvju.exception.BusinessException;
import com.izouma.wenlvju.repo.performance.PerformanceScheduleRepo;
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 PerformanceScheduleService {

    private PerformanceScheduleRepo performanceScheduleRepo;

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

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