/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights reserved. <a>http://www.crunii.com</a>
 */
package com.crunii.micro.common.dto;

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

import com.crunii.micro.common.utils.JsonUtil;
import com.fasterxml.jackson.databind.JavaType;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import javax.validation.Valid;

/**
 * @author 田平 create 2017年4月24日下午3:02:44
 */
@Setter
@Getter
@ToString
@ApiModel(description = "分页请求对象")
public class PageReq<T> implements Serializable {

	private static final long serialVersionUID = 1L;

	@ApiModelProperty(value = "页码，默认1")
	private int pageNo = 1;
	@ApiModelProperty(value = "页大小，默认10")
	private int pageSize = 10;
	@Valid
	@ApiModelProperty(value = "参数实体")
	private T query;
	@ApiModelProperty(value = "排序字段,一般前端不传，由后端指定")
	private List<OrderProp> orderProps = Collections.emptyList();

	public PageReq() {

	}

	public PageReq(T t) {
		this.query = t;
	}

	/**
	 * 获取mysql的limit的开始位置
	 *
	 * @return
	 */
	public int getMyStart() {
		return (pageNo - 1) * pageSize;
	}

	public static <K> PageReq<K> getPageReq(String json, Class<K> objClass) {
		JavaType javaType = JsonUtil.getMapper().getTypeFactory().constructParametricType(PageReq.class, objClass);
		try {
			return JsonUtil.getMapper().readValue(json, javaType);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

}
