package pass

import (
	"PPOSUtils/utils"
	"encoding/json"
	"errors"
	"net/url"
	"reflect"
)

type Request struct {
	Client            *PassClient
	params            url.Values
	apiAddress        string
	publicParamsSlice []string //必传参数名
}

func (that *Request) initParams() *Request {
	if that.params == nil {
		that.params = make(url.Values)
	}
	return that
}

func (that *Request) GetResponseCode() int64 {
	return that.Client.GetResponseCode()
}

func (that *Request) ParseList(data interface{}) (*struct {
	Count int
	Page  int
	Size  int
	List  interface{}
}, error) {
	_json, _err := json.Marshal(data)
	if _err != nil {
		return nil, _err
	}
	_list := &struct {
		Count int
		Page  int
		Size  int
		List  interface{}
	}{}
	if _err := json.Unmarshal(_json, &_list); _err != nil {
		return nil, _err
	}
	return _list, nil
}

//
func (that *Request) ParseResponeMp(mode interface{}, data interface{}, isMustValidate ...bool) error {
	_mp, _ok := data.(map[string]interface{})
	if !_ok {
		return errors.New(that.apiAddress + "parse response error, data not map")
	}
	v := reflect.ValueOf(mode)
	if !v.IsNil() {
		t := reflect.TypeOf(mode)
		fieldNum := t.Elem().NumField()
		for i := 0; i < fieldNum; i++ {
			_type := t.Elem().Field(i).Type
			_k := t.Elem().Field(i).Tag.Get("json")
			if _k != "" {
				_v, _ok := _mp[_k]
				//非强制性验证字段属性
				if len(isMustValidate) > 0 && isMustValidate[0] == false && !_ok {
					continue
				}
				//强制验证字段必填
				if !_ok {
					return errors.New("response error:" + _k)
				}
				//字段所属类型
				switch _type.String() {
				case "int64":
					v.Elem().Field(i).SetInt(utils.ToInt64(_v))
				case "string":
					v.Elem().Field(i).SetString(utils.ToString(_v, true))
				case "bool":
					if _bool, _ok := _v.(bool); _ok {
						v.Elem().Field(i).SetBool(_bool)
					} else {
						v.Elem().Field(i).SetBool(false)
					}
				}
			}
		}
	}
	return nil
}
