package com.tzld.piaoquan.growth.common.component;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.nio.charset.StandardCharsets;

@Slf4j
@Component
public class ProxyHttpPoolClient {

    @Autowired
    @Qualifier("proxyHttpClient")
    private CloseableHttpClient httpClient;

    public String get(String url) throws IOException {
        HttpGet httpGet = new HttpGet(url);
        return request(httpGet);
    }

    public String post(String url) throws IOException {
        HttpPost httpPost = new HttpPost(url);
        return request(httpPost);
    }


    public String post(String url, String json) throws IOException {
        HttpPost httpPost = new HttpPost(url);
        if (StringUtils.isBlank(json)) {
            return request(httpPost);
        }
        StringEntity entity = new StringEntity(json, StandardCharsets.UTF_8);
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        return request(httpPost);
    }


    public String post(String url, String json, String contentType) throws IOException {
        HttpPost httpPost = new HttpPost(url);
        if (StringUtils.isBlank(json)) {
            return request(httpPost);
        }
        StringEntity entity = new StringEntity(json, StandardCharsets.UTF_8);
        entity.setContentEncoding("UTF-8");
        entity.setContentType(contentType);
        httpPost.setEntity(entity);
        return request(httpPost);
    }

    public String post(String url, File file) throws IOException {
        HttpPost uploadFile = new HttpPost(url);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addBinaryBody("media", file);
        uploadFile.setEntity(builder.build());
        return request(uploadFile);
    }

    public String request(HttpRequestBase request) throws IOException {
        int retry = 0;
        while (retry <= 3) {
            try {
                retry++;
                HttpEntity entity = null;
                CloseableHttpResponse response = request((HttpUriRequest) request);
                if (response == null) {
                    log.error("call api exception no response");
                    throw new RuntimeException("call api exception no response");
                }
                entity = response.getEntity();
                String content = null;
                if (entity != null) {
                    content = EntityUtils.toString(entity, "UTF-8");
                }
                int httpStatus = response.getStatusLine().getStatusCode();
                if (httpStatus == HttpStatus.SC_OK) {
                    return content;
                }
                String path = request.getURI().toString();
                log.error("http call api {} fail response status {} content {}", path, httpStatus, content);
            } catch (Exception e) {
                log.error("request error", e);
            }
        }
        return null;
    }


    public CloseableHttpResponse request(HttpUriRequest request) {
        try {
            return httpClient.execute(request);
        } catch (Exception e) {
            String path = request.getURI().toString();
            if (e instanceof SocketTimeoutException) {
                log.error(String.format("http timeout request url = %s .", path));
            }
            throw new RuntimeException(String.format("http exception request url = %s ", path), e);
        }
    }


}
