package com.luojia_channel.common.utils;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.luojia_channel.common.domain.page.PageRequest;
import com.luojia_channel.common.domain.page.PageResponse;

import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

public class PageUtil {
    public static <R,T> PageResponse<R> convert(IPage<T> page, Function<? super T,? extends R> mapper) {
        List<R> targetList = page.getRecords().stream()
                .map(mapper)
                .collect(Collectors.toList());
        return PageResponse.<R>builder()
                .current(page.getCurrent())
                .size(page.getSize())
                .records(targetList)
                .total(page.getTotal())
                .build();
    }

    public static <R,T> PageResponse<R> convert(IPage<T> page, Class<R> clazz) {
        List<R> targetList = page.getRecords().stream()
                .map(each -> BeanUtil.copyProperties(each, clazz))
                .collect(Collectors.toList());
        return PageResponse.<R>builder()
                .current(page.getCurrent())
                .size(page.getSize())
                .records(targetList)
                .total(page.getTotal())
                .build();
    }

    public static Page convert(PageRequest request){
        return new Page(request.getCurrent(), request.getSize());
    }
}
