package thyyxxk.webserver.utils;

import cn.hutool.extra.spring.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.ListUtils;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.batch.MyBatisBatchItemWriter;

import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Consumer;

/**
 * <p>
 * 描述： 判断list
 * </p>
 *
 * @author xc
 * @date 2021-09-18 09:10
 */
@Slf4j
public class ListUtil {
    public static boolean isBlank(List<?> list) {
        return list == null || list.isEmpty();
    }

    public static boolean notBlank(List<?> list) {
        return !isBlank(list);
    }

    public static <T> void partitionAndFunc(List<T> list, int size, Consumer<List<T>> a) {
        List<List<T>> list1 = ListUtils.partition(list, size);
        for (List<T> ts : list1) {
            a.accept(ts);
        }
    }

    public static <T> void partitionAndFunc(List<T> list, Consumer<List<T>> a) {
        partitionAndFunc(list, 20, a);
    }

    public static <M, T> void batchList(List<T> list, Class<M> clazz, BiConsumer<M, T> biConsumer) {
        SqlSessionFactory sqlSessionFactory = SpringUtil.getBean(SqlSessionFactory.class);
        SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH);
        M mapper = session.getMapper(clazz);
        List<List<T>> partitionList = ListUtils.partition(list, 20);
        try {
            for (List<T> ts : partitionList) {
                for (T t : ts) {
                    biConsumer.accept(mapper, t);
                }
                session.commit();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            session.close();
        }
    }

}
