package com.izouma.uwip.service;

import com.izouma.uwip.domain.Docking;
import com.izouma.uwip.dto.PageQuery;
import com.izouma.uwip.exception.BusinessException;
import com.izouma.uwip.repo.DockingRepo;
import com.izouma.uwip.utils.JpaUtils;
import com.izouma.uwip.utils.ObjUtils;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@AllArgsConstructor
public class DockingService {

    private final DockingRepo dockingRepo;

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

    public void batchSave(List<Docking> dockingList) {
        dockingList.forEach(docking -> {
            if (docking.getId() != null) {
                Docking record = dockingRepo.findById(docking.getId()).orElseThrow(new BusinessException("无记录"));
                ObjUtils.merge(record, docking);
                dockingRepo.save(record);
            } else {
                dockingRepo.save(docking);
            }
        });
    }
}
