package com.hdkj.lt.job.util;

import org.apache.commons.lang3.ObjectUtils;

import java.util.List;
import java.util.Optional;
import java.util.function.Function;

/**
 * @Description
 * @Author wcx
 * @Date 2025/7/30 16:32
 * @Version 1.0
 */
public class JobUtils {
    /**
     * 批量处理集合数据
     */
    public static <T, R> void saveBatchData(List<T> list, Integer size,Function<List<T>, R> function) {
        Integer batchSize = Optional.ofNullable(size).orElse(2000); // 分批次处理, 每次处理2000
        if (ObjectUtils.isNotEmpty(list)) {
            Integer totalSize = list.size(); // 批量处理总数量
            Integer length = (totalSize + batchSize - 1) / batchSize; // 批量处理次数
            for (int i = 0; i < length; i++) {
                Integer startIndex = i * batchSize;
                Integer endIndex = Math.min((i + 1) * batchSize, totalSize);
                List<T> saveList = list.subList(startIndex, endIndex);
                if (ObjectUtils.isNotEmpty(saveList)) {
                    function.apply(saveList);
                }
            }
        }
    }
}
