package cn.com.poc.user.wecom.api;

import cn.com.poc.common.utils.http.LocalHttpClient;
import cn.com.poc.user.wecom.domain.WecomLoginInfoResponse;
import cn.com.poc.user.wecom.domain.WecomUserInfo3rd;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.StringEntity;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;

@Service
public class WecomServiceApi implements WecomBaseApi {

    public WecomUserInfo3rd getUserInfo3rd(String suiteAccessToken, String code) {
        HttpUriRequest httpUriRequest = RequestBuilder.get()
                .setUri(QY_BASE_URI + "/cgi-bin/service/getuserinfo3rd")
                .addParameter("suite_access_token", suiteAccessToken)
                .addParameter("code", code)
                .build();
        return LocalHttpClient.executeJsonResult(httpUriRequest, WecomUserInfo3rd.class);
    }

    public WecomUserInfo3rd getUserDetail3rd(String suiteAccessToken, String userTicket) {
        String jsonData = String.format("{\"user_ticket\":\"%1$s\"}", userTicket);
        HttpUriRequest httpUriRequest = RequestBuilder.post()
                .setHeader(JSON_HEADER)
                .addParameter("suite_access_token", suiteAccessToken)
                .setUri(QY_BASE_URI + "/cgi-bin/service/getuserdetail3rd")
                .setEntity(new StringEntity(jsonData, StandardCharsets.UTF_8))
                .build();
        return LocalHttpClient.executeJsonResult(httpUriRequest, WecomUserInfo3rd.class);
    }

    public WecomLoginInfoResponse getLoginInfo(String providerAccessToken, String authCode) {
        String jsonData = String.format("{\"auth_code\":\"%1$s\"}", authCode);
        HttpUriRequest httpUriRequest = RequestBuilder.post()
                .setHeader(JSON_HEADER)
                .addParameter("access_token", providerAccessToken)
                .setUri(QY_BASE_URI + "/cgi-bin/service/get_login_info")
                .setEntity(new StringEntity(jsonData, StandardCharsets.UTF_8))
                .build();
        return LocalHttpClient.executeJsonResult(httpUriRequest, WecomLoginInfoResponse.class);
    }
}
