package jwt

import (
	logger "eta/eta_mini_ht_api/common/component/log"
	"eta/eta_mini_ht_api/common/exception"
	"github.com/dgrijalva/jwt-go"
	"time"
)

type Claims struct {
	OpenId string `json:"open_id"`
	Mobile string `json:"mobile"`
	jwt.StandardClaims
}

var (
	KEY = []byte("5Mb5Gdmb5y")
)

// CreateToken 生成token
func CreateToken(openId string, mobile string) (tokenString string, err error) {

	claims := &Claims{
		openId,
		mobile,
		jwt.StandardClaims{
			NotBefore: time.Now().Unix(),
			ExpiresAt: time.Now().Add(time.Hour * 24 * 90).Unix(),
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	tokenString, err = token.SignedString(KEY)
	if err != nil {
		logger.Error("生成token失败", err)
	}
	return
}

type JwtInfo struct {
	OpenId string
	Mobile string
}

// CheckToken 校验token
func CheckToken(tokenStr string) (info JwtInfo, err error) {
	token, err := jwt.Parse(tokenStr, func(*jwt.Token) (interface{}, error) {
		return KEY, nil
	})
	if err != nil {
		logger.Error("解析Token失败：%v", err)
		err = exception.New(exception.JWTTokenDecodeFailed)
		return
	}
	if claims, ok := token.Claims.(jwt.MapClaims); ok {
		nbf, _ := claims["nbf"].(float64)
		exp, _ := claims["exp"].(float64)

		if float64(time.Now().Unix()) < nbf {
			logger.Error("Token无效")
			err = exception.New(exception.JWTTokenInvalid)
			return
		}
		if float64(time.Now().Unix()) >= exp {
			logger.Error("Token已过期")
			err = exception.New(exception.JWTTokenExpired)
			return
		}
		info = JwtInfo{
			OpenId: claims["open_id"].(string),
			Mobile: claims["mobile"].(string),
		}
		return
	}
	logger.Error("claims解析失败")
	err = exception.New(exception.JWTTokenDecodeFailed)
	return
}
