package lib

import (
	"fmt"
	"time"

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

var (
	key              []byte = []byte("sx87sda0w7x7sd")
	JWtExpiresSecond int64  = 60 * 60 * 12
)

//MyToken ...
type MyToken struct {
	jwt.StandardClaims
	UID int64 `json:"uid"` //管理员的id

}

func NewMyToken(id int64) *MyToken {
	return &MyToken{UID: id}
}

//CreateJWTToken ...
func (mytoken *MyToken) CreateJWTToken() (string, error) {
	nowTime := time.Now().Unix()
	mytoken.StandardClaims = jwt.StandardClaims{
		NotBefore: nowTime,
		IssuedAt:  nowTime,
		ExpiresAt: nowTime + JWtExpiresSecond,
		Issuer:    "mmm_partnermg",
	}

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

//ValidJWTToken ...
func (mytoken *MyToken) 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
	}
	getoken, ok := token.Claims.(*MyToken)
	if ok && token.Valid {
		// 验证成功,返回信息
		return getoken, nil
	}
	// 验证失败
	return nil, fmt.Errorf("token Valid fail")
}

func (mytoken *MyToken) IsJwtErrorExpired(err error) bool {
	ve, ok := err.(*jwt.ValidationError)
	if ok && ve.Errors == jwt.ValidationErrorExpired {
		return true
	}
	return false
}