package utils

import (
	"errors"
	"mtp20access/model/common/request"
	"mtp20access/model/common/response"

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

type GinUtils struct {
	C   *gin.Context
	Err error
}

// BindFormReq 绑定Form入参的方法
func (r *GinUtils) BindFormReq(req interface{}) {
	if r.Err != nil {
		return
	}
	if r.Err = r.C.ShouldBind(&req); r.Err != nil {
		response.FailWithMessage("入参不正确", r.C)
		return
	}
}

// BindJsonReq 绑定Body入参的方法
func (r *GinUtils) BindJsonReq(req interface{}) {
	if r.Err != nil {
		return
	}
	if r.Err = r.C.ShouldBindJSON(&req); r.Err != nil {
		response.FailWithMessage("入参不正确", r.C)
		return
	}
}

func (r *GinUtils) GetClaims() (claims *request.CustomClaims) {
	if r.Err != nil {
		return
	}
	// 获取请求账号信息
	s, exists := r.C.Get("claims")
	if !exists {
		r.Err = errors.New("获取请求账号信息异常")
		response.FailWithMessage("获取请求账号信息异常", r.C)
		return
	}
	claims = s.(*request.CustomClaims)

	return
}
