package cooper

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

//NewMQ ...
func (that *CooperClient) NewFaceSearchRequest() *FaceSearchRequest {
	return &FaceSearchRequest{
		Client:     that,
		apiAddress: "/baiduFace/search",
	}
}

type FaceSearchResponse struct {
	FaceToken string                        `json:"face_token"` //list
	UserList  []*FaceSearchResponseUserList `json:"user_list"`  //list
}

type FaceSearchResponseUserList struct {
	GroupId  string  `json:"group_id"`  //
	UserId   string  `json:"user_id"`   //
	Score    float64 `json:"score"`     //
	UserInfo string  `json:"user_info"` //
}

//FaceSearchRequest ...
type FaceSearchRequest struct {
	Client       *CooperClient
	apiAddress   string
	FaceImageUrl string `json:"face_image_url"` //用户id
	GroupIds     string `json:"group_ids"`      //用户分组id
	IsCache      int64  `json:"is_cache"`       //
}

//SetExchangeName...
func (that *FaceSearchRequest) SetFaceImage(faceImageURL string, isCache int64) *FaceSearchRequest {
	that.FaceImageUrl = faceImageURL
	that.IsCache = isCache
	return that
}

//SetData...
func (that *FaceSearchRequest) SetGroupID(groupID string) *FaceSearchRequest {
	that.GroupIds = groupID
	return that
}

//Params ...
func (that *FaceSearchRequest) Params() (url.Values, error) {
	var m = make(url.Values)
	m.Set("face_image_url", that.FaceImageUrl)
	m.Set("is_cache", utils.ToString(that.IsCache, true))
	m.Set("group_ids", that.GroupIds)
	return m, nil
}

//Do ...
func (that *FaceSearchRequest) Do() (*FaceSearchResponse, error) {
	_rs := &FaceSearchResponse{}
	//
	_data, _err := that.Client.Post(that.apiAddress, that)
	if _err != nil {
		return _rs, _err
	}
	//
	_slice := []string{
		"face_token",
		"user_list",
	}
	//
	_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 + "请求响应参数不正确")
		}
	}
	_userList := []*FaceSearchResponseUserList{}
	//
	if utils.TypeOf(_sliceData["user_list"]) != "nil" {
		_list, _ok := _sliceData["user_list"].([]interface{})
		if !_ok {
			return _rs, errors.New(that.apiAddress + "user_list type err, type:" + utils.TypeOf(_sliceData["user_list"]))
		}
		for _, _v := range _list {
			_faceSearchResponseUserList := &FaceSearchResponseUserList{}
			if _err := utils.MapToStruct(_v, _faceSearchResponseUserList); _err != nil {
				return _rs, errors.New(that.apiAddress + "map to struct error:" + _err.Error())
			}
			_userList = append(_userList, _faceSearchResponseUserList)
		}
	}
	//
	_rs.FaceToken = utils.ToString(_sliceData["face_token"])
	_rs.UserList = _userList
	return _rs, nil
}
