package ppos

import (
	"PPOSUtils/orm"
	"PPOSUtils/utils"
	"errors"
	"fmt"
	"runtime/debug"
)

//logicInterface 接口
type logicInterface interface {
	CreatePostion(appID, mpID int64, params ...interface{}) error
}

type dbInterface interface {
	NewDB(mp utils.Mp) *orm.DataBase
}

//logic 逻辑接口
type Logic struct {
	ParamsCustom      *paramsCustom
	paramsParseStatus bool
	afterMiddleware   []func()
}

func (that *Logic) AddAfterMiddleware(afterMiddleware func()) {
	if that.afterMiddleware == nil {
		that.afterMiddleware = []func(){}
	}
	that.afterMiddleware = append(that.afterMiddleware, afterMiddleware)
}

func (that *Logic) SetCompayID(value int64) {
	that.initParamsCustom()
	that.ParamsCustom.SetCompayID(value)
}

func (that *Logic) SetBusinessID(value int64) {
	that.initParamsCustom()
	that.ParamsCustom.SetBusinessID(value)
}

func (that *Logic) SetStadiumID(value int64) {
	that.initParamsCustom()
	that.ParamsCustom.SetStadiumID(value)
}

func (that *Logic) SetSalesID(value int64) {
	that.initParamsCustom()
	that.ParamsCustom.SetSalesID(value)
}

func (that *Logic) SetData(key string, value interface{}) {
	that.initParamsCustom()
	that.ParamsCustom.SetData(key, value)
}

//SetAppID 设置paas隔离参数值
func (that *Logic) SetAppID(appID int64) {
	that.initParamsCustom()
	if that.GetAppID() == 0 {
		that.ParamsCustom.SetData("app_id", appID)
	}
}

func (that *Logic) SetPosition(name string, value interface{}) {
	that.initParamsCustom()
	that.ParamsCustom.SetPositionData(name, value)
}

func (that *Logic) SetMpID(mpID int64) {
	that.initParamsCustom()
	that.ParamsCustom.SetData("mp_id", mpID)
}

func (that *Logic) SetParamsInstance(value *paramsCustom) *Logic {
	that.ParamsCustom = value
	return that
}

func (that *Logic) GetPostion(appID ...int64) utils.Mp {
	that.initParamsCustom()
	return that.ParamsCustom.GetPostion(appID...)
}

func (that *Logic) GetParams() utils.Mp {
	that.initParamsCustom()
	return that.ParamsCustom.GetCustom()
}

func (that *Logic) GetAppID() int64 {
	that.initParamsCustom()
	_name := "app_id"
	_v := that.ParamsCustom.getCustomValue(_name)
	return utils.ToInt64(_v)
}

func (that *Logic) GetMpID() int64 {
	that.initParamsCustom()
	_name := "mp_id"
	_v := that.ParamsCustom.getCustomValue(_name)
	return utils.ToInt64(_v)
}

func (that *Logic) GetCompanyID(param ...interface{}) (value int64) {
	if len(param) > 0 {
		defer func() {
			if _err := recover(); _err != nil {
				value = utils.ToInt64(param[0])
				return
			}
		}()
	}
	_name := "company_id"
	return that.getMustValue(_name)
}

func (that *Logic) GetMemberID(param ...interface{}) (value int64) {
	if len(param) > 0 {
		defer func() {
			if _err := recover(); _err != nil {
				value = utils.ToInt64(param[0])
				return
			}
		}()
	}
	_name := "member_id"
	value = that.getMustValue(_name)
	return
}

func (that *Logic) GetBusinessID(param ...interface{}) (value int64) {
	if len(param) > 0 {
		defer func() {
			if _err := recover(); _err != nil {
				value = utils.ToInt64(param[0])
				return
			}
		}()
	}
	_name := "business_id"
	return that.getMustValue(_name)
}

func (that *Logic) GetPersonnelID(param ...interface{}) (value int64) {
	if len(param) > 0 {
		defer func() {
			if _err := recover(); _err != nil {
				value = utils.ToInt64(param[0])
				return
			}
		}()
	}
	_name := "personnel_id"
	value = that.getMustValue(_name)
	return
}

func (that *Logic) GetBranchID(param ...interface{}) (value int64) {
	if len(param) > 0 {
		defer func() {
			if _err := recover(); _err != nil {
				value = utils.ToInt64(param[0])
				return
			}
		}()
	}
	_name := "branch_id"
	value = that.getMustValue(_name)
	return
}

func (that *Logic) GetAccountType() int64 {
	_name := "account_type"
	return that.getMustValue(_name)
}

func (that *Logic) GetAccountID(param ...interface{}) (value int64) {
	if len(param) > 0 {
		defer func() {
			if _err := recover(); _err != nil {
				value = utils.ToInt64(param[0])
				return
			}
		}()
	}
	_name := "account_id"
	value = that.getMustValue(_name)
	return
}

//获取场馆ID - param为0 代表 该参数允许为0
func (that *Logic) GetStadiumID(param ...interface{}) (value int64) {
	if len(param) > 0 {
		defer func() {
			if _err := recover(); _err != nil {
				value = utils.ToInt64(param[0])
				return
			}
		}()
	}
	_name := "stadium_id"
	value = that.getMustValue(_name)
	return
}

func (that *Logic) GetSalesID(param ...interface{}) (value int64) {
	if len(param) > 0 {
		defer func() {
			if _err := recover(); _err != nil {
				value = utils.ToInt64(param[0])
				return
			}
		}()
	}
	_name := "sales_id"
	value = that.getMustValue(_name)
	return
}

func (that *Logic) getMustValue(name string) int64 {
	that.initParamsCustom()
	_v := that.ParamsCustom.getCustomValue(name)
	if _v == nil {
		panic(name + " is nil")
	}
	_value := utils.ToInt64(_v)
	if _value == 0 {
		panic(name + " is zero")
	}
	return _value
}

//GetData ...
func (that *Logic) GetData(name string) interface{} {
	that.initParamsCustom()
	_v := that.ParamsCustom.getCustomValue(name)
	return _v
}

//newUtilsActon
func (that *Logic) NewUtilsActon(requestMiddleware func() interface{}) utils.UtilsAction {
	middleware := &utils.ActionStruct{}
	middleware.SetRequestMiddleware(func(appID int64, params ...interface{}) (rs interface{}) {
		//异常捕获，友好返回错误提示
		defer func() {
			if _err := recover(); _err != nil {
				rs = ThrowException(4001000004, errors.New("recover:"+fmt.Sprint(_err)))
				debug.PrintStack()
				return
			}
		}()
		//
		_rs := func() interface{} {
			//请求结束前，执行的函数方法
			defer that.close()
			//初始化
			if _err := that.initLogic(params...); _err != nil {
				return ThrowException(4001000004, _err)
			}
			that.SetAppID(appID)
			//执行逻辑方法
			return requestMiddleware()
		}()
		return _rs
	})
	middleware.SetResponMiddleware(func(appID int64, rs interface{}, excp utils.UtilsException, params ...interface{}) (interface{}, utils.UtilsException) {
		if excp != nil {
			if len(params) > 0 {
				//db.Log(appID, excp.GetTraceAsString(), utils.ToString(params[0]))
			} else {
				//db.Log(appID, excp.GetTraceAsString())
			}
		}
		return rs, excp
	})
	return middleware
}

func (that *Logic) close() {
	if that.afterMiddleware != nil {
		for _, _afterMiddleware := range that.afterMiddleware {
			func() {
				defer func() {
					if _err := recover(); _err != nil {
						//
					}
				}()
				_afterMiddleware()
			}()
		}
	}
}

func (that *Logic) initParamsCustom() {
	if that.ParamsCustom == nil {
		that.ParamsCustom = new(paramsCustom)
	}
}

func (that *Logic) initLogic(params ...interface{}) error {
	if that.paramsParseStatus {
		return nil
	}
	that.initParamsCustom()
	if len(params) > 0 {
		switch _paramsType := params[0].(type) {
		case []interface{}:
			if len(_paramsType) > 0 {
				_paramsCustomMp, _ok := _paramsType[0].(utils.Mp)
				if !_ok {
					return errors.New("接口请求失败，'公共参数'格式错误," + utils.TypeOf(_paramsType[0]))
				}
				for _k, _v := range _paramsCustomMp {
					that.ParamsCustom.SetData(_k, _v)
				}
			}
			if len(_paramsType) > 1 {
				_paramsPostionMp, _ok := _paramsType[1].(utils.Mp)
				if !_ok {
					return errors.New("接口请求失败，'公共参数'格式错误," + utils.TypeOf(_paramsType[1]))
				}
				for _k, _v := range _paramsPostionMp {
					that.SetPosition(_k, _v)
				}
			}
		case utils.Mp:
			for _k, _v := range _paramsType {
				that.ParamsCustom.SetData(_k, _v)
			}
		}
	}
	that.paramsParseStatus = true
	return nil
}

//CreatePostion ...
func (that *Logic) Init(appID int64, params ...interface{}) error {
	if that.paramsParseStatus {
		return nil
	}
	if _err := that.initLogic(params...); _err != nil {
		return _err
	}
	that.SetAppID(appID)
	that.paramsParseStatus = true
	return nil
}
