package controllers

import (
	"fmt"
	"hongze/hongze_mobile_admin/models/custom"
	"hongze/hongze_mobile_admin/models/tables/h5_admin_session"
	"hongze/hongze_mobile_admin/services"
	"hongze/hongze_mobile_admin/utils"
	"net/url"
	"strconv"
	"strings"
)

// BaseAuth 需要授权token的基类
type BaseAuth struct {
	BaseCommon
	AdminWx *custom.AdminWx                  `description:"管理员信息"`
	Token   string                           `description:"用户token"`
	Session *h5_admin_session.H5AdminSession `description:"用户session"`
}

func (c *BaseAuth) Prepare() {
	var requestBody string
	method := c.Ctx.Input.Method()
	if method == "GET" {
		requestBody = c.Ctx.Request.RequestURI
	} else {
		requestBody, _ = url.QueryUnescape(string(c.Ctx.Input.RequestBody))
	}
	authorization := c.Ctx.Input.Header("Authorization")

	fmt.Println("requestBody:", requestBody)
	ip := c.Ctx.Input.IP()
	fmt.Println("ip:", ip)

	//apiLog.Println("请求地址:", c.Ctx.Input.URI(), "RequestBody:", requestBody, "IP:", ip, ";authorization:", authorization)
	//if authorization == "" {
	//	cookie := c.Ctx.GetCookie("rddp_access_token")
	//	utils.FileLog.Info("authorization:%s,cookie:%s", authorization, cookie)
	//	authorization = cookie
	//}
	uri := c.Ctx.Input.URI()
	utils.FileLog.Info("URI:%s", uri)
	//if strings.Contains(uri, "/h5adminapi/wechat/login") {
	//	authorization = ""
	//}
	if authorization == "" {
		c.TokenMsgError("请求异常,没有携带token!", "请求异常,没有携带token ")
		return
	}

	session, err := h5_admin_session.GetSessionByToken(authorization)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			c.TokenMsgError("信息已变更,请重新登陆!", "Token 信息已变更:Token: "+authorization)
			return
		}
		c.TokenMsgError("网络异常,请稍后重试!", "获取用户信息异常,Err:"+err.Error())
		return
	}
	if session == nil {
		c.TokenMsgError("网络异常,请稍后重试!", "session is empty")
		return
	}

	c.Session = session
	var adminWx *custom.AdminWx
	if session.OpenId != "" {
		tmpAdminWx, tmpErr := services.GetAdminUserItemByOpenId(session.OpenId)
		adminWx = tmpAdminWx
		err = tmpErr
	} else {
		c.TokenMsgError("数据异常!", "session is empty")
		return
	}
	//wxUser, err := models.GetWxUserItemByUserId(session.UserId)
	//wxUser, err := services.GetWxUserItemByOpenId(session.OpenId)
	if err != nil {
		//没有找到记录
		if err.Error() == utils.ErrNoRow() {
			c.TokenMsgError("信息已变更,请重新登陆!", "获取admin 信息失败 "+strconv.Itoa(session.AdminId))
			return
		}

		//错误信息,账户未绑定,跳转到绑定页面
		if err == services.ERR_ADMIN_NOT_BIND {
			//如果不是登录接口
			if !strings.Contains(uri, "/h5adminapi/admin/login") {
				c.BindMsgError("账户未绑定!", "获取admin_wx信息异常,Err:"+err.Error())
				return
			}
		} else {
			//其他错误信息
			c.TokenMsgError("网络异常,请稍后重试!", "获取admin_wx信息异常,Err:"+err.Error())
			return
		}

	}
	if adminWx == nil {
		c.TokenMsgError("网络异常,请稍后重试!", "admin is empty")
		return
	}
	if adminWx.AdminId > 0 && adminWx.Enabled != 1 {
		c.BindMsgError("账户信息异常!", "账户状态异常,强制退出")
		return
	}
	c.AdminWx = adminWx

	c.Token = authorization
}