package cn.cecep.talroad.util;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import javax.validation.constraints.NotNull;
import java.util.Collections;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @ClassName PageConvertUtil
 * @Description
 * @Author liyongbing
 * @Date 2023/5/11 15:45
 * @Version 1.0
 **/
public class PageConvertUtil {


	public static <R, P> Page<R> pagConvert(IPage<P> page, Class<R> rClass) {
		return pagConvert(page, e -> BeanUtil.copyProperties(e, rClass));
	}

	public static <R, P> Page<R> pagConvert(@NotNull IPage<P> page, @NotNull Function<P, R> mapFunction) {
		return new Page<R>()
			.setCurrent(page.getCurrent())
			.setSize(page.getSize())
			.setTotal(page.getTotal())
			.setRecords(Optional
				.ofNullable(page.getRecords())
				.orElse(Collections.emptyList())
				.stream()
				.map(mapFunction)
				.collect(Collectors.toList())
			)
			;
	}
}
