package com.yanzuoguang.wxxcx.user.getpluginpid;

import com.alibaba.fastjson.TypeReference;
import com.yanzuoguang.util.helper.CheckerHelper;
import com.yanzuoguang.util.helper.HttpHelper;
import com.yanzuoguang.util.helper.JsonHelper;
import com.yanzuoguang.wxxcx.base.*;

/**
 * 通过 wx.pluginLogin 接口获得插件用户标志凭证 code 后传到开发者服务器 转换
 *
 * @author 李贤军
 */
public class WxXcxAuthGetPluginOpenPidRequest implements WxXcxRequestUrl, WxXcxRequestUrlPara, WxXcxRequestPostFormData {

    private final WxXcxConfig wxXcxConfig;
    private final WxXcxRequest wxXcxRequest;
    private final WxXcxAccessToken accessToken;
    private final WxXcxAuthGetPluginOpenPidReq req;

    public WxXcxAuthGetPluginOpenPidRequest(WxXcxConfig wxXcxConfig, WxXcxRequest wxXcxRequest, WxXcxAccessToken accessToken, WxXcxAuthGetPluginOpenPidReq req) {
        this.wxXcxConfig = wxXcxConfig;
        this.wxXcxRequest = wxXcxRequest;
        this.accessToken = accessToken;
        this.req = req;
    }

    @Override
    public String getUrl() {
        return wxXcxConfig.getBaseUrl() + wxXcxConfig.getAuthGetPluginOpenPIdUrl() + "?" + this.getUrlPara();
    }

    @Override
    public String getUrlPara() {
        return HttpHelper.getUrlParameter(accessToken);
    }

    @Override
    public String getPost() {
        return HttpHelper.getUrlParameter(req);
    }

    public WxXcxAuthGetPluginOpenPidRes getResponse() {
        checkParam(req);
        return this.wxXcxRequest.request(this, response -> {
            WxXcxAuthGetPluginOpenPidRes ret = JsonHelper.deserialize(response, new TypeReference<WxXcxAuthGetPluginOpenPidRes>() {
            });
            WxXcxAssert.assertBaseError(ret);
            return ret;
        });
    }

    private void checkParam(WxXcxAuthGetPluginOpenPidReq req) {
        CheckerHelper.newInstance()
                .notBlankCheck(WxXcxAccessTokenField.FIELD_ACCESS_TOKEN, req.getAccess_token())
                .notBlankCheck("code", req.getCode())
                .checkException();
    }
}