package controllers

import (
	"encoding/json"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/cache"
	"github.com/astaxie/beego/context"
	"github.com/astaxie/beego/validation"
	"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/infrastructure/utils"
	"gitlab.fjmaimaimai.com/mmm-go/partner/pkg/protocol"
	"strconv"
)

//缓存
var CacheSms = cache.NewMemoryCache()

var (
	clientId     = "pdf233Znkjo"
	clientSecret = "oHexnmeomYdo19NCmdwne83dfj"
)

type BaseController struct {
	beego.Controller
}

func (controller BaseController) JsonUnmarshal(v interface{}) error {
	body := controller.Ctx.Input.GetData("requestBody").([]byte)
	return json.Unmarshal(body, v)
}

func (controller BaseController) GetLimitInfo() (offset int, limit int) {
	offset, _ = controller.GetInt("offset")
	limit, _ = controller.GetInt("limit")
	return
}

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

	return
}

func (this *BaseController) Resp(msg *protocol.ResponseMessage) {
	this.Data["json"] = msg
	this.Ctx.Input.SetData("outputData", msg)
	this.ServeJSON()
}

func (this *BaseController) RespH5(msg *protocol.ResponseMessage) {
	if msg.Errno != 0 {
		msg.Errno = -1
	}
	this.Data["json"] = msg
	this.Ctx.Input.SetData("outputData", msg)
	this.ServeJSON()
}

//获取请求头信息
func (this *BaseController) GetRequestHeader(ctx *context.Context) *protocol.RequestHeader {
	h := &protocol.RequestHeader{}
	h.AccessToken = ctx.Input.Header("x-mmm-accesstoken")
	h.AppProject = ctx.Input.Header("x-mmm-appproject")
	h.DeviceType, _ = strconv.Atoi(ctx.Input.Header("x-mmm-devicetype"))
	h.Sign = ctx.Input.Header("x-mmm-sign")
	h.Uuid = ctx.Input.Header("x-mmm-uuid")
	h.TimeStamp = ctx.Input.Header("x-mmm-timestamp")
	h.Version = ctx.Input.Header("x-mmm-version")
	h.UserId, _ = strconv.ParseInt(ctx.Input.Header("x-mmm-id"), 10, 64)

	if len(h.AccessToken) > 0 {
		if claim, err := utils.ParseJWTToken(h.AccessToken); err == nil {
			h.UserId = claim.UserId
			h.CompanyId = claim.CompanyId
			h.AdminType = claim.AdminType
		}
	}
	return h
}