/* (C) 2021 YiRing, Inc. */
package com.yiring.common.vo;

import com.yiring.common.util.Commons;
import io.swagger.v3.oas.annotations.media.Schema;
import java.io.Serial;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.FieldDefaults;
import org.springframework.data.domain.Page;

/**
 * 分页查询响应公共类
 *
 * @author ifzm
 * @version 0.1 2019/3/10 16:29
 */
@Schema(name = "PageVo", description = "公共分页查询响应输出")
@Data
@NoArgsConstructor
@AllArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE)
public class PageVo<T extends Serializable> implements Serializable {

    @Serial
    private static final long serialVersionUID = 6103761701912769946L;

    @Schema(description = "数据")
    List<T> data;

    @Schema(description = "数据总数", example = "100")
    Long total;

    @Schema(description = "分页页数", example = "10")
    Integer pages;

    /**
     * 通常在带有时效性的数据查询时有用途（可选参数）
     */
    @Schema(description = "数据最新时间")
    LocalDateTime latest;

    /**
     * 构建一个 PageVo
     *
     * @param data 数据
     * @return PageVo
     */
    @SuppressWarnings({ "unused" })
    public static <R extends Serializable> PageVo<R> build(List<R> data) {
        return build(data, data.size(), 1);
    }

    /**
     * 构建一个 PageVo
     *
     * @param data  数据
     * @param total 总数据量
     * @return PageVo
     */
    @SuppressWarnings({ "unused" })
    public static <R extends Serializable> PageVo<R> build(List<R> data, long total, int pages) {
        return build(data, total, pages, null);
    }

    /**
     * 构建一个 PageVo
     *
     * @param data   数据
     * @param total  总数据量
     * @param latest 数据最新时间
     * @return PageVo
     */
    @SuppressWarnings({ "unused" })
    public static <R extends Serializable> PageVo<R> build(List<R> data, long total, int pages, LocalDateTime latest) {
        PageVo<R> vo = new PageVo<>();
        vo.setData(data);
        vo.setTotal(total);
        vo.setPages(pages);
        vo.setLatest(latest);
        return vo;
    }

    /**
     * 提取 Page 查询结果并转换成 Vo
     *
     * @param page Page 查询结果
     * @param type Vo 类
     * @param <S>  数据实体表
     * @param <T>  Vo 表
     * @return PageVo
     */
    @SuppressWarnings({ "unused" })
    public static <S, T extends Serializable> PageVo<T> toPageVo(Page<S> page, Class<T> type) {
        List<T> data = Commons.transform(page.toList(), type);
        return build(data, page.getTotalElements(), 1);
    }

    /**
     * @return 空的分页查询结果
     */
    @SuppressWarnings("unused")
    public static <T extends Serializable> PageVo<T> empty() {
        return build(Collections.emptyList(), 0, 1);
    }
}
