package club.trycache.service;

import com.alibaba.fastjson.JSONObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * @Author: trycache
 * @Description RestTemplate服务类
 * @Date 2022/7/20 9:46
 */
@Service
public class RestTemplateService {

    private final static RestTemplate restTemplate;

    static {
        restTemplate = new RestTemplate();
    }

    public static HttpHeaders buildHeaders() {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        return headers;
    }

    public static JSONObject buildParams(Map<String, Object> params) {
        JSONObject param = new JSONObject();
        if (null != params && !params.isEmpty() && params.size() > 0) {
            params.forEach((k, v) -> param.put(k, v));
        }
        return param;
    }

    /**
     * 执行post方法并返回json字符串请求结果
     * @param url
     * @param params
     * @return
     */
    public static String doPost(String url, Map<String, Object> params) {
        HttpHeaders headers = buildHeaders();
        JSONObject param = buildParams(params);
        HttpEntity<JSONObject> requestEntity = new HttpEntity<>(param, headers);
        String result = restTemplate.postForObject(url, requestEntity, String.class);
        return result;
    }

    public static JSONObject doPost4Json(String url, Map<String, Object> params) {
        HttpHeaders headers = buildHeaders();
        JSONObject param = buildParams(params);
        HttpEntity<JSONObject> requestEntity = new HttpEntity<>(param, headers);
        JSONObject result = restTemplate.postForObject(url, requestEntity, JSONObject.class);
        return result;
    }

    public static JSONObject doPost4JsonStr(String url, String jsonStr) {
        HttpHeaders headers = buildHeaders();
        JSONObject param = JSONObject.parseObject(jsonStr);
        HttpEntity<JSONObject> requestEntity = new HttpEntity<>(param, headers);
        JSONObject result = restTemplate.postForObject(url, requestEntity, JSONObject.class);
        return result;
    }

    public static JSONObject doPost4Json(String url) {
        return doPost4Json(url, null);
    }

    public static JSONObject doPost(String url) {
        String result = doPost(url, null);
        return JSONObject.parseObject(result);
    }

}
