package com.iamberry.wechat.tools;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import sun.misc.BASE64Decoder;

public class WeChatIOTUtil {
	
	/**
	 * 获取设备的deviceid和二维码
	 * @param url
	 * @param charset
	 * @param timeout
	 * @return
	 */
	public static String sendGet(String url, String charset, int timeout)  
    {  
      String result = "";  
      try  
      {  
        URL u = new URL(url);  
        try  
        {  
          URLConnection conn = u.openConnection();  
          conn.connect();  
          conn.setConnectTimeout(timeout);  
          BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset));  
          String line="";  
          while ((line = in.readLine()) != null)  
          {  
             
            result = result + line;  
          }  
          in.close();  
        } catch (IOException e) {  
          return result;  
        }  
      }  
      catch (MalformedURLException e)  
      {  
        return result;  
      }  
         
      return result;  
    } 
	
	/*
	用法：
	需要先获取access_token
	product_id为微信硬件平台生成
	String access_token="l5HeZ40kiJZq1vogAbOcE9yoyNEmPWOlfI877t-_6WQizVA8WNhZM_C3oscv0MFgkEkF04k6Nb1AFJJlCIfm9ZA9CB5cCbg_ytWpNFdDfWu1Pt5gxrJ2rZwceD5NTihhRBQgAHAHRG";//  
    String product_id="29439";  
    String data = test_yingjian.sendGet("https://api.weixin.qq.com/device/getqrcode?access_token="+access_token+"&product_id="+product_id, "utf-8", 30000);  
    System.out.println("获取设备的deviceid和二维码:"+data);  */
	
	/**
	 * post请求方法
	 * @param url
	 * @param charset
	 * @param timeout
	 * @return
	 */
	public static String sendPost(String requrl,String param){  
        URL url;  
         String sTotalString="";    
       try {  
           url = new URL(requrl);  
            URLConnection connection = url.openConnection();   
               
            connection.setRequestProperty("accept", "*/*");  
            connection.setRequestProperty("connection", "Keep-Alive");  
            connection.setRequestProperty("Content-Type", "text/xml");  
           // connection.setRequestProperty("Content-Length", body.getBytes().length+"");  
            connection.setRequestProperty("User-Agent",  
                    "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)");  
               
               
               connection.setDoOutput(true);    
               OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "utf-8");    
               out.write(param); // 向页面传递数据
               out.flush();    
               out.close();    
               // 一旦发送成功，用以下方法就可以得到服务器的回应：    
               String sCurrentLine;    
                
               sCurrentLine = "";    
               sTotalString = "";    
               InputStream l_urlStream;    
               l_urlStream = connection.getInputStream();    
               //三层包装阿！    
               BufferedReader l_reader = new BufferedReader(new InputStreamReader(    
                       l_urlStream));    
               while ((sCurrentLine = l_reader.readLine()) != null) {    
                   sTotalString += sCurrentLine + "\r\n";    
            
               }    
                  
       } catch (Exception e) {  
           // TODO Auto-generated catch block  
           e.printStackTrace();  
       }    
             
           System.out.println(sTotalString);    
           return sTotalString;  
    }  
	
	/* 
	 设备授权用法：
	 String access_token="l5HeZ40kiJZq1vogAbOcE9yoyNEmPWOlfI877t-_6WQizVA8WNhZM_C3oscv0MFgkEkF04k6Nb1AFJJlCIfm9ZA9CB5cCbg_ytWpNFdDfWu1Pt5gxrJ2rZwceD5NTihhRBQgAHAHRG";//更换为自己的access_token  
     String deviceId="gh_c73446c8ce91_f88655561f9b96dd";//调用生成二维码接口返回的设备id  
     String mac="12312313213";//设备mac地址，可询问提供硬件设备的厂商人员  
     String params="{\"device_num\":\"1\",\"device_list\":[{"  
                +"\"id\":\""+deviceId+"\","  
                +"\"mac\":\""+mac+"\","  
                 +"\"connect_protocol\":\"3\","  
                 +"\"auth_key\":\"\","  
                 +"\"close_strategy\":\"1\","  
                 +"\"conn_strategy\":\"1\","  
                 +"\"crypt_method\":\"0\","  
                 +"\"auth_ver\":\"0\","  
                 +"\"manu_mac_pos\":\"-1\","  
                 +"\"ser_mac_pos\":\"-2\","   
                 +"\"ble_simple_protocol\": \"0\""  
                 + "}],"  
                 +"\"op_type\":\"1\""  
                + "}";  
                  
           String s=test_yingjian.sendPost("https://api.weixin.qq.com/device/authorize_device?access_token="+access_token, params);  
               System.out.println("返回："+s); 
               
         
      向设备发送消息用法：
     String deviceId="gh_c73446c8ce91_f88655561f9b96dd";//调用生成二维码接口返回的设备id  
      content里为自定义字段，需要与工厂约定，并且需要BASE64 编码
     WeixinUtils weixinUtils = new WeixinUtils();
		AccessToken accessToken = weixinUtils.getAccessToken("wxc71b789fad06a2d7","8a90e3ab0e2db7772f5f64e7ed2f4b98");
		String content1 = getBASE64("[{\"base_info\":\"1\",\"errcode\":\"100008\",\"errmsg\":\"mac invalid\"}]");
		 String params="{\"device_type\":\"wxc71b789fad06a2d7\","  
						 +"\"open_id\":\"o-icas0dRzE7WYAEAmcX4BQCUyFo\""  
			                 +"\"device_id\":\"gh_c73446c8ce91_f88655561f9b96dd\""  
			                 +"\"content\":\""+content1+"\""  
			                 + "}]"  
			                + "}";   
		String s=test_yingjian.sendPost("https://api.weixin.qq.com/device/transmsg?access_token="+accessToken.getToken(), params);  
		System.out.println("返回："+s); 

正确的Json返回结果：
{"ret":0,"ret_info":"this is ok"}
错误的Json返回示例:
{"errcode":-1,"errmsg":""}
                */
	
	/**
	 * 接受微信平台推送信息并添加到数据库
	 * @param request
	 * @param response
	 * {
    "device_id":"device_id",
    "device_type":"device_type",
    "msg_id":123456789,
    "msg_type":"device_text",
    "create_time":1457337567,
    "open_id":"openid",
    "session_id":123456789,
    "content":"content"
}
	 * 
	 * 
	 */
	/*public void receivingDeviceMessage(HttpServletRequest request,HttpServletResponse response){
		String device_id = request.getParameter("device_id");
		String device_type = request.getParameter("device_type");
		//String msg_id = request.getParameter("msg_id");
		//String msg_type = request.getParameter("msg_type");
		//String create_time = request.getParameter("create_time");
		String open_id = request.getParameter("open_id");
		//String session_id = request.getParameter("session_id");
		String content = request.getParameter("content");
		用device_id查询数据库是否存在
		 String access_token="l5HeZ40kiJZq1vogAbOcE9yoyNEmPWOlfI877t-_6WQizVA8WNhZM_C3oscv0MFgkEkF04k6Nb1AFJJlCIfm9ZA9CB5cCbg_ytWpNFdDfWu1Pt5gxrJ2rZwceD5NTihhRBQgAHAHRG";//更换为自己的access_token  
		
		 
		
	}*/
	
	// 将 s 进行 BASE64 编码 
	public static String getBASE64(String s) {
		if (s == null)
			return null;
		return (new sun.misc.BASE64Encoder()).encode(s.getBytes());
	}

	// 将 BASE64 编码的字符串 s 进行解码
	public static String getFromBASE64(String s) {
		if (s == null)
			return null;
		BASE64Decoder decoder = new BASE64Decoder();
		try {
			byte[] b = decoder.decodeBuffer(s);
			return new String(b);
		} catch (Exception e) {
			return null;
		}
	}
	
}
 