package controllers

import (
	"sparrow/pkg/models"
	"sparrow/services/knowoapi/model"
	"time"

	"github.com/kataras/iris/v12"

	jwt "github.com/golang-jwt/jwt/v4"
)

// Token helper
type Token struct {
}

// UserClaims user claim
type UserClaims struct {
	UserID   uint
	UserName string
	UserType string
	RoleCode int
	VendorID string
	jwt.StandardClaims
}

// TokenMaker 生成token
func (t *Token) TokenMaker(user *models.User) string {
	claims := UserClaims{
		UserName: user.UserName,
		UserID:   user.ID,
		RoleCode: user.UserRoleID,
		VendorID: user.VendorID,
	}
	claims.ExpiresAt = time.Now().Add(time.Hour * 24).Unix()
	claims.Issuer = "lutai"
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	ser, _ := token.SignedString([]byte(model.SignedString))
	return ser
}

func (t *Token) getUserClaims(ctx iris.Context) jwt.MapClaims {
	tk := ctx.Values().Get("jwt").(*jwt.Token)
	return tk.Claims.(jwt.MapClaims)
}

// 获取当前用户recordid
func (t *Token) getRecorID(ctx iris.Context) uint {
	claims := t.getUserClaims(ctx)
	return uint(claims["UserID"].(float64))
}

// 获取当前用户vendorid
func (t *Token) getVendorID(ctx iris.Context) string {
	claims := t.getUserClaims(ctx)
	return claims["VendorID"].(string)
}

func (t *Token) getRoleID(ctx iris.Context) int {
	claims := t.getUserClaims(ctx)
	return int(claims["RoleCode"].(float64))
}
