package cooper

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

//NewFaceUserAddRequest ...
func (that *CooperClient) NewFaceUserAddRequest() *FaceUserAddRequest {
	return &FaceUserAddRequest{
		Client:     that,
		apiAddress: "/baiduFace/userAdd",
	}
}

//NewFaceUserUpdateRequest ...
func (that *CooperClient) NewFaceUserUpdateRequest() *FaceUserAddRequest {
	return &FaceUserAddRequest{
		Client:     that,
		apiAddress: "/baiduFace/userUpdate",
	}
}

type FaceUserAddResponse struct {
	FaceToken string                      `json:"face_token"`
	Location  FaceUserAddResponseLocation `json:"location"`
}

type FaceUserAddResponseLocation struct {
	Height   int64   `json:"height"`
	Left     float64 `json:"left"`
	Rotation int64   `json:"rotation"`
	Top      float64 `json:"top"`
	Width    int64   `json:"width"`
}

//FaceUserAddRequest ...
type FaceUserAddRequest struct {
	Client       *CooperClient
	apiAddress   string
	UserId       string `json:"user_id"`
	FaceImageUrl string `json:"face_image_url"` //用户id
	GroupId      string `json:"group_id"`       //用户分组id
	ImageType    string `json:"image_type"`     //
}

//SetExchangeName...
func (that *FaceUserAddRequest) SetFaceImage(faceImageURL, imageType string) *FaceUserAddRequest {
	that.FaceImageUrl = faceImageURL
	that.ImageType = imageType
	return that
}

//SetData...
func (that *FaceUserAddRequest) SetGroupID(groupID int64) *FaceUserAddRequest {
	that.GroupId = utils.ToString(groupID)
	return that
}

func (that *FaceUserAddRequest) SetUserId(userId string) *FaceUserAddRequest {
	that.UserId = userId
	return that
}

//Params ...
func (that *FaceUserAddRequest) Params() (url.Values, error) {
	var m = make(url.Values)
	m.Set("face_image_url", that.FaceImageUrl)
	m.Set("image_type", that.ImageType)
	m.Set("group_id", that.GroupId)
	m.Set("user_id", that.UserId)
	return m, nil
}

//Do ...
func (that *FaceUserAddRequest) Do() (FaceUserAddResponse, error) {
	_rs := FaceUserAddResponse{}
	//
	_data, _err := that.Client.Post(that.apiAddress, that)
	if _err != nil {
		return _rs, _err
	}
	//
	_slice := []string{
		"face_token",
	}
	//
	_sliceData, _ok := _data.(map[string]interface{})
	if !_ok {
		return _rs, errors.New(that.apiAddress + "请求响应格式不正确")
	}
	//
	for _, _val := range _slice {
		if _, _ok := _sliceData[_val]; !_ok {
			return _rs, errors.New(that.apiAddress + "请求响应参数不正确")
		}
	}
	//
	_str, _err := json.Marshal(_sliceData)
	if _err != nil {
		return _rs, errors.New(that.apiAddress + "Umarshal failed!" + _err.Error())
	}
	_err = json.Unmarshal(_str, &_rs)
	if _err != nil {
		return _rs, errors.New(that.apiAddress + "Umarshal failed2!" + _err.Error())
	}
	return _rs, nil
}
