package tools

import (
	"errors"
	zhongwen "github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	zhtranslation "github.com/go-playground/validator/v10/translations/zh"
)

var validate *validator.Validate
var trans ut.Translator

func init() {

	//中文
	zh := zhongwen.New()
	uni := ut.New(zh, zh)
	trans, _ = uni.GetTranslator("zh")

	validate = validator.New(validator.WithRequiredStructEnabled())

	_ = zhtranslation.RegisterDefaultTranslations(validate, trans)
}

func Validate(s interface{}) error {
	err := validate.Struct(s)
	var errs validator.ValidationErrors
	if errors.As(err, &errs) {
		return errors.New(errs[0].Translate(trans))
	}
	return err
}
