package com.iamberry.wechat.iot;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
import java.util.logging.Logger;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import org.springframework.util.Base64Utils;

import com.iamberry.wechat.tools.HttpClient431Util;
import com.iamberry.wechat.tools.MyX509TrustManager;

import net.sf.json.JSONObject;

/**
 * 微信硬件平台接口
 * @company	深圳爱贝源科技有限公司
 * @website www.iamberry.com
 * @author 	献
 * @tel		18271840547
 * @date	2017年2月20日
 */
public class WechatIotUtils {

	/**
	 * 获取设备id和二维码URL
	 */
	private static final String get_deviceId_qrcode = "https://api.weixin.qq.com/device/getqrcode?access_token=ACCESS_TOKEN&product_id=PRODUCT_ID";
	
	/**
	 * 设备授权
	 */
	public static final String authorize_device = "https://api.weixin.qq.com/device/authorize_device?access_token=ACCESS_TOKEN";
	
	/**
	 * 主动发消息给设备
	 */
	public static final String transmsg = "https://api.weixin.qq.com/device/transmsg?access_token=ACCESS_TOKEN";
	
	
	/***
	 * 机器指令集
	 */
	
	/**
	 * 激活续费命令
	 */
	public static final String INIT_MACHINE_COMMAND = "*setData%s %s#";
	
	/**
	 * 获取ticket
	 */
	public final static String GETTICKET_URL="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=";//接口凭据 
	public final static String UNBIND_URL="https://api.weixin.qq.com/device/unbind?access_token=";//解除绑定 
	
	/**
	 * 根据设备id获取绑定用户
	 */
	public final static String getOpenIdUrl = "https://api.weixin.qq.com/device/get_openid?access_token=ACCESS_TOKEN&device_type=DEVICE_TYPE&device_id=DEVICE_ID";
	/**
	 * 获取deviceid和二维码
	 * @author 献
	 * @Time   2017年2月20日
	 */
	public static JSONObject getQrcode(String accessToken, String productId) {
		String url = get_deviceId_qrcode.replace("ACCESS_TOKEN", accessToken).replace("PRODUCT_ID", productId);
		try {
			String result = HttpClient431Util.doGet(null, url);
			return JSONObject.fromObject(result);
		} catch (Exception e) {
			// 失败
			return null;
		}
	}
	/**
	 * 根据设备id获取绑定用户
	 */
	public static JSONObject getOpenId(String accessToken, String device_type,String device_id) {
		String url = getOpenIdUrl.replace("ACCESS_TOKEN", accessToken).replace("DEVICE_TYPE", device_type).replace("DEVICE_ID", device_id);
		try {
			String result = HttpClient431Util.doGet(null, url);
			return JSONObject.fromObject(result);
		} catch (Exception e) {
			// 失败
			return null;
		}
	}
	
	/**
	 * 设备授权
	 * @param accessToken
	 * @param mac
	 * @param deviceId
	 * @return
	 * @author 献
	 * @Time   2017年2月20日
	 */
	public static JSONObject authorize(String accessToken, String mac, String deviceId) {
		String url = authorize_device.replace("ACCESS_TOKEN", accessToken);
		
		/*Device device = new Device();
		device.setAuth_key("ABC");
		device.setAuth_ver(1);					// 加密
		device.setBle_simple_protocol(1);		// 精简协议
		device.setClose_strategy(2);			// 退出公众号以后不端口
		device.setConn_strategy(4);				// 非公众号页面（如主界面等），微信自动连接
		device.setCrypt_method(1);				// AES加密
		device.setId(deviceId);
		device.setMac(mac);
		device.setManu_mac_pos(-1);				// 在尾部
		device.setSer_mac_pos(-1);
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("device_num", 1);
		map.put("device_list", device);
		map.put("op_type", 1);*/
        String params = "{\"device_num\":\"1\",\"device_list\":[{"    
                + "\"id\":\"" + deviceId + "\"," + "\"mac\":\"" + mac + "\","    
                + "\"connect_protocol\":\"3\"," + "\"auth_key\":\"\","    
                + "\"close_strategy\":\"1\"," + "\"conn_strategy\":\"5\","    
                + "\"crypt_method\":\"0\"," + "\"auth_ver\":\"0\","    
                + "\"manu_mac_pos\":\"-1\"," + "\"ser_mac_pos\":\"-1\","    
                + "\"ble_simple_protocol\": \"0\"" + "}],"    
                + "\"op_type\":\"1\"" + "}";    
      
		String req = JSONObject.fromObject(params).toString();
		return httpRequest(url, "POST", req);
	}
	
	/**
	 * 向设备主动发送消息
	 * @param accessToken
	 * @param context
	 * @param deviceId
	 * @param openId
	 * @return
	 * @author 献
	 * @Time   2017年2月20日
	 */
	public static JSONObject send(String accessToken, String context, String deviceId, String openId, String type) {
		String url = transmsg.replace("ACCESS_TOKEN", accessToken);
		
		TransMsg msg = new TransMsg();
		msg.setContent(Base64Utils.encodeToString(context.getBytes()));
		msg.setDevice_id(deviceId);
		msg.setOpen_id(openId);
		msg.setDevice_type(type);			// 公众号的原始id
		
		return httpRequest(url, "POST", JSONObject.fromObject(msg).toString());
	}
	
	/**
	 * 自定义请求HTTPS的内容
	 * @param requestUrl
	 * @param requestMethod
	 * @param outputStr
	 * @return
	 * @author 献
	 * @Time   2017年2月20日
	 */
	public static JSONObject httpRequest(String requestUrl,
			String requestMethod, String outputStr) {
		JSONObject jsonObject = null;
		StringBuilder buffer = new StringBuilder();
		try {
			// 创建SSLContext对象，并使用我们指定的信任管理器初始化
			TrustManager[] tm = { new MyX509TrustManager() };
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new java.security.SecureRandom());
			// 从上述SSLContext对象中得到SSLSocketFactory对象
			SSLSocketFactory ssf = sslContext.getSocketFactory();

			// 准备连接
			URL url = new URL(requestUrl);
			HttpsURLConnection httpUrlConn = (HttpsURLConnection) url
					.openConnection();
			httpUrlConn.setSSLSocketFactory(ssf);

			// 设置（是否输出数据、是否输入数据、是否使用缓存）
			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);

			// 设置请求方式(GET/POST)
			httpUrlConn.setRequestMethod(requestMethod);
			if ("GET".equalsIgnoreCase(requestMethod))
				httpUrlConn.connect();

			// 当有数据需要提交时
			if (null != outputStr) {
				OutputStream outputStream = httpUrlConn.getOutputStream();
				// 注意编码格式,防止中文乱码
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}

			// 将返回的输入流转换成字符串
			InputStream inputStream = httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			// 释放资源
			inputStream.close();
			inputStream = null;
			httpUrlConn.disconnect();
			jsonObject = JSONObject.fromObject(buffer.toString());
		} catch (ConnectException ce) {
			Logger.getAnonymousLogger().info("Weixin server connection timed out.");
		} catch (Exception e) {
			Logger.getAnonymousLogger().info("信任管理器请求时..." + e);
			Logger.getAnonymousLogger().info("jsonObject..." + jsonObject);
		}
		return jsonObject;
	}
	
	/**
	 * 解除绑定
	 * @param access_token
	 * @param openid
	 * @param deviceid
	 * @param ticket
	 * @return
	 */
	public static JSONObject cancelBinding (String access_token,String openid,String deviceid,String ticket) {
		// TODO Auto-generated method stub
		if (access_token == null && openid == null 
				&& deviceid == null && ticket == null) {
			return null;
		}
		ticket = WechatIotUtils.getJsapiTicket(access_token);//前台传入
		String url = WechatIotUtils.UNBIND_URL+access_token; 
	    String params="{ \"ticket\": \""+ticket+"\", \"device_id\": \""+deviceid+"\", \"openid\": \""+openid+"\"}";
	    return httpRequest(url, "POST", params);
	}
	
	/**
	 * 获取ticket
	 * @param access_token
	 * @return
	 */
	public static String getJsapiTicket(String access_token){
	       JSONObject jsonData=WechatIotUtils.httpRequest(GETTICKET_URL, "GET", null);
	       String errcode = jsonData.getString("errcode");
	       String ticket = null;
	       if(errcode.equals("0")){
	           ticket = jsonData.getString("ticket");
	       }
	       return ticket;
	}
	
	
	/**
	 * 1.2	激活/续费指令封装
	 * @param command 16进制的11表示下发激活指令,命令的唯一标识
	 * @param hour 本次租赁的小时数量，,如果发送为0，则表示永久购买
	 * @param water 本次可使用的水量,单位为升
	 * verify 命令标识+小时+水量，然后取和的低八位，转16进制传递
	 * @return
	 */
	public static String activateRenewal(Integer command,Integer hour,Integer water){
		/*String content = command+Integer.toHexString(hour)+Integer.toHexString(water);
		int content2 = Integer.valueOf(command+hour+water);
		String msg = Integer.toBinaryString(content2); 
        System.out.println(msg); // 输出二进制序列
        msg = msg.substring(msg.length() - 8); 
        System.out.println(msg); // 输出二进制序列
        int low = 0xFF;
        System.out.println(content2&low);
        System.out.println(Integer.toHexString(Integer.valueOf(msg))); 
        
        byte te = (byte)content2;
        byte low8a = (byte) ((content2<<8)>>8);
        System.out.println(Integer.toHexString(low8a));
        System.out.println(te);*/
		
		int content = Integer.valueOf(command+hour+water);
		int low = 0xFF;
		content = content&low;
		String verify = command+"0"+Integer.toHexString(hour)+"0"+Integer.toHexString(water)+Integer.toHexString(content);
		return verify;
		
	} 
	
	static short get_Lvalue(int u16)
	{
	      int Lvalue=0;   // low 8 bits
	      Lvalue= (short)(u16 & 0xff);  //get low  8 bits;           
	      return (short) Lvalue;
	}
	/**
	 * 1.5	改变机器数据的方向数据封装
	 * @param command 16进制的15表示改变数据方向的命令，唯一标识
	 * @param recv 这里表示是修改数据发送还是接受的 01：接受 02：发送
	 * @param state 这里表示方向 00：厂商服务器 01：微信手环 02：HTML页面
	 *verify Command+recv+state,取和的第八位
	 * @return
	 */
	public static String changeMachineData(Integer command,Integer recv,Integer state){
		String  msg = Integer.toHexString(command);
		String content = "";
	
		return content;
		
	} 
	
	public static String str2HexStr(String str) {    
        char[] chars = "0123456789ABCDEF".toCharArray();    
        StringBuilder sb = new StringBuilder("");  
        byte[] bs = str.getBytes();    
        int bit;    
        for (int i = 0; i < bs.length; i++) {     
            bit = (bs[i] & 0x0f0) >> 4;    
            sb.append(chars[bit]);    
            bit = bs[i] & 0x0f;    
            sb.append(chars[bit]);    
        }    
        return sb.toString();    
    }
	
	/**
	 * 按5位对齐
	 * @param t
	 * @return
	 * @author 献
	 * @Time   2017年4月7日
	 */
	public static String align(String t) {
		if (t.length() >= 5) {
			return t;
		}
		return align("0" + t);
	}

	/**
	 * 取消绑定
	 * @param device_id		设备id
	 * @param ticket		票据
	 * @param openid		用户openID
	 * @param isUnBind		true : 取消绑定；false : 绑定
	 * @return
	 */
	public static JSONObject unBind(String device_id, String ticket, String openid, String access_token, boolean isUnBind) {
		String url = isUnBind ? "https://api.weixin.qq.com/device/unbind?access_token=" : "https://api.weixin.qq.com/device/bind?access_token=";
		String data = new StringBuilder("{\"ticket\":\"").append(ticket).append("\",").append("\"device_id\":\"").append(device_id)
				.append("\",").append("\"openid\":\"").append(openid).append("\"}").toString();
		return httpRequest(url + access_token, "POST", data);
	}
}
