package com.sino.rrs.action;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import sun.misc.BASE64Encoder;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sino.publicclass.base.BaseAction;
import com.sino.weixin.oauth.util.Constants;
import com.sino.weixin.oauth.util.HttpsUtil;

public class DownLoadImageAction extends BaseAction{

	public void upload() throws Exception {
		String orderId = getParameter("orderId", "");
		String state=getParameter("state","");
		String photo_1 = getParameter("image_0", "");
		String photo_2 = getParameter("image_1", "");
		String photo_3 = getParameter("image_2", "");
		String photo_4 = getParameter("image_3", "");
		
		String imagePath_1_stream = photo_1.equals("") ? "" : downLoadWeixinImage(photo_1);
	    String imagePath_2_stream = photo_2.equals("") ? "" : downLoadWeixinImage(photo_2);
	    String imagePath_3_stream = photo_3.equals("") ? "" : downLoadWeixinImage(photo_3);
	    String imagePath_4_stream = photo_4.equals("") ? "" : downLoadWeixinImage(photo_4);
		
		JSONObject httpResult = null;
		boolean flag=false;
		
		JSONObject bodyJson = new JSONObject();
		  bodyJson.put("orderId",orderId);
		  bodyJson.put("state", state);
		  bodyJson.put("photo_1",imagePath_1_stream);
		  bodyJson.put("photo_2",imagePath_2_stream);
		  bodyJson.put("photo_3",imagePath_3_stream);
		  bodyJson.put("photo_4",imagePath_4_stream);
		  bodyJson.put("action",8);
	 
		  httpResult=JSONObject.parseObject(HttpsUtil.doPost(Constants.url,bodyJson,"UTF-8"));
		  if(httpResult.size()>0){
			  if(httpResult.getIntValue("errorCode")==0){
				  flag=true;
			  }
		  }
		  httpResult.put("code", flag);
		  response.setContentType("text/html;charset=UTF-8");
		  response.getWriter().print(httpResult.toJSONString());
		  setNext(false);
	}
	
	
	 public String downLoadWeixinImage(String mediaId) {
	       InputStream is = null;
	       String url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token="
	               + Constants.ACCESS_TOKEN + "&media_id=" + mediaId;
	       
	       try {
	           URL urlGet = new URL(url);
	           HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
	           http.setRequestMethod("GET"); // 必须是get方式请求
	           http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
	           http.setRequestProperty("Charset", "UTF-8"); 
	           http.setDoOutput(true);
	           http.setDoInput(true);
	           System.setProperty("sun.net.client.defaultConnectTimeout", "10000");// 连接超时30秒
	           System.setProperty("sun.net.client.defaultReadTimeout", "10000"); // 读取超时30秒
	           http.connect();
	           String contentType=http.getContentType();
	           // 获取文件转化为byte流
	           is = http.getInputStream();
	           return readInputStream(is);  //生成字节数组
	       } catch (Exception e) {
	           e.printStackTrace();
	       }
	       return null;
	   }

	   /**

	    * 获取下载图片信息（jpg）
	    * 
	    * @param mediaId
	    *            文件的id
	    * @throws Exception
	    */

	   public String readInputStream(InputStream input) throws Exception {
	       byte[] data = new byte[1024];
	       int len = 0;
	       ByteArrayOutputStream outSteam = new ByteArrayOutputStream(); 
	       try {
	           while ((len = input.read(data)) != -1) {
	               outSteam.write(data, 0, len);  
	           }
	          
	           byte[] bytes= outSteam.toByteArray();
	           String str = new BASE64Encoder().encode(bytes);
	           return str;
	       } catch (IOException e) {
	           e.printStackTrace();
	       } finally {
	           if (input != null) {
	               try {
	            	   input.close();
	               } catch (IOException e) {
	                   e.printStackTrace();
	               }
	           }
	           if (outSteam != null) {
	               try {
	            	   outSteam.close();
	               } catch (IOException e) {
	                   e.printStackTrace();
	               }
	           }
	       }
	       return null;
	   }
	   
	   public static void main(String[] args) throws Exception {
//		   DownLoadImageAction a=new DownLoadImageAction();
		//   a.upload();
//		  System.out.println(a.downLoadWeixinImage("-1IZPDHgsisuImsj8JIhj-nhJIRasjV4FYVw3ge3Tsz9FAwjQaFdQvoiRo-ZzT8l"));
		   JSONObject json1 = new JSONObject();
//		   JSONObject json2 = new JSONObject();
		   JSONArray jsonArray=new JSONArray();
		   for(int i =1;i<5;i++){
			   JSONObject map = new JSONObject();
			   map.put("q1"+i, "12"+i);
			   map.put("q2"+i, "13"+i);
			   jsonArray.add(map);
		   }
		   json1.put("q", "12");
		   json1.put("er", jsonArray);
		   System.out.println(json1);
		   
	   }
}
