package tool

import (
	jwt "github.com/golang-jwt/jwt/v4"
	"gitlab.fjmaimaimai.com/allied-creation/sumifcc-bchart/pkg/config"
	"time"
)

type UserToken struct {
	UserId      int64   `json:"userId"`
	CoachId     int64   `json:"coach_id"`
	AdminId     int64   `json:"adminId"`
	ClientType  string  `json:"clientType"`
	AccessShops []int64 `json:"accessShops"`
}

func (tk UserToken) GenerateToken(jwtConfig config.JwtAuth) (string, error) {
	claims := make(jwt.MapClaims)
	claims["exp"] = time.Now().Unix() + jwtConfig.Expire
	claims["iat"] = time.Now().Unix()
	claims["UserId"] = tk.UserId
	claims["CoachId"] = tk.CoachId
	claims["AdminId"] = tk.AdminId
	claims["ClientType"] = tk.ClientType
	claims["AccessShops"] = tk.AccessShops
	token := jwt.New(jwt.SigningMethodHS256)
	token.Claims = claims

	return token.SignedString([]byte(jwtConfig.AccessSecret))
}

func (tk *UserToken) ParseToken(jwtConfig config.JWT, str string) error {
	//tokenClaims, err := jwt.ParseWithClaims(
	//	str,
	//	tk,
	//	func(token *jwt.Token) (interface{}, error) {
	//		return []byte(jwtConfig.Secret), nil
	//	})
	//if err != nil {
	//	return err
	//}
	//if claim, ok := tokenClaims.Claims.(*UserToken); ok && tokenClaims.Valid {
	//	*tk = *claim
	//	return nil
	//}
	//return errors.New("token 解析失败")
	return nil
}

// CheckUserInfo 如果UserToken有效 返回:true 否则返回false
func (tk *UserToken) CheckUserInfo() bool {
	return !(tk.UserId > 100000000 || tk.UserId <= 0)
}