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

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

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

//MiniServerGetTokenRequest
type MiniServerGetTokenRequest struct {
	Request
}

func (that *MiniServerGetTokenRequest) SetAuthorizerAppId(value string) *MiniServerGetTokenRequest {
	that.initParams()
	that.params.Set("authorizer_appid", value) //小程序的AppID (授权方)
	return that
}

//Params ...
func (that *MiniServerGetTokenRequest) 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 *MiniServerGetTokenRequest) Do() (string, error) {
	//返回data
	_data, _err := that.Client.GetData(that.apiAddress, that)
	if _err != nil {
		return "", _err
	}
	//
	_sliceData, _ok := _data.(map[string]interface{})
	if !_ok {
		return "", errors.New(that.apiAddress + "请求响应格式不正确")
	}
	//返回结果
	_token := utils.ToString(_sliceData["result"])
	if _token == "" {
		return "", errors.New("token获取失败")
	}
	return _token, nil
}
