package token

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"github.com/sirupsen/logrus"
	"os"
	"time"
)

type UserClaims struct {
	ID          int64  `json:"user_id"`
	UserName    string `json:"user_name"`
	RoleId      int64  `json:"role_id"`
	Avatar      string `json:"avatar"`
	Nickname    string `json:"nickname"`
	SystemId    int32  `json:"system_id"`
	AccessToken string `json:"access_token"`
	jwt.StandardClaims
}

var (
	secret     = []byte(os.Getenv("JWT_SECRET"))
	effectTime = 30 * 24 * time.Hour // 30天有效期
)

func GetAuthorization(c *gin.Context) (t string) {
	t = c.GetHeader("authorization")
	if t == "" {
		t = c.Request.URL.Query().Get("authorization")
	}

	return t
}

func CurrentUser(c *gin.Context) *UserClaims {
	if user, _ := c.Get("user"); user != nil {
		if u, ok := user.(*UserClaims); ok {
			return u
		}
	}
	logrus.Warn("CurrentUser = nil")
	return nil
}

func GetUID(c *gin.Context) int64 {
	user := CurrentUser(c)
	if user == nil {
		return 0
	}
	return user.ID
}

func GenerateTokenUsingUUID() string {
	return uuid.New().String()
}
