package share

import (
	"crypto/rand"
	"errors"
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"math/big"
	"time"
)

const (
	SECRETKEY = "243223ffslsfsldfl412fdsfsdf" //私钥
)

type CustomClaims struct {
	UserId int64
	jwt.StandardClaims
}

func GetJsonAnyParam(c *gin.Context) func(param string) (interface{}, error) {
	jsonData := map[string]interface{}{}
	err := c.BindJSON(&jsonData)

	return func(param string) (interface{}, error) {
		if err != nil {
			return nil, err
		}
		value, err := func() (interface{}, error) {

			i, exists := jsonData[param]
			if !exists {
				return nil, errors.New("缺少" + param + "字段")
			}

			return i, nil
		}()
		if err != nil {
			return nil, err
		}
		return value, err
	}
}

func GenerateToken(userId string) (string, error) {
	maxAge := 60 * 60 * 24
	// Create the Claims
	claims := &jwt.StandardClaims{
		ExpiresAt: time.Now().Add(time.Duration(maxAge) * time.Second).Unix(), // 过期时间，必须设置,
		Issuer:    userId,                                                     // 非必须，也可以填充用户名，
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	tokenString, err := token.SignedString([]byte(SECRETKEY))
	if err != nil {
		fmt.Println(err)
	}
	return tokenString, err
}
func ParseToken(tokenString string) (jwt.MapClaims, error) {
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		// Don't forget to validate the alg is what you expect:
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
		}

		// hmacSampleSecret is a []byte containing your secret, e.g. []byte("my_secret_key")
		return []byte(SECRETKEY), nil
	})
	if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
		return claims, nil
	} else {
		return nil, err
	}
}

//权限判断，废弃
//func JwtMiddleware() gin.HandlerFunc {
//	return func(c *gin.Context) {
//		tokenString := c.GetHeader("auth-sign")
//		if tokenString == "" {
//			c.JSON(401, gin.H{"message": "缺少token"})
//			c.Abort()
//			return
//		}
//
//		token, err := ParseToken(tokenString)
//
//		if err != nil {
//			c.JSON(401, gin.H{"message": "无效令牌"})
//			c.Abort()
//			return
//		}
//		users := make([]configs.MysqlData, 0)
//		bools, err := configs.Engine.Table("user").
//			Join("INNER", "role", "role.id = user.role_id").
//			Join("INNER", "role_authority", "role_authority.authority_id = role.id").
//			Join("INNER", "authority", "authority.id = role_authority.authority_id").
//			Where("authority.authority_path=?", c.Request.URL.Path).
//			Where("user.id = ?", token["iss"]).
//			Exist(&users)
//		if err == nil {
//			fmt.Println(bools)
//			if bools {
//				c.Next()
//			} else {
//				c.JSON(200, gin.H{"message": "权限不足"})
//				c.Abort()
//				return
//			}
//		}
//
//	}
//}

func RandomInt(min, max *big.Int) *big.Int {
	// 读取密码学安全的随机比特
	byteLen := (max.BitLen() + 7) / 8
	b := make([]byte, byteLen)
	rand.Read(b)

	// 将字节转换为大整数
	r := new(big.Int).SetBytes(b)

	// 需要将生成的大整数范围限制在[min,max]
	r.Rem(r, new(big.Int).Sub(max, min)).Add(r, min)
	return r
}
