package com.ytpm.general;

import com.github.pagehelper.PageInfo;
import lombok.Data;

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

/**
 * @author marx
 * @date 2022/5/13 10:27
 * @description 列表数据返回实体
 */
@Data
public class ResultTable<T> implements Serializable {

    private Integer code;
    private String message;
    private List<T> data;
    private PageMeta pageMeta;

    public ResultTable() {
    }

    public ResultTable(Integer code, String message, List<T> data, PageMeta pageMeta) {
        this.code = code;
        this.message = message;
        this.data = data;
        this.pageMeta = pageMeta;
    }

    public ResultTable(Integer code, String message) {
        this.code = code;
        this.message = message;
    }

    /**
     * 查询成功，返回实体
     *
     * @param list 返回列表集合
     * @param total 总条数
     * @param perPage 单页数量
     * @param currentPage 当前页码
     * @param lastPage 总页码
     * @return
     */
    public static <T> ResultTable resultTableOk(List<T> list, Long total, Integer perPage, Integer currentPage, Integer lastPage) {
        if(null == list){
            list = new ArrayList<>();
        }
        PageMeta pageMeta = new PageMeta(total, perPage, currentPage, lastPage);
        return new ResultTable<T>(StatusCode.OK, RepMessage.QUERY_SUCCESS, list, pageMeta);
    }

    /**
     * 查询成功，返回实体
     *
     * @param pageInfo 分页插件返回实体
     * @return
     */
    public static <T> ResultTable<T> resultTableOk(PageInfo<T> pageInfo) {
        //当前页
        int currentPage = pageInfo.getPageNum();
        //每页的数量
         int perPage = pageInfo.getPageSize();

        //总页数
         int lastPage  = pageInfo.getPages();
         long total  = pageInfo.getTotal();
         List<T> list = pageInfo.getList();
        if(null == list){
            list = new ArrayList<>();
        }
        PageMeta pageMeta =  new PageMeta(total, perPage, currentPage, lastPage);
        return new ResultTable(StatusCode.OK, RepMessage.QUERY_SUCCESS, list, pageMeta);
    }

    /**
     * 查询失败，返回实体
     * @param code
     * @param msg
     * @return
     */
    public static ResultTable resultFail(int code, String msg) {
        return new ResultTable(code, msg);
    }
}
