package controllers

import (
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/validation"
	"oppmg/common/log"
	"oppmg/protocol"
	"strconv"
)

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

//Prepare 实现beego.ControllerInterface 的接口
func (this *BaseController) Prepare() {
	p := this.Ctx.Input.GetData("RouterPattern")
	fmt.Println("====>r:", p)
}

func (this *BaseController) GetAppHead() (appHead protocol.BaseHeader) {
	appHead.AccessToken = this.Ctx.Input.Header(protocol.HeaderAccessToken)
	appHead.RefreshToken = this.Ctx.Input.Header(protocol.HeaderRefreshToken)
	return

}

//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()
}

func (this *BaseController) GetCompanyId() int64 {
	v := this.Ctx.Input.GetData(protocol.HeaderCompanyid)
	companyid, _ := strconv.ParseInt(fmt.Sprint(v), 10, 64)

	if beego.BConfig.RunMode != "prod" && companyid == 0 {
		companyid, _ = strconv.ParseInt(this.Ctx.Input.Header("x-mmm-cid"), 10, 64)
	}
	return companyid
}

func (this *BaseController) GetUserId() int64 {
	v := this.Ctx.Input.GetData(protocol.HeaderUserid)
	userid, _ := strconv.ParseInt(fmt.Sprint(v), 10, 64)

	if beego.BConfig.RunMode != "prod" && userid == 0 {
		userid, _ = strconv.ParseInt(this.Ctx.Input.Header("x-mmm-uid"), 10, 64)
	}
	return userid
}

//Valid  valid struct
func (this *BaseController) Valid(obj interface{}) (result bool, msg *protocol.ResponseMessage) {
	/*校验*/
	var err error
	valid := validation.Validation{}
	result, err = valid.Valid(obj)
	if err != nil {
		msg = protocol.BadRequestParam("1")
		return
	}
	if !result {
		msg = protocol.BadRequestParam("2")
		return
	}

	return
}