package utils

import "gorm.io/gorm"

//分页封装
func Paginate(page int, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if page == 0 {
			page = 1
		}
		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}
		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}

type PageData struct {
	Page       int64
	PageSize   int64
	TotalCount int64
	TotalPage  int64
	Data       interface{}
}

func GetPageData(page, pageSize, total int64) (int64, int64, PageData) {
	if page <= 0 {
		page = 1
	}

	if pageSize <= 0 {
		pageSize = 10
	}

	var pageData PageData
	pageData.Page = page
	pageData.PageSize = pageSize
	pageData.TotalCount = total
	pageData.TotalPage = total / pageSize
	if total%pageSize > 0 {
		pageData.TotalPage += 1
	}

	if page > pageData.TotalPage {
		page = pageData.TotalPage
		pageData.Page = page
	}

	start := pageSize * (page - 1)
	if start < 0 {
		start = 0
	}
	return pageSize, start, pageData
}
