package controllers

import (
	"encoding/json"
	"fmt"
	"net/http"
	"oppmg/common/log"
	"oppmg/protocol"

	"github.com/astaxie/beego"
)

//BaseHeader 请求的header数据
//减少在具体业务方法中使用 this.Ctx.Input.Header("xxxx")
type BaseHeader struct {
	AccessToken  string `json:"access_token"`
	RefreshToken string `json:"refresh_token"`
}

//BaseController 基础
type BaseController struct {
	beego.Controller
	AppHead BaseHeader
}

//Options 实现beego.ControllerInterface 的接口
func (this *BaseController) Options() {

	this.Ctx.Abort(http.StatusBadRequest, "")

}

//Prepare 实现beego.ControllerInterface 的接口
func (this *BaseController) Prepare() {
	this.AppHead.AccessToken = this.Ctx.Input.Header("access_token")
	this.AppHead.RefreshToken = this.Ctx.Input.Header("refresh_token")
	//详细header待定 TODO
	if this.Ctx.Input.RequestBody != nil {
		log.Info(fmt.Sprintf("====>Recv data from client:\nHeadData: %s\n BodyData: %s", this.Ctx.Request.Header, string(this.Ctx.Input.RequestBody)))
	} else {
		log.Info(fmt.Sprintf("====>Recv data from client:\nHeadData: %s ", this.Ctx.Request.Header))
	}

}

//Finish 实现beego.ControllerInterface 的接口
func (this *BaseController) Finish() {
	strByte, _ := json.Marshal(this.Data["json"])
	length := len(strByte)
	if length > 5000 {
		log.Info(fmt.Sprintf("<====Send to client:  RspBodyData: %s......", string(strByte[:5000])))
	} else {
		log.Info(fmt.Sprintf("<====Send to client: RspBodyData: %s", string(strByte)))
	}
}

func (this *BaseController) ResposeJson(msg *protocol.ResponseMessage) {
	this.Data["json"] = msg
	this.ServeJSON()
}