package middleware

import (
	"git.echol.cn/loser/logger/log"
	"github.com/gin-gonic/gin"
	r "miniapp/model/common/response"
	"miniapp/oauth2"
	"strings"
)

// AuthorizeToken 验证OAuth2生成的Token
func AuthorizeToken() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		// 判断有无token
		tokenStr := ctx.GetHeader("Authorization")
		if tokenStr == "" || !strings.HasPrefix(tokenStr, "Bearer ") {
			r.FailWithMessage("请先登录", ctx)
			ctx.Abort()
			return
		}
		// 先取出用户Token
		token, err := oauth2.OAuthServer.ValidationBearerToken(ctx.Request)
		if err != nil {
			log.Errorf("获取Token失败，错误：%s", err.Error())
			r.FailWithMessage("登录已失效或已在其他地方登录", ctx)
			ctx.Abort()
			return
		}
		// 把UserId字段反序列化成map
		//info := make(map[string]string)
		//if err = json.Unmarshal([]byte(token.GetUserID()), &info); err != nil {
		//	core.R(ctx).FailWithMessageAndCode("Token数据解析失败", http.StatusUnauthorized)
		//	ctx.Abort()
		//	return
		//}
		//go func() {
		//	// 异步记录用户在线情况，十分钟没操作就是不在线了
		//	rdsKey := "oauth:online:" + info["userId"]
		//	global.RedisConn.Set(context.Background(), rdsKey, "1", 10*time.Minute)
		//}()
		// 判断通过，允许放行
		ctx.Request.Header.Add("userId", token.GetUserID())
		ctx.Set("userId", token.GetUserID())
		ctx.Next()
	}
}

// DealLoginUserId 处理登录用户Id
func DealLoginUserId() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		// 判断有无token
		tokenStr := ctx.GetHeader("Authorization")
		if tokenStr == "" || !strings.HasPrefix(tokenStr, "Bearer ") {
			//ctx.Next()
			return
		}
		// 先取出用户Token
		token, err := oauth2.OAuthServer.ValidationBearerToken(ctx.Request)
		if err != nil {
			//ctx.Next()
			return
		}
		//log.Debugf("本次请求存在正常Token: %v", tokenStr)
		// 判断通过，允许放行
		ctx.Request.Header.Add("userId", token.GetUserID())
		ctx.Set("userId", token.GetUserID())
		//ctx.Next()
	}
}
