package book

import (
	"fmt"

	commonReq "github.com/flipped-aurora/gin-vue-admin/server/model/common/request"
	"github.com/flipped-aurora/gin-vue-admin/server/model/common/response"
	"github.com/flipped-aurora/gin-vue-admin/server/utils"
	"github.com/gin-gonic/gin"
)

func bindID(c *gin.Context) (uint, bool) {
	var req commonReq.GetById
	if err := c.ShouldBindQuery(&req); err != nil {
		response.FailWithMessage(err.Error(), c)
		return 0, false
	}
	if err := utils.Verify(req, utils.IdVerify); err != nil {
		response.FailWithMessage(err.Error(), c)
		return 0, false
	}
	return req.Uint(), true
}

func bindIDs(c *gin.Context) (commonReq.IdsReq, bool) {
	var req commonReq.IdsReq
	if err := c.ShouldBindQuery(&req); err != nil {
		response.FailWithMessage(err.Error(), c)
		return req, false
	}
	if len(req.Ids) == 0 {
		for _, rawID := range c.QueryArray("ids[]") {
			var id int
			if _, err := fmt.Sscanf(rawID, "%d", &id); err != nil {
				response.FailWithMessage(err.Error(), c)
				return req, false
			}
			req.Ids = append(req.Ids, id)
		}
	}
	if len(req.Ids) == 0 {
		response.FailWithMessage("ids不能为空", c)
		return req, false
	}
	return req, true
}

func pageResult(c *gin.Context, list interface{}, total int64, page commonReq.PageInfo) {
	response.OkWithDetailed(response.PageResult{List: list, Total: total, Page: page.Page, PageSize: page.PageSize}, "获取成功", c)
}
