package com.njcn.oracle.mybatis.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.oracle.mybatis.mapper.BatchBaseMapper;
import com.njcn.oracle.mybatis.service.IReplenishMybatisService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StopWatch;

import java.util.ArrayList;
import java.util.List;

/**
 * @author hongawen
 * @version 1.0.0
 * @date 2023年06月06日 18:16
 */
@Service
public abstract class ReplenishMybatisServiceImpl<M extends BatchBaseMapper<T>, T> extends ServiceImpl<BatchBaseMapper<T>, T> implements IReplenishMybatisService<T> {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertBatchBySlice(List<T> data, int size) throws RuntimeException{
        int totalCount = data.size();
        int idxLimit = Math.min(size, totalCount);
        List<T> dataTemp = new ArrayList<>(data);
        //保存单批提交的数据集合
        if (idxLimit == size) {
            int times = totalCount / idxLimit + 1;
            for (int i = 1; i <= times; i++) {
                if (totalCount >= idxLimit) {
                    List<T> temp = dataTemp.subList(0, idxLimit);
                    this.baseMapper.insertBatchSomeColumn(temp);
                    temp.clear();
                    totalCount = totalCount - idxLimit;
                } else {
                    if (CollectionUtil.isNotEmpty(dataTemp)) {
                        this.baseMapper.insertBatchSomeColumn(dataTemp);
                    }
                }
            }
        } else {
            this.baseMapper.insertBatchSomeColumn(dataTemp);
        }
        System.gc();

    }


}
