package xiaoqu.home.open.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Component
public class HttpUtil {

	private static Logger logger = LoggerFactory.getLogger(HttpUtil.class);

	public static final String POST = "POST";

	public static final String GET = "GET";

	public static final String UTF8 = "UTF-8";

	public static final String GBK = "GBK";

	public static final String GB2312 = "GB2312";

	public static final String ContextTypeXml = "text/xml";

	public String downfile(String url, String encoding) {
		InputStream in = null;
		try {
			URL postUrl = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) postUrl.openConnection();
			conn.setRequestProperty("User-Agent", "Internet Explorer");
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setRequestMethod(GET);
			conn.setUseCaches(false);
			conn.setInstanceFollowRedirects(true);
			conn.setConnectTimeout(20000);
			conn.setReadTimeout(30000);
			in = conn.getInputStream();
			return read(in, encoding);
		} catch (Exception e) {
			logger.error("下载文件出错,url:" + url, e);
		} finally {
			close(in);
		}
		return null;
	}

	private void close(InputStream in) {
		if (null != in) {
			try {
				in.close();
			} catch (Exception e) {
			}
		}
	}

	private void close(OutputStream out) {
		if (null != out) {
			try {
				out.close();
			} catch (Exception e) {

			}
		}
	}

	public String getResponse(String url, String method, String encoding, String body) {
		OutputStream out = null;
		InputStream in = null;
		try {
			URL postUrl = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) postUrl.openConnection();
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setRequestMethod(method);
			conn.setUseCaches(false);
			conn.setInstanceFollowRedirects(true);
			conn.setConnectTimeout(20000);
			conn.setReadTimeout(20000);
			conn.connect();
			out = conn.getOutputStream();
			out.write(body.getBytes());
			out.flush();
			in = conn.getInputStream();
			String result = read(in, encoding);
			return result;
		} catch (MalformedURLException e) {
			logger.error("请求地址有误, url:" + url, e);
			throw new RuntimeException(e);
		} catch (Exception e) {
			logger.error("IO错误,url:" + url + ",body:" + body, e);
			throw new RuntimeException(e);
		} finally {
			close(in);
			close(out);
		}
	}





	public String read(InputStream in, String encoding) {
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(in, encoding), 1024 * 1024);
			StringBuilder builder = new StringBuilder();
			String line = null;
			while (null != (line = reader.readLine())) {
				builder.append(line);
			}
			return builder.toString();
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		} finally {
			close(in);
		}
	}
	public static String get(String urlStr){
		StringBuffer sb=new StringBuffer();
		try {
			URL url = new URL(urlStr);
			InputStream is = url.openStream();
			InputStreamReader isr = new InputStreamReader(is,"utf-8");
			BufferedReader reader = new BufferedReader(isr);
			String lines;
			while ((lines = reader.readLine()) != null) {
				lines = new String(lines.getBytes(), "utf-8");
				sb.append(lines);
			}
			is.close();
		} catch(IOException e) {
			System.out.println(e);
		}
		return sb.toString();
	}
	public static String postJson(String serverUrl,String paramJson){
		StringBuffer sb = new StringBuffer("");
		//logger.info("发送数据json:"+paramJson);
		try {
			String dataStr = paramJson;
			byte[] data =dataStr.getBytes();
			URL url = new URL(serverUrl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();


			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setRequestProperty("Accept-Charset", "UTF-8");
			conn.setRequestProperty("Charset", "UTF-8");
			conn.setRequestProperty("Content-Length", String.valueOf(data.length));
			//conn.setRequestProperty("Content-Type", "application/json");
			conn.setRequestProperty("Content-type", "application/json;charset=UTF-8");
			conn.connect();


			OutputStream  out = conn.getOutputStream();
			out.write(data);
			out.flush();
			out.close();


			BufferedReader reader = new BufferedReader(new InputStreamReader(
					conn.getInputStream()));
			String lines;
			while ((lines = reader.readLine()) != null) {
				lines = new String(lines.getBytes(), "utf-8");
				sb.append(lines);
			}

			/*InputStream in = conn.getInputStream();
			String a = null;
			try {
				//System.out.println(in.available());
				byte[] data1 = new byte[in.available()];
				in.read(data1);
				//System.out.println(data1);
				//System.out.println(new String(data1));
				result = new String(data1);
			} catch (Exception e1) {
				e1.printStackTrace();
			}*/
		} catch (Exception e) {
			logger.error(e.getMessage());
			//e.printStackTrace();
		}
		return sb.toString();
	}
	public static String postJson123123(String serverUrl,String paramJson){
		StringBuffer sb = new StringBuffer("");
		try {
			//创建连接
			URL url = new URL(serverUrl);
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();

			/*
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setRequestMethod("POST");
			connection.setUseCaches(false);
			connection.setInstanceFollowRedirects(true);
			connection.setRequestProperty("Charset", "UTF-8");
			connection.setRequestProperty("Content-Type", "application/json");
			connection.connect();*/

			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setUseCaches(false);
			connection.setRequestMethod("POST");
			connection.setRequestProperty("Connection", "Keep-Alive");
			connection.setRequestProperty("Charset", "UTF-8");
			connection.setRequestProperty("Content-Length", String.valueOf(paramJson.getBytes().length));
			connection.setRequestProperty("Content-Type", "application/json");
			connection.connect();

			DataOutputStream out = new DataOutputStream(
					connection.getOutputStream());
			out.writeBytes(paramJson);
			out.flush();
			out.close();
			//读取响应
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));
			String lines;
			while ((lines = reader.readLine()) != null) {
				lines = new String(lines.getBytes(), "utf-8");
				sb.append(lines);
			}
			reader.close();
			connection.disconnect();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sb.toString();
	}


	private void sendMessage(String mobiles,String hardwareNo){
		String timestemp = getTimestemp();
		String userName="qufangbian";
		String password="014455";
		String key = getKey(userName,password,   timestemp);
		StringBuffer url= new StringBuffer();
		url.append("http://www.youxinyun.com:3070/Platform_Http_Service/servlet/SendSms?");
		url.append("UserName=").append(userName);
		url.append("&Key=").append(key);
		url.append("&Timestemp=").append(timestemp);
		url.append("&Content=").append("【趣方便】设备缺纸,请更换,编号:").append(hardwareNo);
		url.append("&CharSet=").append("utf-8");
		url.append("&Mobiles=").append(mobiles);
		String s=get(url.toString());
		System.out.println(s);
	}

	String getKey(String userName, String password, String timestemp) {
		String key = "";
		try {
			MessageDigest mdTemp = MessageDigest.getInstance("MD5");
			mdTemp.update(userName.getBytes());
			mdTemp.update(password.getBytes());
			mdTemp.update(timestemp.getBytes());
			key = bytesToHexString(mdTemp.digest());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return key;
	}
	String getTimestemp() {
		return (new SimpleDateFormat("MMddHHmmss")).format(new Date());
	}
	String bytesToHexString(byte[] src) {
		String resultString = "";
		StringBuilder stringBuilder = new StringBuilder("");
		if (src == null || src.length<= 0) {
			return null;
		}
		for(int i = 0; i<src.length; i++) {
			int v = src[i] &0xFF;
			String hv = Integer.toHexString(v);
			if(hv.length() < 2) {
				stringBuilder.append(0);
			}
			stringBuilder.append(hv);
		}
		resultString = stringBuilder.toString();
		stringBuilder = null;
		return resultString;
	}


	public static void main(String args[])  throws Exception {
		System.out.println(get("http://mini.eastday.com/mobile/171204142640683.html"));
	}



	public static String post(String requestUrl, String accessToken, String params)
			throws Exception {
		String contentType = "application/x-www-form-urlencoded";
		return HttpUtil.post(requestUrl, accessToken, contentType, params);
	}

	public static String post(String requestUrl, String accessToken, String contentType, String params)
			throws Exception {
		String encoding = "UTF-8";
		if (requestUrl.contains("nlp")) {
			encoding = "GBK";
		}
		return HttpUtil.post(requestUrl, accessToken, contentType, params, encoding);
	}

	public static String post(String requestUrl, String accessToken, String contentType, String params, String encoding)
			throws Exception {
		String url = requestUrl + "?access_token=" + accessToken;
		return HttpUtil.postGeneralUrl(url, contentType, params, encoding);
	}

	public static String postGeneralUrl(String generalUrl, String contentType, String params, String encoding)
			throws Exception {
		URL url = new URL(generalUrl);
		// 打开和URL之间的连接
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setRequestMethod("POST");
		// 设置通用的请求属性
		connection.setRequestProperty("Content-Type", contentType);
		connection.setRequestProperty("Connection", "Keep-Alive");
		connection.setUseCaches(false);
		connection.setDoOutput(true);
		connection.setDoInput(true);

		// 得到请求的输出流对象
		DataOutputStream out = new DataOutputStream(connection.getOutputStream());
		out.write(params.getBytes(encoding));
		out.flush();
		out.close();

		// 建立实际的连接
		connection.connect();
		// 获取所有响应头字段
		Map<String, List<String>> headers = connection.getHeaderFields();
		// 遍历所有的响应头字段
		for (String key : headers.keySet()) {
			System.err.println(key + "--->" + headers.get(key));
		}
		// 定义 BufferedReader输入流来读取URL的响应
		BufferedReader in = null;
		in = new BufferedReader(
				new InputStreamReader(connection.getInputStream(), encoding));
		String result = "";
		String getLine;
		while ((getLine = in.readLine()) != null) {
			result += getLine;
		}
		in.close();
		System.err.println("result:" + result);
		return result;
	}


}
