package com.erp.common.core.model;

import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.List;

/**
 * 分页响应封装
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class PageResponse<T> {

    /**
     * 当前页数据列表
     */
    private List<T> list;

    /**
     * 总记录数
     */
    private Long total;

    /**
     * 当前页码
     */
    private Long page;

    /**
     * 每页记录数
     */
    private Long pageSize;

    /**
     * 总页数
     */
    private Long totalPages;

    /**
     * 是否有下一页
     */
    private Boolean hasNext;

    /**
     * 是否有上一页
     */
    private Boolean hasPrevious;

    /**
     * 从第几条开始
     */
    private Long offset;

    public Boolean getHasNext() {
        if (total == null || page == null || pageSize == null) {
            return null;
        }
        return page * pageSize < total;
    }

    public Boolean getHasPrevious() {
        if (page == null) {
            return null;
        }
        return page > 1;
    }

    public Long getOffset() {
        if (page == null || pageSize == null) {
            return null;
        }
        return (page - 1) * pageSize;
    }
    
    /**
     * 分页响应工厂方法
     */
    public static <T> PageResponse<T> of(List<T> list, Long total, Integer page, Integer pageSize) {
        Long totalPages = pageSize != null && pageSize > 0 ? (total + pageSize - 1) / pageSize : 0L;
        Long pageLong = page != null ? page.longValue() : null;
        Long pageSizeLong = pageSize != null ? pageSize.longValue() : null;
        return PageResponse.<T>builder()
                .list(list)
                .total(total)
                .page(pageLong)
                .pageSize(pageSizeLong)
                .totalPages(totalPages)
                .hasNext(pageLong != null && pageSizeLong != null && pageLong * pageSizeLong < total)
                .hasPrevious(pageLong != null && pageLong > 1)
                .offset(pageLong != null && pageSizeLong != null ? (pageLong - 1) * pageSizeLong : 0L)
                .build();
    }
}
