package com.keyware.shandan.system.utils;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * 异步的HTTP请求客户端
 *
 * @author Administrator
 */
@Slf4j
@Component
public class AsyncRestTemplate {

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 发起post请求
     *
     * @param url    请求接口
     * @param data   body数据
     * @param header 请求header
     * @return 带监听回调的异步处理
     */
    @Async
    public ListenableFuture<JSONObject> sendAsyncPost(String url, Map<String, Object> data, MultiValueMap<String, String> header) {
        log.debug("用户同步请求：{},body:{}", url, new JSONObject(data).toJSONString());
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        if (header != null) {
            headers.addAll(header);
        }

        HttpEntity<Map<String, Object>> body = new HttpEntity<>(data, headers);
        try {
            JSONObject jsonObject = restTemplate.postForObject(url, body, JSONObject.class);
            if (jsonObject == null) {
                jsonObject = new JSONObject();
            }
            return AsyncResult.forValue(jsonObject);
        } catch (Exception e) {
            return AsyncResult.forExecutionException(e);
        }
    }

    public String sendPost(String url, Map<String, Object> data) {
        log.debug("用户同步请求：{},body:{}", url, new JSONObject(data).toJSONString());
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        params.setAll(data);
        HttpEntity<MultiValueMap<String, Object>> body = new HttpEntity<>(params, headers);

        //设置超时时间
        SimpleClientHttpRequestFactory clientHttpRequestFactory =new SimpleClientHttpRequestFactory();
//        clientHttpRequestFactory.setConnectionRequestTimeout(-1);
        clientHttpRequestFactory.setConnectTimeout(-1);
        clientHttpRequestFactory.setReadTimeout(-1);
        RestTemplate restTemplate1= new RestTemplate();
        restTemplate1.setRequestFactory(clientHttpRequestFactory);


        return restTemplate1.postForObject(url, body, String.class);
    }
}
