package ppos

import (
	//"PPOSModule/ac/db"
	"PPOSUtils/utils"
	"errors"
)

type ParamsInterface interface {
	CreateMpApi(params ...interface{}) error    //控制器传入的公共参数
	SetPosition(name string, value interface{}) //
	GetPostion(appID ...int64) utils.Mp         //orm隔离字段
	GetParams() utils.Mp                        //令牌扩展参数
	SetAppID(appID int64)                       //
	SetMpID(mpID int64)
	SetJwtStr(jwt string)
	GetJwtType() int64
}

//paramsBase 公共参数：paasID
type paramsBase struct {
	paramsSlice []string
	paramsMp    utils.Mp
	postionMp   utils.Mp //会话相关的隔离字段
}

func (that *paramsBase) SetAppID(appID int64) {
	that.init()
	that.paramsMp.Set("app_id", appID)
	//设置隔离字段
	that.postionMp.Set("app_id", appID)
}

func (that *paramsBase) SetMpID(mpID int64) {
	that.init()
	that.paramsMp.Set("mp_id", mpID)
}
func (that *paramsBase) SetJwtStr(jwt string) {
	that.init()
	that.paramsMp.Set("jwt_str", jwt)
}
func (that *paramsBase) GetJwtType() int64 {
	return utils.ToInt64(that.paramsMp.Get("jwt_type"))
}

func (that *paramsBase) init() {
	if that.postionMp == nil {
		that.paramsSlice = []string{
			//"app_id",
			"mp_id",
		}
		that.paramsMp = utils.NewMP()
		that.postionMp = utils.NewMP()
	}
}

//get 会话相关的隔离字段
func (that *paramsBase) GetPostion(appID ...int64) utils.Mp {
	that.init()
	if that.postionMp == nil {
		that.postionMp = utils.NewMP()
	}
	return that.postionMp
}

//get 会话相关的隔离字段
func (that *paramsBase) GetParams() utils.Mp {
	that.init()
	return that.paramsMp
}

func (that *paramsBase) SetPosition(name string, value interface{}) {
	that.init()
	that.postionMp.Set(name, value)
}

func (that *paramsBase) CreateMpApi(params ...interface{}) error {
	that.init()
	if len(params) > 0 {
		_paramsMp, _ok := params[0].(utils.Mp)
		if !_ok {
			return errors.New("接口请求失败，'公共参数'格式错误," + utils.TypeOf(_paramsMp))
		}
		for _, _v := range that.paramsSlice {
			if !_paramsMp.Has(_v) {
				return errors.New("接口请求失败，'公共参数'" + _v + "缺失")
			}
		}
		for _k, _v := range _paramsMp {
			//fmt.Println(_k, "=========", _v)
			that.paramsMp.Set(_k, _v)
			//that.postionMp.Set(_k, _v)
		}
	}
	return nil
}
