package com.njzscloud.common.mp.support;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;

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

/**
 * 分页参数
 */
@Getter
@Setter
@Accessors(chain = true)
public final class PageParam {
    /**
     * 每页显示条数，默认 500
     */
    private Integer size;

    /**
     * 当前页，默认 1
     */
    private Integer current;

    /**
     * 排序字段信息
     * 格式：a:desc,b:asc
     */
    private String orders;

    public <T> Page<T> toPage() {
        List<OrderItem> orderItemList = new ArrayList<>();
        if (StrUtil.isNotBlank(orders)) {
            String[] orderItems = orders.split(",");
            for (String orderItem : orderItems) {
                String[] item = orderItem.split(":");
                OrderItem orderItem_ = new OrderItem();
                if (item.length == 1) {
                    orderItem_.setColumn(item[0]);
                    orderItemList.add(orderItem_);
                } else if (item.length == 2) {
                    orderItem_.setColumn(item[0]);
                    if ("asc".equalsIgnoreCase(item[1])) {
                        orderItem_.setAsc(true);
                    } else if ("desc".equalsIgnoreCase(item[1])) {
                        orderItem_.setAsc(false);
                    } else {
                        throw new RuntimeException(StrUtil.format("排序参数错误，字段：orders，接收到的值：{}", orders));
                    }
                    orderItemList.add(orderItem_);
                } else {
                    throw new RuntimeException(StrUtil.format("排序参数错误，字段：orders，接收到的值：{}", orders));
                }
            }
        }
        Page<T> page = new Page<>(current == null ? 1 : current, size == null ? 500 : size);
        page.setOrders(orderItemList);
        return page;
    }
}
