package app

import (
	"mtp2_if/global/e"

	"github.com/gin-gonic/gin"
)

// Gin is gin.Context
type Gin struct {
	C *gin.Context
}

// Response 通用Response数据结构
type Response struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
	PageInfo
	Data interface{} `json:"data"`
}

// Response setting gin.JSON
func (g *Gin) Response(httpCode, errCode int, data interface{}) {
	g.C.JSON(httpCode, Response{
		Code: errCode,
		Msg:  e.GetMsg(errCode),
		Data: data,
	})
	return
}

// ResponseByPage 带分页信息返回方法
func (g *Gin) ResponseByPage(httpCode, errCode int, data interface{}, page PageInfo) {
	g.C.JSON(httpCode, Response{
		Code:     errCode,
		Msg:      e.GetMsg(errCode),
		PageInfo: page,
		Data:     data,
	})
	return
}

// GetPageData 获取指定分页的数据
func GetPageData(datas []interface{}, pageInfo PageInfo) []interface{} {
	// 开始上标
	start := pageInfo.Page * pageInfo.PageSize
	// 结束下标
	// a := []int{1,2,3,4,5}
	// a[2:4] -> [3 4]
	end := start + pageInfo.PageSize

	if start <= len(datas) {
		// 判断结束下标是否越界
		if end > len(datas) {
			end = len(datas)
		}
		datas = datas[start:end]
	} else {
		datas = datas[0:0]
	}

	return datas
}
