package middleware

import (
	"github.com/gin-gonic/gin"
	"hongze/hongze_yb/controller/response"
	"hongze/hongze_yb/models/tables/rddp/session"
	services "hongze/hongze_yb/services/user"
	"hongze/hongze_yb/utils"
)

func Token() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.Request.Header.Get("Authorization")
		if token == "" {
			token = c.DefaultQuery("authorization", "")
			if token == "" {
				token = c.DefaultQuery("Authorization", "")
			}
		}
		if token == "" {
			response.TokenError(nil, "未登录或非法访问", "未登录或非法访问", c)
			c.Abort()
			return
		}
		sessionInfo, err := session.GetTokenByToken(token)
		if err != nil {
			if err == utils.ErrNoRow {
				response.TokenError(nil, "信息已变更,请重新登陆！", "找不到对应session", c)
				c.Abort()
				return
			}
			response.TokenError(nil, "网络异常，请稍后重试!", err.Error(), c)
			c.Abort()
			return
		}

		if sessionInfo == nil {
			response.TokenError(nil, "网络异常，请稍后重试1038!", "找不到对应session", c)
			c.Abort()
			return
		}

		var userInfo services.UserInfo

		if sessionInfo.OpenID != "" {
			tmpUserInfo, tmpErr := services.GetWxUserItemByOpenId(sessionInfo.OpenID)
			userInfo = tmpUserInfo
			err = tmpErr
		} else {
			response.TokenError(nil, "数据异常!", "openid为空", c)
			c.Abort()
			return
		}

		if err != nil {
			//用户openid查询出来发现没有绑定用户
			if err == services.ERR_USER_NOT_BIND {
				response.TokenError(nil, "信息已变更,请重新登陆1058!", err.Error(), c)
				c.Abort()
				return
			}
			//没有找到记录
			if err == utils.ErrNoRow {
				response.TokenError(nil, "信息已变更,请重新登陆2064!", err.Error(), c)
				c.Abort()
				return
			}

			response.TokenError(nil, "网络异常，请稍后重试3069!", err.Error(), c)
			c.Abort()
			return
		}

		c.Set("userInfo", userInfo)
		c.Next()
	}
}
