package com.izouma.wenlvju.service.regulation;

import cn.hutool.core.util.ObjectUtil;
import com.izouma.wenlvju.domain.regulation.RecordExpertAudit;
import com.izouma.wenlvju.dto.PageQuery;
import com.izouma.wenlvju.exception.BusinessException;
import com.izouma.wenlvju.repo.regulation.RecordExpertAuditRepo;
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 RecordExpertAuditService {

    private RecordExpertAuditRepo recordExpertAuditRepo;

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

    public void batchSave(List<RecordExpertAudit> audits) {
        audits.forEach(record -> {
            if (record.getId() != null) {
                RecordExpertAudit orig = recordExpertAuditRepo.findById(record.getId())
                        .orElseThrow(new BusinessException("无记录"));
                ObjUtils.merge(orig, record);
                recordExpertAuditRepo.save(orig);
            } else {
                RecordExpertAudit orig = recordExpertAuditRepo.findByRecordIdAndType(record.getRecordId(), record.getType());
                if (ObjectUtil.isNotNull(orig)) {
                    ObjUtils.merge(orig, record);
                    recordExpertAuditRepo.save(orig);
                } else {
                    recordExpertAuditRepo.save(record);
                }

            }
        });
    }
}
