package util;

import com.alibaba.fastjson.JSONObject;
import common.Constant;
import common.Resp;
import exception.HttpException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

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

public class HttpUtil {
	public static Resp apiGetJsonX(String uri, JSONObject parameters, JSONObject headers) throws HttpException, IOException {
		String resp = getJsonX(uri, parameters, headers);
		return Tools.toJavaClass(resp, Resp.class);
	}

	public static String getJsonX(String uri, JSONObject paramMap, JSONObject headers) throws IOException {
		String reqURL = uri;

		if (paramMap != null) {
			StringBuilder queryParams = new StringBuilder();
			for (String key : paramMap.keySet()) {
				if (queryParams.length() > 0) {
					queryParams.append('&');
				}
				queryParams.append(URLEncoder.encode(key, Constant.DEFAULT_ENCODING)).append('=')
						.append(URLEncoder.encode(paramMap.get(key).toString(), Constant.DEFAULT_ENCODING));
			}
			reqURL += '?' + queryParams.toString();
		}

		HttpGet httpGet = new HttpGet(reqURL);

		if (headers != null) {
			for (String key : headers.keySet()) {
				httpGet.setHeader(key, headers.getString(key));
			}
		}

		return doHttp(httpGet);
	}

	/**
	 * 至信链api请求
	 * @param uri 请求路径
	 * @param parameters 请求参数
	 * @param headers 请求头
	 * @return 至信链api统一的相应格式
	 * @throws Exception
	 */
	public static Resp apiPostJsonX(String uri, JSONObject parameters, JSONObject headers) throws IOException {
		String resp = postJsonX(uri, parameters, headers);
		return Tools.toJavaClass(resp, Resp.class);
	}

	public static String postJsonX(String uri, JSONObject parameters, JSONObject headers) throws IOException {
		HttpPost httpPost = initPost(uri, headers);

		if (parameters != null) {
			StringEntity entity = new StringEntity(parameters.toJSONString(), Constant.DEFAULT_ENCODING);
			entity.setContentType(Constant.CONTENT_TYPE);
			httpPost.setEntity(entity);
		}

		return doHttp(httpPost);
	}

	public static HttpPost initPost(String uri, JSONObject headers) {
		HttpPost httpPost = new HttpPost(uri);

		if (headers != null) {
			for (String key : headers.keySet()) {
				httpPost.setHeader(key, headers.getString(key));
			}
		}

		return httpPost;
	}

	public static String doHttp(HttpRequestBase request) throws IOException {
		try (CloseableHttpClient httpClient = HttpClients.createDefault();
			 CloseableHttpResponse httpResponse = httpClient.execute(request)) {

			int statusCode = httpResponse.getStatusLine().getStatusCode();
			if (statusCode == HttpStatus.SC_OK) {
				HttpEntity responseEntity = httpResponse.getEntity();
				return EntityUtils.toString(responseEntity, Constant.DEFAULT_ENCODING);
			}

			throw new IOException("HTTP request failed with msg: " + httpResponse);
		}
	}

	public static Resp formData(String url, JSONObject headers, JSONObject params, File file) throws IOException {
		HttpPost httpPost = initPost(url, headers);

		MultipartEntityBuilder builder = MultipartEntityBuilder.create();
		// 添加文本字段
		for (String key : params.keySet()) {
			builder.addTextBody(key, params.getString(key), ContentType.create("text/plain", StandardCharsets.UTF_8));
		}
		// 添加文件字段（假设fileContent是文件内容，filename是文件名）
		builder.addBinaryBody("file", file);

		HttpEntity multipartEntity = builder.build();
		httpPost.setEntity(multipartEntity);

		return Tools.toJavaClass(doHttp(httpPost), Resp.class);
	}
}