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 TokenNoLogin() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.Request.Header.Get("Authorization")
		if token == "" {
			token = c.GetString("authorization")
			if token == "" {
				token = c.GetString("Authorization")
			}
		}
		if token == "" {
			response.TokenError(nil, "未登录或非法访问", "token为空", 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, "网络异常，请稍后重试!", "session为空", c)
			c.Abort()
			return
		}

		var userInfo services.UserInfo

		if sessionInfo.OpenID != "" {
			tmpUserInfo, tmpErr := services.GetWxUserItemByOpenId(sessionInfo.OpenID)
			userInfo = tmpUserInfo
			err = tmpErr
			if err != nil && err != services.ERR_NO_USER_RECORD && err != services.ERR_USER_NOT_BIND{
				response.TokenError(nil, "数据异常!", "openid查询用户信息错误", c)
				c.Abort()
				return
			}
		} else {
			//判断pc端登录的情况
			tmpUserInfo, tmpErr := services.GetWxUserItemByUserId(int(sessionInfo.UserID), 3)
			userInfo = tmpUserInfo
			err = tmpErr
			if err != nil {
				response.TokenError(nil, "数据异常!", "userID查询用户信息错误", c)
				c.Abort()
				return
			}
		}

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

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

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