package middleware

import (
	"encoding/base64"
	"entrance-grpc/iam"
	"gadmin/config"
	"gadmin/utility/serializer"
	"gadmin/utility/token"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

// 路由白名单
var whitelist = []string{
	"/api/gm/userRoles",
}

// Token 验证token
func Token() gin.HandlerFunc {
	return func(c *gin.Context) {
		if isWhite(c.Request.URL.Path) {
			c.Next()
			return
		}

		encodeToken := token.GetAuthorization(c)
		if encodeToken == "" {
			c.JSON(200, serializer.CheckLogin())
			c.Abort()
			return
		}
		bytesT, err := base64.URLEncoding.DecodeString(encodeToken)
		if err != nil {
			logrus.Warningf("middleware base64.URLEncoding.DecodeString:%+v", err.Error())
			c.JSON(200, serializer.CheckLogin())
			c.Abort()
			return
		}
		t := string(bytesT)

		resp, err := config.GetIamClient().CheckToken(c, &iam.CheckTokenReq{
			Token: t,
		})
		if err != nil {
			logrus.Warningf("middleware config.GetIamClient().CheckToken:%+v", err.Error())
			c.JSON(200, serializer.CheckLogin())
			c.Abort()
			return
		}
		if resp.Code != 0 {
			logrus.Warningf("middleware config.GetIamClient().CheckToken code:%+v,msg:%+v", resp.Code, resp.Msg)
			c.JSON(200, serializer.CheckLogin())
			c.Abort()
			return
		}
		user := resp.Data
		/*tokenKey := config.GetTokenKey(t)
		if config.TokenRedis.Exists(tokenKey).Val() == 0 {
			c.JSON(200, serializer.CheckLogin())
			c.Abort()
			return
		}
		userStr := config.TokenRedis.Get(tokenKey).Val()

		user := new(token.UserClaims)
		if err := jsoniter.UnmarshalFromString(userStr, user); err != nil {
			c.JSON(200, serializer.CheckLogin())
			c.Abort()
			return
		}
		if user.ID == 0 {
			c.JSON(200, serializer.CheckLogin())
			c.Abort()
			return
		}
		// 查询登录token是否有效
		key := config.GetUserTokenKey(user.ID)
		tokenCTStr := config.TokenRedis.HGet(key, t).Val()
		tokenCreateTime, err := strconv.Atoi(tokenCTStr)
		if err != nil {
			logrus.Warningf("middleware config.LogRedis.HGet:%+v", err.Error())
			c.JSON(200, serializer.CheckLogin())
			c.Abort()
			return
		}

		if tokenCreateTime == 0 {
			c.JSON(200, serializer.CheckLogin())
			c.Abort()
			return
		}

		tokenCT := time.Now()
		// 正式环境校验token有效期
		if os.Getenv("GIN_MODE") == "release" {
			tokenCT = time.Unix(int64(tokenCreateTime), 0)
		}

		if tokenCT.Before(time.Now().Add(-config.TokenExpireTime)) {
			c.JSON(200, serializer.CheckLogin())
			c.Abort()
			return
		}
		config.TokenRedis.HSet(key, t, time.Now().Unix())
		config.TokenRedis.Expire(key, time.Hour*12)

		config.TokenRedis.Expire(tokenKey, time.Hour*12)*/

		//if os.Getenv("GIN_MODE") == "release" && claims.UserName == "mojun" {
		//	c.JSON(200, serializer.CheckLogin())
		//	c.Abort()
		//	return
		//}

		c.Set("user", user)
		c.Set("admin_role_id", user.RoleID)
		c.Next()
		return
	}
}

func isWhite(path string) bool {
	for _, v := range whitelist {
		if path == v {
			return true
		}
	}
	return false
}
