package com.philisense.www.utils;

import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class SmsSenderUtil {
  public static JSONObject sendVerify(String phone, String verifycode) {
    //String url = "http://wz.weixin123.biz:8080/sms/service/send";
    //String param = "sys=app&template=005&phone=" + phone + "&content=" + verifycode;
	  JSONObject jo = new JSONObject();
	  try {

	    String url = "http://api.sms1086.com/Api/Send.aspx";
	    Date day=new Date();    
	    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
	    String password = MD5("94D135E0" + df.format(day));
		String param = "username="+URLEncoder.encode("zws12345","GB2312")+"&password=" + URLEncoder.encode(password,"GB2312") + "&mobiles="+ URLEncoder.encode(phone,"GB2312")+"&content="+ URLEncoder.encode("【中卫市12345】您的验证码为：" + verifycode + "，如有疑问请联系12345","GB2312")+"&timestamp="+URLEncoder.encode(df.format(day),"GB2312");
		jo = httpRequest(url, "POST", param);
	    jo.put("success", "0".equals(jo.getString("result")) ? "Success" : "Error");
	    jo.put("msg", URLDecoder.decode(jo.getString("description"), "GB2312"));
	    String success = jo.getString("success");
	    String msg = jo.getString("msg");
	    System.out.println(success);
	    System.out.println(msg);
	} catch (UnsupportedEncodingException e) {
		e.printStackTrace();
		jo.put("success", "Error");
	    jo.put("msg", "发送短信失败");
	}
    
    return jo;
  }
  
  public static JSONObject sendSms(String phone, String content) {
//    String url = "http://wz.weixin123.biz:8080/sms/service/send";
//    String param = "sys=weixin&template=custom&phone=" + phone + "&content=" + urlEncodeUTF8(content);
	  JSONObject jo = new JSONObject();
		try {
			String url = "http://api.sms1086.com/Api/Send.aspx";
			Date day=new Date();    
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
			String password = MD5("94D135E0" + df.format(day));
			String param = "username="+URLEncoder.encode("zws12345","GB2312")+"&password=" + URLEncoder.encode(password,"GB2312") + "&mobiles="+ URLEncoder.encode(phone,"GB2312")+"&content="+ URLEncoder.encode(content,"GB2312")+"&timestamp="+URLEncoder.encode(df.format(day),"GB2312");
			jo = httpRequest(url, "POST", param);
			jo.put("success", "0".equals(jo.getString("result")) ? "Success" : "Error");
		    jo.put("msg", URLDecoder.decode(jo.getString("description"), "GB2312"));
		    String success = jo.getString("success");
		    String msg = jo.getString("msg");
		    System.out.println(success);
		    System.out.println(msg);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			jo.put("success", "Error");
		    jo.put("msg", "发送短信失败");
		}
    
    return jo;
  }
  
  public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
    JSONObject jsonObject = null;
    StringBuffer buffer = new StringBuffer();
    try {
      URL url = new URL(requestUrl);
      HttpURLConnection httpUrlConn = (HttpURLConnection)url.openConnection();
      httpUrlConn.setDoOutput(true);
      httpUrlConn.setDoInput(true);
      httpUrlConn.setUseCaches(false);
      httpUrlConn.setRequestMethod(requestMethod);
      httpUrlConn.setConnectTimeout(600000);
      httpUrlConn.setReadTimeout(600000);
      if ("GET".equalsIgnoreCase(requestMethod))
        httpUrlConn.connect(); 
      if (outputStr != null) {
        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();
      System.err.println(buffer.toString());
//      jsonObject = JSONObject.fromObject(buffer.toString());
      jsonObject = toJsonObj(mapStringToMap(buffer.toString()));

    } catch (ConnectException ce) {
      ce.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    } 
    return jsonObject;
  }

  public static String MD5(String pwd) {
      //用于加密的字符
      char md5String[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
              'a', 'b', 'c', 'd', 'e', 'f' };
      try {
          //使用平台的默认字符集将此 String 编码为 byte序列，并将结果存储到一个新的 byte数组中
          byte[] btInput = pwd.getBytes();
           
          //信息摘要是安全的单向哈希函数，它接收任意大小的数据，并输出固定长度的哈希值。
          MessageDigest mdInst = MessageDigest.getInstance("MD5");
           
          //MessageDigest对象通过使用 update方法处理数据， 使用指定的byte数组更新摘要
          mdInst.update(btInput);
           
          // 摘要更新之后，通过调用digest（）执行哈希计算，获得密文
          byte[] md = mdInst.digest();
           
          // 把密文转换成十六进制的字符串形式
          int j = md.length;
          char str[] = new char[j * 2];
          int k = 0;
          for (int i = 0; i < j; i++) {   //  i = 0
              byte byte0 = md[i];  //95
              str[k++] = md5String[byte0 >>> 4 & 0xf];    //    5 
              str[k++] = md5String[byte0 & 0xf];   //   F
          }
           
          //返回经过加密后的字符串
          return new String(str);
           
      } catch (Exception e) {
          return null;
      }
  }
  
  public static String urlEncodeUTF8(String source) {
    String result = source;
    try {
      result = URLEncoder.encode(source, "utf-8");
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    } 
    return result;
  }
  
  private static Map<String, String> mapStringToMap(String str) {
		String[] strs = str.split("&");
		Map<String, String> map = new HashMap<String, String>();
		for (String string : strs) {
			String key = string.split("=")[0];
			String value = string.substring(string.indexOf("=") + 1);
			map.put(key.trim(), value.trim());
		}
		return map;
  }

    private static JSONObject toJsonObj(Map<String, String> map) {
        JSONObject resultJson = new JSONObject();
        Iterator it = map.keySet().iterator();
        while (it.hasNext()) {
            String key = (String) it.next();
            resultJson.put(key, map.get(key));
        }
        return resultJson;
    }
  
  public static void main(String[] args) {
//		sendVerify("15810769788", "802300");
//		sendVerify("18538162126", "802300");
	  sendVerify("13501251452", "802300");
  }
  
  

}