package com.ruoyi.common.core.page;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.StringUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 基于mpbatis-plus分页封装的工具类，兼容若依原来的参数
 *
 * @author zhushuyong
 * @date 2021-10-13
 */
public class MpPageUtils {

    private MpPageUtils() {}

    public static Page intPage() {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        String orderByColumn = pageDomain.getOrderByColumn();
        String isAsc = pageDomain.getIsAsc();
        if (StringUtils.isNull(pageNum) || StringUtils.isNull(pageSize)) {
            throw new BaseException("参数不符合规范，不能进行分页查询");
        }
        Page page = new Page((long)pageNum, (long)pageSize);
        String orderBy = StringUtils.toUnderScoreCase(orderByColumn);
        if (StringUtils.isNotEmpty(orderBy))
        {
            List<OrderItem> orderItemList = new ArrayList<>();
            orderItemList.add(isAsc.equals("asc")? OrderItem.asc(orderBy) : OrderItem.desc(orderBy));
            page.setOrders(orderItemList);
        }
        return page;
    }

    public static <T> TableDataInfo<T> copyPage(IPage<T> sourcePage) {
        TableDataInfo<T> tableDataInfo = new TableDataInfo();
        tableDataInfo.setCode(0);
        tableDataInfo.setRows(sourcePage.getRecords());
        tableDataInfo.setTotal(sourcePage.getTotal());
        return tableDataInfo;
    }

    public static <S, T> TableDataInfo<T> copyPage(IPage<S> sourcePage, Class<T> targetClass) {
        if (Objects.isNull(sourcePage)) {
            return null;
        }
        TableDataInfo<T> tableDataInfo = new TableDataInfo();
        tableDataInfo.setCode(0);
        tableDataInfo.setTotal(sourcePage.getTotal());
        if (CollUtil.isNotEmpty(sourcePage.getRecords())) {
            List<T> targetList = sourcePage.getRecords().stream().map(source -> {
                return BeanUtil.copyProperties(source, targetClass);
            }).collect(Collectors.toList());
            tableDataInfo.setRows(targetList);
        }
        return tableDataInfo;
    }

}
