package com.skyversation.poiaddr.util.net;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.scheduling.annotation.Async;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Set;

public class AddressNetTools {

    private static AddressNetTools instance = new AddressNetTools();

    private AddressNetTools() {
    }

    public synchronized static AddressNetTools getInstance() {
        if (instance == null) {
            instance = new AddressNetTools();
        }
        return instance;
    }

    public String wdSendGetRequest(String urlString) throws Exception {
        HttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(urlString);
        HttpResponse response = httpClient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        return EntityUtils.toString(entity);
    }

    @Async
    public ResponseEntity requestGet(String url, MultiValueMap<String, String> params, Map<String, String> headerMap, Integer ifReloadSize) {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(3 * 1000);
        requestFactory.setReadTimeout(3 * 1000);
        RestTemplate client = new RestTemplate(requestFactory);
        client.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        HttpHeaders headers = new HttpHeaders();
        //请勿轻易改变此提交方式，大部分的情况下，提交方式都是表单提交
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        if (headerMap != null) {
            Set<String> sets = headerMap.keySet();
            for (String key : sets) {
                headers.add(key, headerMap.get(key));
            }
        }

        org.springframework.http.HttpEntity<MultiValueMap<String, String>> requestEntity = new org.springframework.http.HttpEntity<>(params, headers);//执行HTTP请求
        try {
            return client.exchange(url, HttpMethod.GET, requestEntity, String.class);
        } catch (Exception e) {
            if (ifReloadSize > 0) {
                ifReloadSize--;
                return requestGet(url, params, headerMap, ifReloadSize);
            } else {
                System.err.println("requestGet err:" + e);
                return null;
            }
        }
    }
}
