package controllers

import (
	"encoding/json"
	"fmt"
	"github.com/beego/beego/v2/server/web"
	"hongze/hongze_clpt/services"
	"net/http"
	"net/url"
	"strconv"
	"strings"

	"hongze/hongze_clpt/models"
	"hongze/hongze_clpt/utils"
)

//func init() {
//	if utils.RunMode == "release" {
//		logDir := `/data/rdlucklog/hongze_cygx`
//		apiLog = log.Init("20060102.api", logDir)
//	} else {
//		apiLog = log.Init("20060102.api")
//	}
//}

type BaseAuthMobileController struct {
	web.Controller
	User  *models.WxUserItem
	Token string
}

func (this *BaseAuthMobileController) Prepare() {
	fmt.Println("enter prepare")
	method := this.Ctx.Input.Method()
	uri := this.Ctx.Input.URI()
	fmt.Println("Url:", uri)
	if method != "HEAD" {
		if method == "POST" || method == "GET" {
			authorization := this.Ctx.Input.Header("Authorization")
			inviteCompany := this.Ctx.Input.Header("From")
			if authorization == "" {
				authorization = this.GetString("Authorization")
			}
			this.Token = authorization
			if authorization == "" {
				nilWxUser := new(models.WxUserItem)
				this.User = nilWxUser
			} else {
				session, err := models.GetSessionByToken(authorization)
				if err != nil {
					if err.Error() == utils.ErrNoRow() {
						this.JSON(models.BaseResponse{Ret: 408, Msg: "信息已变更,请重新登陆!", ErrMsg: "Token 信息已变更:Token: " + authorization}, false, false)
						this.StopRun()
						return
					}
					this.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "获取用户信息异常,Eerr:" + err.Error()}, false, false)
					this.StopRun()
					return
				}
				if session == nil {
					this.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "sesson is empty "}, false, false)
					this.StopRun()
					return
				}
				//wxUser, err := models.GetWxUserItemByUserId(session.UserId)
				wxUser, err := models.GetWxUserItemByMobile(session.Mobile)
				if err != nil && err != services.ERR_USER_NOT_BIND {
					if err.Error() == utils.ErrNoRow() {
						this.JSON(models.BaseResponse{Ret: 408, Msg: "信息已变更,请重新登陆!", ErrMsg: "获取信息失败 " + strconv.Itoa(session.UserId)}, false, false)
						this.StopRun()
						return
					}
					this.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "获取wx_user信息异常,Eerr:" + err.Error()}, false, false)
					this.StopRun()
					return
				}
				if wxUser == nil {
					this.JSON(models.BaseResponse{Ret: 408, Msg: "网络异常,请稍后重试!", ErrMsg: "admin is empty "}, false, false)
					this.StopRun()
					return
				}
				this.User = wxUser
			}
			this.User.InviteCompany = inviteCompany
			go services.AddCygxPageHistoryRecord(this.User, this.Ctx)
		} else {
			this.JSON(models.BaseResponse{Ret: 408, Msg: "请求异常,请联系客服!", ErrMsg: "POST之外的请求,暂不支持"}, false, false)
			this.StopRun()
			return
		}
	}
}

func (c *BaseAuthMobileController) ServeJSON(encoding ...bool) {
	var (
		hasIndent   = false
		hasEncoding = false
	)
	if web.BConfig.RunMode == web.PROD {
		hasIndent = false
	}
	if len(encoding) > 0 && encoding[0] == true {
		hasEncoding = true
	}
	if c.Data["json"] == nil {
		go utils.SendEmail(utils.APPNAME+" "+utils.RunMode+"异常提醒:", "接口:"+"URI:"+c.Ctx.Input.URI()+";无返回值", utils.EmailSendToUsers)
		return
	}
	baseRes := c.Data["json"].(*models.BaseResponse)
	if baseRes != nil && baseRes.Ret != 200 && baseRes.Ret != 408 && baseRes.IsSendEmail {
		body, _ := json.Marshal(baseRes)
		msgBody := "URI:" + c.Ctx.Input.URI() + "<br/> ErrMsg:" + baseRes.ErrMsg + ";<br/>Msg:" + baseRes.Msg + ";<br/> Body:" + string(body) + ";<br/>" + c.Token
		go utils.SendEmail(utils.APPNAME+" "+utils.RunMode+" 失败提醒", msgBody, utils.EmailSendToUsers)
	}

	c.JSON(c.Data["json"], hasIndent, hasEncoding)
}

func (c *BaseAuthMobileController) JSON(data interface{}, hasIndent bool, coding bool) error {
	c.Ctx.Output.Header("Content-Type", "application/json; charset=utf-8")
	var content []byte
	var err error
	if hasIndent {
		content, err = json.MarshalIndent(data, "", "  ")
	} else {
		content, err = json.Marshal(data)
	}
	if err != nil {
		http.Error(c.Ctx.Output.Context.ResponseWriter, err.Error(), http.StatusInternalServerError)
		return err
	}
	ip := c.Ctx.Input.IP()
	requestBody, _ := url.QueryUnescape(string(c.Ctx.Input.RequestBody))
	c.logUri(content, requestBody, ip)
	//apiLog.Println("请求地址:", c.Ctx.Input.URI(), "Authorization:", c.Ctx.Input.Header("Authorization"), "RequestBody:", requestBody, "ResponseBody", string(content), "IP:", ip)
	if coding {
		content = []byte(utils.StringsToJSON(string(content)))
	}
	return c.Ctx.Output.Body(content)
}

func (c *BaseAuthMobileController) logUri(respContent []byte, requestBody, ip string) {
	authorization := ""
	method := c.Ctx.Input.Method()
	uri := c.Ctx.Input.URI()
	//fmt.Println("Url:", uri)
	if method != "HEAD" {
		if method == "POST" || method == "GET" {
			authorization = c.Ctx.Input.Header("authorization")
			if authorization == "" {
				authorization = c.Ctx.Input.Header("Authorization")
			}
			if authorization == "" {
				newAuthorization := c.GetString("authorization")
				if newAuthorization != `` {
					authorization = "authorization=" + newAuthorization
				} else {
					newAuthorization = c.GetString("Authorization")
					authorization = "authorization=" + newAuthorization
				}
			} else {
				if strings.Contains(authorization, ";") {
					authorization = strings.Replace(authorization, ";", "$", 1)
				}
			}
			if authorization == "" {
				strArr := strings.Split(uri, "?")
				for k, v := range strArr {
					fmt.Println(k, v)
				}
				if len(strArr) > 1 {
					authorization = strArr[1]
					authorization = strings.Replace(authorization, "Authorization", "authorization", -1)
					fmt.Println(authorization)
				}
			}
		}
	}

	utils.ApiLog.Info("uri:%s, authorization:%s, requestBody:%s, responseBody:%s, ip:%s", c.Ctx.Input.URI(), authorization, requestBody, respContent, ip)
	return
}