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

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

//NewMiniServerLoginRequest ... 商家小程序登录，获取用户信息（服务商模式）
func (that *AuthClient) NewMiniServerLoginRequest(openAppId string) *MiniUserInfoRequest {
	return &MiniUserInfoRequest{
		Request: Request{
			Client:            that,
			publicParamsSlice: []string{
				//...
			},
			apiAddress: "/wechat/open/xcxLogin?open_app_id=" + openAppId,
		},
	}
}

//MiniUserInfoRequest
type MiniUserInfoRequest struct {
	Request
}

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
}

//Do ...
func (that *MiniUserInfoRequest) Do() (*MiniUserInfoResponse, error) {
	//返回data
	_data, _err := that.Client.GetData(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
}
