package utils

import (
	"github.com/gin-gonic/gin"
	"github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	zhTranslations "github.com/go-playground/validator/v10/translations/zh"
	"reflect"
)

// ValidateInfo2CN 翻译validator为中文，并通过struct tag 中的label将字段名变成中文反馈在response错误信息中
func ValidateInfo2CN(req interface{}) (string, bool) {
	var validateErr string
	uni := ut.New(zh.New())
	trans, _ := uni.GetTranslator("zh")
	validate := validator.New()
	validate.RegisterTagNameFunc(func(field reflect.StructField) string {
		name := field.Tag.Get("label")
		return name
	})
	_ = zhTranslations.RegisterDefaultTranslations(validate, trans)
	err := validate.Struct(req)
	if err != nil {
		if _, ok := err.(validator.ValidationErrors); !ok {
			return err.Error(), false
		}
		for i := 0; i < len(err.(validator.ValidationErrors)); i++ {
			if len(err.(validator.ValidationErrors))-1 == i {
				validateErr += err.(validator.ValidationErrors)[i].Translate(trans)
			} else {
				validateErr += err.(validator.ValidationErrors)[i].Translate(trans) + ","
			}
		}
		return validateErr, false
	}
	return validateErr, true
}

type BaseRequestHttpHandlerInterface interface {
	Create(c *gin.Context)
	Show(c *gin.Context)
	Update(c *gin.Context)
	Delete(c *gin.Context)
}
