package com.wms_main.repository.http;

import com.wms_main.repository.http.entity.HttpRequest;
import com.wms_main.repository.http.entity.HttpResponse;
import com.wms_main.repository.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.time.LocalDateTime;

/**
 * api 客户端
 */
@Component
@Slf4j
public class HttpClient {

    /**
     * 发送一个 Get 请求
     * @param request 请求数据
     * @return 响应数据
     */
    public HttpResponse httpGet(HttpRequest request) {
        HttpResponse response = new HttpResponse();
        String url = request.getUrl();
        if(StringUtils.isEmpty(url)) {
            // 请求地址没传
            response.setSuccess(false);
            response.setResponseCode(999);
            response.setException(new Exception("请求地址为空"));
            return response;
        }
        if(StringUtils.isNotEmpty(request.getData())) {
            url += request.getData();
        }
        response.setRequestUrl(url);
        response.setRequestMessage(request.getData());
        try {
            CloseableHttpClient httpClient = HttpClientBuilder.create().build();
            HttpGet getRequest = new HttpGet(url + request.getData());
            getRequest.setHeader("Content-Type", request.getContentType());
            getRequest.setHeader("Authorization", request.getToken());
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(request.getTimeout())
                    .setConnectionRequestTimeout(request.getTimeout())
                    .setSocketTimeout(request.getTimeout()).build();
            getRequest.setConfig(requestConfig);
            StopWatch watch = new StopWatch();
            response.setRequestTime(LocalDateTime.now());
            watch.start();
            CloseableHttpResponse getResponse = httpClient.execute(getRequest);
            watch.stop();
            response.setResponseTime(LocalDateTime.now());
            response.setUseTime(watch.getTotalTimeMillis());
            response.setResponseCode(getResponse.getStatusLine().getStatusCode());
            BufferedReader reader = new BufferedReader(new InputStreamReader(getResponse.getEntity().getContent()));
            String line;
            StringBuilder result = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }
            reader.close();
            httpClient.close();
            response.setSuccess(true);
            response.setResponseMessage(result.toString());
            return response;
        } catch (Exception e) {
            response.setSuccess(false);
            response.setResponseCode(999);
            response.setException(e);
            return response;
        }
    }


    /**
     * 发送一个 Post 请求
     * @param request 请求数据
     * @return 响应数据
     */
    public HttpResponse httpPost(HttpRequest request) {
        log.info("请求信息{}", StringUtils.objectToString(request));
        HttpResponse response = new HttpResponse();
        String url = request.getUrl();
        if(StringUtils.isEmpty(url)) {
            // 请求地址没传
            response.setSuccess(false);
            response.setResponseCode(999);
            response.setException(new Exception("请求地址为空"));
            return response;
        }
        if(StringUtils.isEmpty(request.getData())) {
            request.setData("{}");
        }
        response.setRequestUrl(url);
        response.setRequestMessage(request.getData());
        try {
            CloseableHttpClient httpClient = HttpClientBuilder.create().build();
            HttpPost postRequest = new HttpPost(url);
            postRequest.setHeader("Content-Type", request.getContentType());
            postRequest.setHeader("Authorization", request.getToken());
            postRequest.setEntity(new StringEntity(request.getData()));
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(request.getTimeout())
                    .setConnectionRequestTimeout(request.getTimeout())
                    .setSocketTimeout(request.getTimeout()).build();
            postRequest.setConfig(requestConfig);
            StopWatch watch = new StopWatch();
            response.setRequestTime(LocalDateTime.now());
            watch.start();
            CloseableHttpResponse postResponse = httpClient.execute(postRequest);
            watch.stop();
            response.setResponseTime(LocalDateTime.now());
            response.setUseTime(watch.getTotalTimeMillis());
            response.setResponseCode(postResponse.getStatusLine().getStatusCode());
            BufferedReader reader = new BufferedReader(new InputStreamReader(postResponse.getEntity().getContent()));
            String line;
            StringBuilder result = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }
            reader.close();
            httpClient.close();
            response.setSuccess(true);
            response.setResponseMessage(result.toString());
            return response;
        } catch (Exception e) {
            response.setSuccess(false);
            response.setResponseCode(999);
            response.setException(e);
            return response;
        }
    }

    /**
     * 发送一个 delete 请求
     * @param request 请求数据
     * @return 响应数据
     */
    public HttpResponse httpDelete(HttpRequest request) {
        HttpResponse response = new HttpResponse();
        String url = request.getUrl();
        if(StringUtils.isEmpty(url)) {
            // 请求地址没传
            response.setSuccess(false);
            response.setResponseCode(999);
            response.setException(new Exception("请求地址为空"));
            return response;
        }
        if(!StringUtils.isEmpty(request.getData())) {
            url += request.getData();
        }
        response.setRequestUrl(url);
        response.setRequestMessage(request.getData());
        try {
            CloseableHttpClient httpClient = HttpClientBuilder.create().build();
            HttpDelete deleteRequest = new HttpDelete(url + request.getData());
            deleteRequest.setHeader("Content-Type", request.getContentType());
            deleteRequest.setHeader("Authorization", request.getToken());
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(request.getTimeout())
                    .setConnectionRequestTimeout(request.getTimeout())
                    .setSocketTimeout(request.getTimeout()).build();
            deleteRequest.setConfig(requestConfig);
            StopWatch watch = new StopWatch();
            response.setRequestTime(LocalDateTime.now());
            watch.start();
            CloseableHttpResponse getResponse = httpClient.execute(deleteRequest);
            watch.stop();
            response.setResponseTime(LocalDateTime.now());
            response.setUseTime(watch.getTotalTimeMillis());
            response.setResponseCode(getResponse.getStatusLine().getStatusCode());
            BufferedReader reader = new BufferedReader(new InputStreamReader(getResponse.getEntity().getContent()));
            String line;
            StringBuilder result = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }
            reader.close();
            httpClient.close();
            response.setSuccess(true);
            response.setResponseMessage(result.toString());
            return response;
        } catch (Exception e) {
            response.setSuccess(false);
            response.setResponseCode(999);
            response.setException(e);
            return response;
        }
    }
}
