package org.jeecg.common.util;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.codec.digest.DigestUtils;

import com.alibaba.fastjson.JSONObject;

public class  HttpHelper {
	 public static JSONObject httpFilePost(String uploadUrl,String token, File file) throws Exception {
		 String LINEND = "\r\n";
		 String boundary = UUID.randomUUID().toString();
		 FileInputStream fileInputStream = new FileInputStream(file);
	     URL url = new URL(uploadUrl);
	     HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
	     httpURLConnection.setDoInput(true);
	     httpURLConnection.setUseCaches(false);
	     httpURLConnection.setDoOutput(true);
	     httpURLConnection.setRequestMethod("POST");
	     httpURLConnection.setRequestProperty("connection", "keep-alive");
	     httpURLConnection.setRequestProperty("Charsert", "UTF-8");
	     httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
	     httpURLConnection.setRequestProperty("token", token);
	     httpURLConnection.setRequestProperty("Accept","*/*");
	     DataOutputStream outStream = new DataOutputStream(httpURLConnection.getOutputStream());
         StringBuilder stringBuilder = new StringBuilder();
         stringBuilder.append("--").append(boundary).append(LINEND);
         stringBuilder.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + LINEND);
         stringBuilder.append("Content-Type: " + HttpURLConnection.guessContentTypeFromName(file.getName()) + LINEND);
         stringBuilder.append("Content-Transfer-Encoding: binary"+ LINEND);
         stringBuilder.append(LINEND);
         outStream.write(stringBuilder.toString().getBytes());
    	 InputStream is = new FileInputStream(file);
    	 byte[] buffer = new byte[1024];
    	 int len = 0;
    	 while ((len = is.read(buffer)) != -1){
    		 outStream.write(buffer, 0, len);
    	 }
    	 is.close();
    	 outStream.write(LINEND.getBytes());
    	 byte[] end_data = ("--" + boundary + "--" + LINEND).getBytes();
    	 outStream.write(end_data);
    	 outStream.flush();
         fileInputStream.close();
         JSONObject responseMsg = readStream(httpURLConnection.getInputStream());
         outStream.close();
         httpURLConnection.disconnect();    
         return responseMsg;
	 }
	 
	 
	 public static JSONObject httpPost(String uploadUrl,String token,JSONObject jsob) throws Exception {
		 URL url = new URL(uploadUrl);
	     HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
	     httpURLConnection.setDoInput(true);
	     httpURLConnection.setUseCaches(false);
	     httpURLConnection.setDoOutput(true);
	     httpURLConnection.setRequestMethod("POST");
	     httpURLConnection.setRequestProperty("Content-Type","application/json");
	     httpURLConnection.setRequestProperty("charset","UTF-8");
	     httpURLConnection.setRequestProperty("token", token);
         OutputStream os = httpURLConnection.getOutputStream();
         os.write(jsob.toString().getBytes());
         os.flush();
         os.close();
         JSONObject responseMsg = readStream(httpURLConnection.getInputStream());
      	 httpURLConnection.disconnect();
      	 return responseMsg;
		 
	 }
	 
	 
	 public static JSONObject httpTokenPost(String uploadUrl,String appkey,String cid,String secret) throws Exception {
		 URL url = new URL(uploadUrl);
	     HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
	     httpURLConnection.setDoInput(true);
	     httpURLConnection.setUseCaches(false);
	     httpURLConnection.setDoOutput(true);
	     httpURLConnection.setRequestMethod("POST");
	     httpURLConnection.setRequestProperty("Content-Type","application/json");
	     httpURLConnection.setRequestProperty("charset","UTF-8");
	     httpURLConnection.setRequestProperty("appkey", appkey);
	     long l = System.currentTimeMillis();
	     Map<String, Object> map = new HashMap<String, Object>();
	     map.put("role", 1);
		 map.put("name", "dmy06");
	     map.put("userId", "2108");//OA用户体系的用户id
	     map.put("cid", cid);
	     String s1 = JSONObject.toJSONString(map);
	     String s2 = s1 + "&time=" + l + "&secret="+secret;
	     String newMd5 = DigestUtils.md5Hex(s2);
	     String s4 = s1 + "&time=" + l + "&md5=" + newMd5;
	     // 写入请求体
	     byte[] requestBodyBytes = s4.getBytes("UTF-8");
	     OutputStream outputStream = httpURLConnection.getOutputStream();
	     outputStream.write(requestBodyBytes);
	     outputStream.flush();
	     outputStream.close();
	     JSONObject responseMsg = readStream(httpURLConnection.getInputStream());
	     httpURLConnection.disconnect();
	     return responseMsg;
		 
	 }
	 
	 
	 private static JSONObject readStream(InputStream inputStream) throws Exception {
		 ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
	     byte[] buffer = new byte[1024];
	     int bytesRead;
	     while ((bytesRead = inputStream.read(buffer)) != -1) {
	    	 outputStream.write(buffer, 0, bytesRead);
	     }
	     byte[] bytes = outputStream.toByteArray();
	     String result = new String(bytes, "UTF-8");
	     outputStream.close();
	     return JSONObject.parseObject(result);
	}
}
