package com.njcn.db.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.db.mapper.BatchBaseMapper;
import com.njcn.db.service.IReplenishMybatisService;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * @author hongawen
 * @version 1.0.0
 * @date 2023年06月06日 18:16
 */
public 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) {
        try {
            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);
            }
        } catch (Exception e) {
            throw new RuntimeException("分片批量插入数据异常，异常为：" + e);
        }
    }
}
