package com.skyversation.poiaddr.util.net;

import com.alibaba.fastjson.JSONObject;
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.LinkedMultiValueMap;
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 requestGetOrPost(HttpMethod httpMethod, String url, JSONObject params, Map<String, String> headerMap, Integer ifReloadSize) {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(10 * 1000);
        requestFactory.setReadTimeout(10 * 1000);
        RestTemplate client = new RestTemplate(requestFactory);
        client.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        HttpHeaders headers = new HttpHeaders();
        //请勿轻易改变此提交方式，大部分的情况下，提交方式都是表单提交
        headers.setContentType(httpMethod == HttpMethod.POST ? MediaType.APPLICATION_JSON : MediaType.APPLICATION_FORM_URLENCODED);
        if (headerMap != null) {
            Set<String> sets = headerMap.keySet();
            for (String key : sets) {
                headers.add(key, headerMap.get(key));
            }
        }
        try {
            if(httpMethod == HttpMethod.POST){
                org.springframework.http.HttpEntity<JSONObject> requestEntity = new org.springframework.http.HttpEntity<>(params, headers);//执行HTTP请求
                return client.exchange(url, httpMethod, requestEntity, String.class);
            }else{
                MultiValueMap<String, String> params2 = new LinkedMultiValueMap<>();
                if(params != null){
                    for(String key:params.keySet()){
                        params2.add(key,params.get(key).toString());
                    }
                }
                org.springframework.http.HttpEntity<MultiValueMap<String, String>> requestEntity = new org.springframework.http.HttpEntity<>(params2, headers);//执行HTTP请求
                return client.exchange(url, httpMethod, requestEntity, String.class);
            }

        } catch (Exception e) {
            if (ifReloadSize > 0) {
                ifReloadSize--;
                return requestGetOrPost(httpMethod,url, params, headerMap, ifReloadSize);
            } else {
                System.err.println("requestGet err:" + e);
                return null;
            }
        }
    }
}
