/**
 * 核心服务接口sdk（golang版）
 *
 * @desc 啪啪运动 核心服务接口sdk
 * ---------------------------------------------------------------------
 * @author		tang <unphp@qq.com>
 * @date		2020-10-29
 * @copyright	core-utils
 * ---------------------------------------------------------------------
 */
package cooper

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

//NewOauthUserInfoRequest ... 网页授权，获取用户信息
func (that *CooperClient) NewOauthUserInfoRequest() *OauthUserInfoRequest {
	return &OauthUserInfoRequest{
		Request: Request{
			Client:            that,
			publicParamsSlice: []string{
				//...
			},
			apiAddress: "/wxApi/user/info",
		},
	}
}

//OauthUserInfoRequest
type OauthUserInfoRequest struct {
	Request
}

func (that *OauthUserInfoRequest) SetConfig(value string) *OauthUserInfoRequest {
	that.initParams()
	that.params.Set("config", value) //微信相关配置
	return that
}
func (that *OauthUserInfoRequest) SetCode(value string) *OauthUserInfoRequest {
	that.initParams()
	that.params.Set("code", value) //微信code
	return that
}

//Params ...
func (that *OauthUserInfoRequest) Params() (url.Values, error) {
	that.initParams()
	_params := that.params
	if that.publicParamsSlice != nil {
		for _, _v := range that.publicParamsSlice {
			if _params.Get(_v) == "" {
				return nil, errors.New(that.apiAddress + "缺少参数:" + _v)
			}
		}
	}
	return _params, nil
}

//
type OauthUserInfoResponse struct {
	OpenID     string   `json:"openid"`
	Nickname   string   `json:"nickname"`
	Sex        int64    `json:"sex"`
	Province   string   `json:"province"`
	City       string   `json:"city"`
	Country    string   `json:"country"`
	HeadImgURL string   `json:"headimgurl"`
	Privilege  []string `json:"privilege"`
	Unionid    string   `json:"unionid"`
}

//Do ...
func (that *OauthUserInfoRequest) Do() (*OauthUserInfoResponse, error) {
	//返回data
	_data, _err := that.Client.Post(that.apiAddress, that)
	if _err != nil {
		return nil, _err
	}
	//
	_slice := []string{
		"openid", //微信openID
	}
	//
	_sliceData, _ok := _data.(map[string]interface{})
	if !_ok {
		return nil, errors.New(that.apiAddress + "请求响应格式不正确")
	}
	//
	for _, _val := range _slice {
		if _, _ok := _sliceData[_val]; !_ok {
			return nil, errors.New(that.apiAddress + "请求响应参数缺失")
		}
	}
	//
	_str, _err := json.Marshal(_sliceData)
	if _err != nil {
		return nil, errors.New(that.apiAddress + _err.Error())
	}
	//返回结果
	_rs := new(OauthUserInfoResponse)
	_err = json.Unmarshal(_str, &_rs)
	if _err != nil {
		return _rs, errors.New(that.apiAddress + _err.Error())
	}
	return _rs, nil
}
