package utils

import (
	"fmt"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/locales/en"
	"github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	enTranslations "github.com/go-playground/validator/v10/translations/en"
	chTranslations "github.com/go-playground/validator/v10/translations/zh"
	"reflect"
)

var ValidatorTrans ut.Translator

// ValidatorTransInit 验证器错误信息翻译初始化
// local 通常取决于 http 请求头的 'Accept-Language'
func ValidatorTransInit(local string) (err error) {
	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
		zhT := zh.New() //chinese
		enT := en.New() //english
		uni := ut.New(enT, zhT, enT)

		var o bool
		ValidatorTrans, o = uni.GetTranslator(local)
		if !o {
			return fmt.Errorf("uni.GetTranslator(%s) failed", local)
		}
		// 注册一个方法,从自定义标签label中获取值(用在把字段名映射为中文)
		v.RegisterTagNameFunc(func(field reflect.StructField) string {
			label := field.Tag.Get("label")
			if label == "" {
				return field.Name
			}
			return label
		})
		// 注册翻译器
		switch local {
		case "en":
			err = enTranslations.RegisterDefaultTranslations(v, ValidatorTrans)
		case "zh":
			err = chTranslations.RegisterDefaultTranslations(v, ValidatorTrans)
		default:
			err = enTranslations.RegisterDefaultTranslations(v, ValidatorTrans)
		}
		return
	}
	return
}

// ValidatorTransInitZh 验证器错误信息翻译为中文初始化
func ValidatorTransInitZh() (err error) {
	return ValidatorTransInit("zh")
}