package routers

import (
	"github.com/gin-gonic/gin"
	_ "chain33-pai/docs"
	"chain33-pai/routers/api/v1"
	"net/http"
	"reflect"
	"strconv"
	"gopkg.in/go-playground/validator.v8"
	"github.com/gin-gonic/gin/binding"
	"chain33-pai/pkg/logging"
)

// InitRouter initialize routing information
func InitRouter() *gin.Engine {
	r := gin.Default()
	//Custom Validators
	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
		err := v.RegisterValidation("LegalNumber", CheckNumber)
		if err != nil {
			logging.Error("gin custom validator init error, field:LegalNumber")
		}
	}
	r.Use(gin.Logger())
	r.Use(gin.Recovery())
	r.Use(Cors())

	apiv1 := r.Group("/pai")
	//获取树莓派基本信息
	//apiv1.Any("",Cors())
	apiv1.POST("/ticketinfo",v1.GetTicketInfo)
	apiv1.POST("/minetime",v1.RecordMineTime)
	apiv1.POST("/latestversion",v1.GetVersion)
	apiv1.POST("/feedback",v1.FeedBack)
	apiv1.POST("/iscomplete",v1.IsComplete)
	apiv1.POST("/getfeedlist",v1.GetFeedList)
	apiv1.POST("/uploadinfo",v1.GetUploadInfo)
	apiv1.POST("/uploadtest",v1.GetUploadTest)
	apiv1.POST("/test",v1.GetTest)
	return r
}

// 处理跨域请求,支持options访问
func Cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method
		c.Header("Access-Control-Allow-Origin", "*")
		c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token,Authorization") //Content-Type,AccessToken,X-CSRF-Token,Authorization,Token,FZM-APP-ID
		c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, PATCH, DELETE")
		c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
		c.Header("Access-Control-Allow-Credentials", "true")

		// 放行所有OPTIONS方法，因为有的模板是要请求两次的
		if method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
		}

		// 处理请求
		c.Next()
	}
}


func CheckNumber(
	v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value,
	field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string,
) bool {
	val := field.Interface()

	switch val.(type) {
	case int:
		return true
	case string:
		if val.(string) == "" {
			return true
		}
		_, err := strconv.ParseInt(val.(string), 10, 64)
		if err != nil {
			return false
		}
		return true
	case int64:
		return true
	default:
		//utility_log.Error("func ToInt error unknow type")
		return false
	}
}
