package com.microservices.common.core.web.page;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.microservices.common.core.constant.HttpStatus;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

/**
 * 表格分页数据对象
 *
 * @author microservices
 */
@Data
@ApiModel("表格分页数据对象")
public class GenericsTableDataInfo<T> implements Serializable {
    private static final long serialVersionUID = 1L;

    /**
     * 总记录数
     */
    @ApiModelProperty("总记录数")
    private long total;

    /**
     * 列表数据
     */
    @ApiModelProperty("列表数据")
    private List<T> rows;

    /**
     * 消息状态码
     */
    @ApiModelProperty("消息状态码")
    private int code;

    /**
     * 消息内容
     */
    @ApiModelProperty("消息内容")
    private String msg;

    /**
     * 面包屑数据
     */
    @ApiModelProperty("面包屑数据")
    @JsonInclude(JsonInclude.Include.NON_NULL) //为空时隐藏
    private List<Breadcrumb> breadcrumb;

    /**
     * 表格数据对象
     */
    public GenericsTableDataInfo() {
        this.total = 0;
        this.rows = new ArrayList<>();
        this.code = HttpStatus.SUCCESS;
        this.msg = "查询成功";
    }

    /**
     * 将原始列表通过传入方法转换为对应类型，同时根据原始列表分页数据构建分页对象
     *
     * @param rows   原始列表（带分页）
     * @param toList Lambda表达式，对原始列表进行转换
     * @param <E>    原始列表列席
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    public <E> GenericsTableDataInfo(List<E> rows, Page.Function<List<E>, List<T>> toList) {
        rows = Optional.ofNullable(rows).orElse(Collections.emptyList());
        this.total = new PageInfo(rows).getTotal();
        this.rows = toList.apply(rows);
        this.code = HttpStatus.SUCCESS;
        this.msg = "查询成功";
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    public GenericsTableDataInfo(List<T> rows) {
        this.total = new PageInfo(rows).getTotal();
        this.rows = rows;
        this.code = HttpStatus.SUCCESS;
        this.msg = "查询成功";
    }

    /**
     * 分页
     *
     * @param list  列表数据
     * @param total 总记录数
     */
    public GenericsTableDataInfo(List<T> list, Long total) {
        this.rows = list;
        this.total = total;
        this.code = HttpStatus.SUCCESS;
        this.msg = "查询成功";
    }
}