package com.storlead.trade.common;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import org.springframework.util.CollectionUtils;

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

/**
 * @program: sp-tems
 * @description: page类
 * @author: xiaojiawei
 * @create: 2022-04-15 16:37
 **/
@Data
public class Page implements Serializable {
    private static final long serialVersionUID = 1004386013084749956L;

    @TableField(exist = false)
    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    @ApiModelProperty(value = "页码", example = "1")
    private Integer pageIndex = 1;

    @TableField(exist = false)
    @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
    @ApiModelProperty(value = "页面大小", example = "10")
    private Integer pageSize = 10;

    @ApiModelProperty(value = "页码", example = "1")
    private Integer pageNo = 1;

    /**
     * 设置 pageIndex 时同步到 pageNo
     */
    public void setPageIndex(Integer pageIndex) {
        this.pageIndex = pageIndex;
        if (pageIndex != null) {
            this.pageNo = pageIndex;
        }
    }

    /**
     * 设置 pageNo 时同步到 pageIndex
     */
    public void setPageNo(Integer pageNo) {
        this.pageNo = pageNo;
        if (pageNo != null) {
            this.pageIndex = pageNo;
        }
    }

    public static  <T> IPage<T> page(IPage page, Class<T> t) {
        DefaultMapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
        IPage<T> pageVo = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(page.getCurrent(),page.getSize());
        if (CollectionUtils.isEmpty(page.getRecords())) {
            return page;
        }
        List<T> vos = mapperFactory.getMapperFacade().mapAsList(page.getRecords(),t);
        pageVo.setTotal(page.getTotal());
        pageVo.setRecords(vos);
        return pageVo;
    }

}
