package org.springblade.common.utils;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springblade.core.oss.model.BladeFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

@Slf4j
public class HttpClientUtil {
	public static String doPost(String url, JSONObject json) {
		try {
			// 包装String 编码为utf-8
			StringEntity entity = new StringEntity(json.toJSONString(),"UTF-8");
			entity.setContentType("application/json"); //设定内容格式
			HttpPost httpPost = new HttpPost(url); //构建请求对象
			httpPost.setEntity(entity);// 包装请求参数
			httpPost.addHeader("ContentType", "application/json;charset=UTF-8");//设定请求头部
			httpPost.addHeader("Authorization", "Basic c2FiZXI6c2FiZXJfc2VjcmV0");
			HttpClient httpclient = HttpClientBuilder.create().build();
			//获取创建请求客户端
			HttpResponse response = httpclient.execute(httpPost);
			//http客户端发起请求
			log.info("http客户端发起请求:"+response);
//			if (response.getStatusLine().getStatusCode() == 200) {
//				//判定返回状态码 是否是200 （成功）
//				String conResult = EntityUtils.toString(response.getEntity());
//				//重请求体中获取返回值
//				log.info("重请求体中获取返回值:"+conResult);
//				return conResult;
//			}

			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity responseEntity = response.getEntity();
				InputStream inputStream = responseEntity.getContent();
				String result = "";
				try (InputStreamReader reader = new InputStreamReader(inputStream, Charset.forName("UTF-8"))) {
					BufferedReader in = new BufferedReader(reader);
					String line;
					while ((line = in.readLine()) != null) {
						result += line;
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				log.info("重请求体中获取返回值:"+result);
				return result;
			}
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		return null;
	}
	public static String doPost1(String url, JSONObject json,String headValue) {
		try {
			// 包装String 编码为utf-8
			StringEntity entity = new StringEntity(json.toJSONString(),"UTF-8");
			entity.setContentType("application/json"); //设定内容格式
			HttpPost httpPost = new HttpPost(url); //构建请求对象
			httpPost.setEntity(entity);// 包装请求参数
			httpPost.addHeader("ContentType", "application/json;charset=UTF-8");//设定请求头部
			httpPost.addHeader("Authorization", "Basic c2FiZXI6c2FiZXJfc2VjcmV0");
			httpPost.addHeader("Blade-Auth",headValue);
			log.info("token:"+headValue);
			HttpClient httpclient = HttpClientBuilder.create().build();
			//获取创建请求客户端
			HttpResponse response = httpclient.execute(httpPost);
			//http客户端发起请求
			log.info("http客户端发起请求:"+response);
//			if (response.getStatusLine().getStatusCode() == 200) {
//				//判定返回状态码 是否是200 （成功）
//				String conResult = EntityUtils.toString(response.getEntity());
//				log.info("重请求体中获取返回值:"+conResult);
//				//重请求体中获取返回值
//				return conResult;
//			}
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity responseEntity = response.getEntity();
				InputStream inputStream = responseEntity.getContent();
				String result = "";
				try (InputStreamReader reader = new InputStreamReader(inputStream, Charset.forName("UTF-8"))) {
					BufferedReader in = new BufferedReader(reader);
					String line;
					while ((line = in.readLine()) != null) {
						result += line;
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				log.info("重请求体中获取返回值:"+result);
				return result;
			}
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		return null;
	}

	public static String doPost2(String url, /*JSONObject*/MultipartFile file) {
		try {
			// 包装String 编码为utf-8
			StringEntity entity = new StringEntity(file.toString());
			entity.setContentEncoding("UTF-8");
			entity.setContentType("application/json"); //设定内容格式
			HttpPost httpPost = new HttpPost(url); //构建请求对象
			httpPost.setEntity(entity);// 包装请求参数
			httpPost.addHeader("ContentType", "application/json;");//设定请求头部
			HttpClient httpclient = HttpClientBuilder.create().build();
			//获取创建请求客户端
			HttpResponse response = httpclient.execute(httpPost);
			//http客户端发起请求
			if (response.getStatusLine().getStatusCode() == 200) {
				//判定返回状态码 是否是200 （成功）
				HttpEntity entity1 = response.getEntity();
				String conResult = EntityUtils.toString(entity1);
				//EntityUtils.
				//重请求体中获取返回值
				return conResult;
			}
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		return null;
	}

	public static String doPostUploadFile(String url, MultipartFile multipartFile) throws Exception {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);// 创建httpPost
		MultipartEntityBuilder builder = MultipartEntityBuilder.create();
		builder.setCharset(java.nio.charset.Charset.forName("UTF-8"));
		builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); //加上此行代码解决返回中文乱码问题
		String fileName = null;
		fileName = multipartFile.getOriginalFilename();
		builder.addBinaryBody("file", multipartFile.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);// 文件流
//        ContentType contentType = ContentType.create(HTTP.PLAIN_TEXT_TYPE, HTTP.UTF_8);
//        for (Map.Entry<String, Object> entry : params.entrySet()) {
//            if (entry.getValue() == null)
//                continue;
//            // 类似浏览器表单提交，对应input的name和value
//            builder.addTextBody(entry.getKey(), entry.getValue().toString(), contentType);
//        }
		HttpEntity entity = builder.build();
		httpPost.setEntity(entity);
		CloseableHttpResponse response = null;
		try {

			response = httpclient.execute(httpPost);
			StatusLine status = response.getStatusLine();
			int state = status.getStatusCode();
			if (state == HttpStatus.SC_OK) {
				HttpEntity responseEntity = response.getEntity();
				String jsonString = EntityUtils.toString(responseEntity);
				return jsonString;
			} else {
				return null;
			}
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		//return null;
	}
	//connect转发后携带请求头


}
