package thyyxxk.webserver.utils;

import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import thyyxxk.webserver.entity.ResultVo;

@Slf4j
@Component
@RequiredArgsConstructor
public class RestTemplateUtils {
    private final RestTemplate template;

    public <T> ResultVo<T> get(String url, Object req, Class<T> clazz) {
        return template.exchange(url, HttpMethod.GET, new HttpEntity<>(req), new ParameterizedTypeReference<ResultVo<T>>() {
        }).getBody();
    }

    public <T> ResultVo<T> post(String url, Object req, Class<T> clazz, String logName) {
        ResultVo<T> body = template.exchange(url, HttpMethod.POST, new HttpEntity<>(req), new ParameterizedTypeReference<ResultVo<T>>() {
        }).getBody();
        log.info("{}--------------->\n参数：{}\n返回值：{}", logName, JSONUtil.toJsonStr(req), JSONUtil.toJsonStr(body));
        return body;
    }
}
