package com.system.utils;

import com.system.handler.FacePlusThrowErrorHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.util.Map;
import java.util.Set;

/**
 * @author Inori
 */
public class HttpUtil {

    private static final Logger log = LoggerFactory.getLogger(HttpUtil.class);

    /**
     * 连接超时时间
     */
    private static final int CONN_TIMEOUT = 10000;

    /**
     * 请求超时时间
     */
    private static final int READ_TIMEOUT = 10000;

    /**
     * 请求工具
     */
    private static RestTemplate restTemplate;


    static {
        //设置超时时间
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(CONN_TIMEOUT);
        requestFactory.setReadTimeout(READ_TIMEOUT);
        restTemplate = new RestTemplate(requestFactory);
        restTemplate.setErrorHandler(new FacePlusThrowErrorHandler());
    }

    /**
     * 设置header公共参数
     */
    private static HttpHeaders initHeader() {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Accept", "application/json");
        headers.add("Content-Type", "application/json; charset=UTF-8");
        return headers;
    }

    /**
     * 设置header参数
     */
    private static void setHeaderParam(HttpHeaders httpHeaders, Map<String, Object> headers) {
        if (!CollectionUtils.isEmpty(headers)) {
            Set<String> keys = headers.keySet();
            for (String key : keys) {
                httpHeaders.add(key, headers.get(key).toString());
            }
        }
    }

    /**
     * 发送Get请求
     */
    public static ResponseEntity<String> httpGet(String url) {
        //初始化header公共参数
        HttpHeaders httpHeaders = initHeader();
        //发送请求
        HttpEntity<String> httpEntity = new HttpEntity<>(null, httpHeaders);
        log.info("【Get请求】Url: {}", url);
        return restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
    }

    /**
     * 发送Get请求
     */
    public static ResponseEntity<String> httpGet(String url, Map<String, Object> param) {
        //初始化header公共参数
        HttpHeaders httpHeaders = initHeader();
        //组装查询参数
        url = setParam(url, param);
        //发送请求
        HttpEntity<String> httpEntity = new HttpEntity<>(null, httpHeaders);
        log.info("【Get请求】Url: {}", url);
        return restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
    }

    private static String setParam(String url, Map<String, Object> param) {
        Set<String> keys = param.keySet();
        StringBuilder builder = new StringBuilder();
        builder.append("?");
        for (String key : keys) {
            builder.append(key).append("=").append(param.get(key)).append("&");
        }
        builder.deleteCharAt(builder.lastIndexOf("&"));
        url = url + builder.toString();
        return url;
    }

    /**
     * 发送Get请求
     */
    public static ResponseEntity<String> httpGet(String url, Map<String, Object> headers, Map<String, Object> param) {
        //如果查询参数为空，则调用不带参数的Get请求
        if (CollectionUtils.isEmpty(param)) {
            return httpGet(url, headers);
        }
        //组装查询参数
        url = setParam(url, param);
        //发送请求
        log.info("【Get请求】Url: {}", url);
        return httpGet(url, headers);
    }

    /**
     * 发送Post请求
     */
    public static ResponseEntity<String> httpPost(String url, String json) {
        //初始化header公共参数
        HttpHeaders httpHeaders = initHeader();
        //发送请求
        log.info("【Post请求】Url: {}", url);
        return toPost(url, httpHeaders, json);
    }

    /**
     * 发送Post请求
     */
    public static ResponseEntity<String> httpPost(String url, Map<String, Object> header, String json) {
        //初始化header公共参数
        HttpHeaders httpHeaders = initHeader();
        setHeaderParam(httpHeaders, header);
        //发送请求
        log.info("【Post请求】Url: {}", url);
        return toPost(url, httpHeaders, json);
    }

    /**
     * 发送请求
     */
    private static ResponseEntity<String> toPost(String url, HttpHeaders httpHeaders, String json) {
        HttpEntity<String> httpEntity = new HttpEntity<>(json, httpHeaders);
        return restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
    }


}