/**
 * 核心服务接口sdk（golang版）
 *
 * @desc 啪啪运动 核心服务接口sdk
 * ---------------------------------------------------------------------
 * @author		tang <tangzhifu@papa.com.cn>
 * @date		2021-11-22
 * @copyright	core-utils
 * ---------------------------------------------------------------------
 */
package cooper

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

//NewMiniUserInfoRequest ... 小程序登录，获取用户信息
func (that *CooperClient) NewMiniUserInfoRequest() *MiniUserInfoRequest {
	return &MiniUserInfoRequest{
		Request: Request{
			Client:            that,
			publicParamsSlice: []string{
				//...
			},
			apiAddress: "/wxApi/miniProgram/login",
		},
	}
}

//NewMiniServerUserInfoRequest ... 商家小程序登录，获取用户信息（服务商模式）
func (that *CooperClient) NewMiniServerUserInfoRequest() *MiniUserInfoRequest {
	return &MiniUserInfoRequest{
		Request: Request{
			Client:            that,
			publicParamsSlice: []string{
				//...
			},
			apiAddress: "/wxApi/openPlat/miniLogin",
		},
	}
}

//MiniUserInfoRequest
type MiniUserInfoRequest struct {
	Request
}

func (that *MiniUserInfoRequest) SetConfig(value string) *MiniUserInfoRequest {
	that.initParams()
	that.params.Set("config", value) //微信相关配置
	return that
}
func (that *MiniUserInfoRequest) SetCode(value string) *MiniUserInfoRequest {
	that.initParams()
	that.params.Set("code", value) //微信code
	return that
}
func (that *MiniUserInfoRequest) SetAuthorizerAppId(value string) *MiniUserInfoRequest {
	that.initParams()
	that.params.Set("authorizer_appid", value) //小程序的 AppID (授权方)
	return that
}

//Params ...
func (that *MiniUserInfoRequest) 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 MiniUserInfoResponse struct {
	OpenID     string `json:"openid"`      // 用户唯一标识
	SessionKey string `json:"session_key"` // 会话密钥
	UnionID    string `json:"unionid"`     // 用户在开放平台的唯一标识符，在满足UnionID下发条件的情况下会返回
}

//Do ...
func (that *MiniUserInfoRequest) Do() (*MiniUserInfoResponse, 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(MiniUserInfoResponse)
	_err = json.Unmarshal(_str, &_rs)
	if _err != nil {
		return _rs, errors.New(that.apiAddress + _err.Error())
	}
	return _rs, nil
}
