package com.tofly.common.core.util;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Joiner;
import com.google.common.collect.Maps;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class HttpURL {
	
	public static String  FILE_URL_PREFIX="FILE_URL_PREFIX";

	public static String getContent(String path, String param) throws IOException {
		// 打开连接
		URL url = new URL(path);
		URLConnection urlConnection = url.openConnection();
		HttpURLConnection httpUrlConnection = (HttpURLConnection) urlConnection;
		httpUrlConnection.setRequestProperty("Charset", "UTF-8");
		httpUrlConnection.setRequestProperty("Content-Type","application/json;charset=UTF-8");
		if (param != null) {
			// 以POST方式处理
			httpUrlConnection.setDoOutput(true);
			httpUrlConnection.setDoInput(true);
			httpUrlConnection.setUseCaches(false);
			httpUrlConnection.setRequestMethod("POST");
			// 发送post请求
			OutputStream outputStream = httpUrlConnection.getOutputStream();
			PrintWriter printWriter = new PrintWriter(outputStream);
			if (param != null) {
				printWriter.write(param);
			}
			printWriter.flush();
			printWriter.close();
			outputStream.close();
		} else {
			// 默认以GET方式处理
		}

		// 接收处理结果反馈
		String resultString = "";
		// long startTime = System.currentTimeMillis();
		InputStream inputStream = httpUrlConnection.getInputStream();
		// long endTime = System.currentTimeMillis();
		// System.out.println(endTime - startTime);

		int responseCode = httpUrlConnection.getResponseCode();
		if (responseCode == HttpURLConnection.HTTP_OK) {
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
			String line = bufferedReader.readLine();
			while (line != null) {
				resultString += line;
				line = bufferedReader.readLine();
			}
			bufferedReader.close();
		} else {
			// TODO: 改为日志
			resultString="服务返回异常：" + responseCode;
		}
		inputStream.close();
		httpUrlConnection.disconnect();
		return resultString;
	}

	public static byte[] getContentInputStream(String path, String param) throws IOException {
		// 打开连接
		URL url = new URL(path);
		URLConnection urlConnection = url.openConnection();
		HttpURLConnection httpUrlConnection = (HttpURLConnection) urlConnection;
		httpUrlConnection.setRequestProperty("Charset", "UTF-8");
		if (!StringUtil.isEmpty(param)) {
			// 以POST方式处理
			httpUrlConnection.setDoOutput(true);
			httpUrlConnection.setDoInput(true);
			httpUrlConnection.setUseCaches(false);
			httpUrlConnection.setRequestMethod("POST");
			// 发送post请求
			OutputStream outputStream = httpUrlConnection.getOutputStream();
			PrintWriter printWriter = new PrintWriter(outputStream);
			if (param != null) {
				printWriter.write(param);
			}
			printWriter.flush();
			printWriter.close();
			outputStream.close();
		} else {
			// 默认以GET方式处理
		}
		InputStream inputStream = httpUrlConnection.getInputStream();

		byte[] flieByte=null;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		int size = 0;
		byte[] buf = new byte[10240];
		while ((size = inputStream.read(buf)) > 0) {
			out.write(buf, 0, size);
			out.flush();
		}
		flieByte = out.toByteArray();
		out.close();
		inputStream.close();
		httpUrlConnection.disconnect();
		return flieByte;
	}

	
	
	public static String getContent(String path, Map param) throws IOException {
		/*throw new IOException();*/
		JSONObject obj = new JSONObject(param);
		return getContent(path,obj.toString());
		
	}

	/**
	 * 获得path部分<br>
	 *
	 * @param uriStr URI路径
	 * @return path
	 */
	public static String getPath(String uriStr) {
		URI uri = null;
		try {
			uri = new URI(uriStr);
		} catch (URISyntaxException e) {
			System.out.println(e.getMessage());
			return "";
		}
		return uri.getPath();
	}



	public static Map getParameterMap(HttpServletRequest request) {
		// 参数Map
		Map properties = request.getParameterMap();
		// 返回值Map
		Map returnMap = new HashMap();
		Iterator entries = properties.entrySet().iterator();
		Map.Entry entry;
		String name = "";
		String value = "";
		while (entries.hasNext()) {
			entry = (Map.Entry) entries.next();
			name = (String) entry.getKey();
			Object valueObj = entry.getValue();
			if(null == valueObj){
				value = "";
			}else if(valueObj instanceof String[]){
				String[] values = (String[])valueObj;
				for(int i=0;i<values.length;i++){
					value = values[i] + ",";
				}
				value = value.substring(0, value.length()-1);
			}else{
				value = valueObj.toString();
			}
			returnMap.put(name, value);
		}
		return returnMap;
	}


	public static String asUrlParams(Map<String, String> source){
		Map<String, String> tmp = Maps.newHashMap();
		// java8 语法
		source.forEach((k, v) -> {
			if (k != null){
				try {
					tmp.put(k, URLEncoder.encode(v, "utf-8"));
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}
		});
		return Joiner.on("&").useForNull("").withKeyValueSeparator("=").join(tmp);
	}



	public static void main(String[] args) throws IOException {

	}
}
