package utils

import (
	"fmt"
	"time"

	jwt "github.com/dgrijalva/jwt-go"
)

var (
	key = []byte("sx87sda0w7x7sd")
)

//MyToken ...
type MyToken struct {
	jwt.StandardClaims
	UID       int `json:"uid"`
	CompanyID int `json:"company_id"`
}

//CreateJWTToken ...
func CreateJWTToken(id int) (string, error) {
	nowTime := time.Now().Unix()
	claims := MyToken{
		StandardClaims: jwt.StandardClaims{
			NotBefore: nowTime,
			IssuedAt:  nowTime,
			ExpiresAt: 60 * 60 * 2, //过期时间
			Issuer:    "test_a",
		},
		UID: id,
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString(key)
}

//ValidJWTToken ...
func ValidJWTToken(tokenString string) (*MyToken, error) {
	token, err := jwt.ParseWithClaims(
		tokenString,
		&MyToken{},
		func(token *jwt.Token) (interface{}, error) {
			return key, nil
		})
	if err != nil {
		return nil, err
	}
	if claims, ok := token.Claims.(*MyToken); ok && token.Valid {
		// 验证成功,返回信息
		return claims, nil
	}
	// 验证失败
	return nil, fmt.Errorf("token Valid fail")
}