package com.izouma.wenlvju.service.regulation;

import com.izouma.wenlvju.domain.regulation.RecordCheck;
import com.izouma.wenlvju.dto.PageQuery;
import com.izouma.wenlvju.exception.BusinessException;
import com.izouma.wenlvju.repo.regulation.RecordCheckRepo;
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 RecordCheckService {

    private RecordCheckRepo recordCheckRepo;

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

    public void batchSave(List<RecordCheck> checkList, Long userId) {
        checkList.forEach(check -> {
            if (check.getId() != null) {
                RecordCheck orig = recordCheckRepo.findById(check.getId())
                        .orElseThrow(new BusinessException("无记录"));
                ObjUtils.merge(orig, check);
                recordCheckRepo.save(orig);
            } else {
                check.setUserId(userId);
                recordCheckRepo.save(check);
            }
        });
    }
}
