package com.ssm.util.sms;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.alibaba.fastjson.JSON;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;

import com.ssm.util.sms.SmsConst;
import org.apache.http.util.EntityUtils;

public class SmsUtil {
	/**
	   * get请求发送短信
	   * @param phoen 手机号码
	   * @param content 发送的内容
	   * @param count 发送的手机号个数
	   * @return  msgid 编号
	   */
	public static String SendSmsGet(String phoen ,String content, int count) throws Exception{
		String url = SmsConst.SENDSMSNEW_URL+"?" +
				"userId="+SmsConst.userId+"&password="+SmsConst.password+
				"&pszMobis="+phoen+"&pszMsg=" +content+
				"&iMobiCount="+count+"&pszSubPort=*";
		String urlutf = new String(url.getBytes("utf-8"),"ISO-8859-1");
		URL getUrl =new URL(urlutf);
		HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection();
		connection.connect();
		BufferedReader reader=new BufferedReader(new InputStreamReader(connection.getInputStream()));
		String lines=reader.readLine();
		String msgid = "";
		Pattern agePattern = Pattern.compile("<\\s*string\\s*[^>]*?\\s*>(.*?)<\\s*/\\s*string\\s*>");
		Matcher ageMatcher = agePattern.matcher(lines);
		if(ageMatcher.find()){
			msgid = ageMatcher.group(1);
		}
		reader.close();
		connection.disconnect();
		return msgid;
	}

	/**
	 * post请求发送短信
	 * @param phoen 手机号码
	 * @param content 发送的内容
	 * @param count 发送的手机号个数
	 * @return   msgid 编号
	 */
	public static String SendSmsPost(String phoen ,String content, int count) throws IOException {
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(SmsConst.SENDSMSNEW_URL);
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair("userId", SmsConst.userId));
	    nameValuePairs.add(new BasicNameValuePair("password", SmsConst.password));
	    nameValuePairs.add(new BasicNameValuePair("pszMobis", phoen));
	    content = new String(content.getBytes("utf-8"),"ISO-8859-1");
	    nameValuePairs.add(new BasicNameValuePair("pszMsg", content));
	    nameValuePairs.add(new BasicNameValuePair("iMobiCount", count+""));
	    nameValuePairs.add(new BasicNameValuePair("pszSubPort","*"));
	    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
	    HttpResponse response = httpclient.execute(httppost);
	    BufferedReader reader = new BufferedReader(new InputStreamReader(
	    		response.getEntity().getContent())); 
	    String lines = reader.readLine();
	    String msgid = "";
	    Pattern agePattern = Pattern.compile("<\\s*string\\s*[^>]*?\\s*>(.*?)<\\s*/\\s*string\\s*>");
		Matcher ageMatcher = agePattern.matcher(lines);
		if(ageMatcher.find()){
			msgid = ageMatcher.group(1);
		}
		reader.close();
		return msgid;
	}

	/**
	 * post请求发送短信（新）
	 *
	 * @param phones  手机号码
	 * @param content 发送的内容
	 * @return res    json返回值
	 */
	public static String sendNewSmsPost(String phones, String content) throws IOException {
		HttpClient httpClient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost("https://api.4321.sh/sms/send");
		httpPost.addHeader("Content-Type", "application/json");
		Map<String, Object> map = new HashMap<>();
		map.put("apikey", "N11727b332");// api接口账号
		map.put("secret", "1172799e3242ebe1");// api接口秘钥
		map.put("sign_id", "101760");// 签名id
		map.put("mobile", phones);// 手机号
		map.put("content", content);// 短信内容
		String json = JSON.toJSONString(map);
		httpPost.setEntity(new StringEntity(json, "UTF-8"));
		HttpResponse response = httpClient.execute(httpPost);
		HttpEntity entity = response.getEntity();
		String res = EntityUtils.toString(entity);
		return res;
	}

	/**
	 * post请求发送短信（新）
	 *
	 * @param phones  手机号码
	 * @param content 发送的内容
	 * @param templateId 模板id
	 * @return res    json返回值
	 */
	public static String sendTemplateSmsPost(String phones, String content, String templateId) throws IOException {
		HttpClient httpClient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost("https://api.4321.sh/sms/template");
		httpPost.addHeader("Content-Type", "application/json");
		Map<String, Object> map = new HashMap<>();
		map.put("apikey", "N11727b332");// api接口账号
		map.put("secret", "1172799e3242ebe1");// api接口秘钥
		map.put("sign_id", 101760);// 签名id
		map.put("template_id", templateId);// 模板id
		map.put("mobile", phones);// 手机号
		map.put("content", content);// 短信内容
		String json = JSON.toJSONString(map);
		httpPost.setEntity(new StringEntity(json, "UTF-8"));
		HttpResponse response = httpClient.execute(httpPost);
		HttpEntity entity = response.getEntity();
		String res = EntityUtils.toString(entity);
		return res;
	}

	/**
	   * get请求发送的状态（根据发送信息时返回成功的编号查询）
	   * @param msgid 编号
	   * @return
	   * 返回值：
			Null：短信还在发送队列中或短信被下级网关拒绝
			接收状态报告内容返回格式（一次返回一条）： 时间,流水号,通道号,手机号,*,*,状态值,详细错误原因
			
		例：2008-01-23 15:43:34,4143567542310872314,10657999,13265661403,*,*,0,DELIVRD
			
		状态值：
			0 发送成功，并接收到成功的状态报告
			1 已提交运营商，正在等待运营商状态报告
			2 发送失败，并接收到失败的状态报告
	   *  注：格式中*是备用字段
	   */
	public static String StatusReportGet(String msgid) throws Exception{
		String url = SmsConst.STATUSREPORT_URL+ "?" +
				"userId="+SmsConst.userId+"&password="+SmsConst.password+
				"&msgid="+msgid;
		URL getUrl =new URL(url);
		HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection();    
		connection.connect();
		BufferedReader reader=new BufferedReader(new InputStreamReader(connection.getInputStream()));
		StringBuffer strBuf = new StringBuffer();
		String line = null;
		while ((line = reader.readLine()) != null) {
			strBuf.append(line).append("\n");
		}
		reader.close();
		connection.disconnect();
		return strBuf.toString();
	}

	/**
	   * post请求发送的状态（根据发送信息时返回成功的编号查询）
	   * @param msgid 编号
	   * @return
	   * 返回值：
			Null：短信还在发送队列中或短信被下级网关拒绝
			接收状态报告内容返回格式（一次返回一条）： 时间,流水号,通道号,手机号,*,*,状态值,详细错误原因
			
		例：2008-01-23 15:43:34,4143567542310872314,10657999,13265661403,*,*,0,DELIVRD
		
		状态值：
			0 发送成功，并接收到成功的状态报告
			1 已提交运营商，正在等待运营商状态报告
			2 发送失败，并接收到失败的状态报告
	   *  注：格式中*是备用字段
	   */
	public static String StatusReportPost(String msgid) throws IOException {
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(SmsConst.STATUSREPORT_URL);
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair("userId", SmsConst.userId));
	    nameValuePairs.add(new BasicNameValuePair("password", SmsConst.password));
	    nameValuePairs.add(new BasicNameValuePair("msgid", msgid));
	    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
	    HttpResponse response = httpclient.execute(httppost);
		
		//读取返回值
		StringBuffer strBuf = new StringBuffer();
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				response.getEntity().getContent())); 
		String line = null;
		while ((line = reader.readLine()) != null) {
			strBuf.append(line).append("\n");
		}
		reader.close();    
		
		return strBuf.toString();  
	}

	/**
	 * get获取发送信息的状态报告接口 
	 * return 
	 * 返回值(list集合)：
	 * 	1.null 无状态报告
	 * 	2.接收状态报告内容列表(最高维数为500)，返回格式：日期,时间,信息编号,*,状态值,详细错误原因
	 * 例：2008-01-23,15:43:34,0518153837115735,*,123456,234567,0,DELIVRD
	 *  注：格式中*是备用字段
	 */
	public static List<String> MongateCsGetStatusReportExExGet() throws Exception{
		String url = SmsConst.STATUSREPORTEXEX_URL+"?" +
				"userId="+SmsConst.userId+"&password="+SmsConst.password;
		URL getUrl =new URL(url);
		HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection();    
		connection.connect();
		BufferedReader reader=new BufferedReader(new InputStreamReader(connection.getInputStream()));
		StringBuffer strBuf = new StringBuffer();
		String line = null;
		while ((line = reader.readLine()) != null) {
			strBuf.append(line).append("\n");
		}
		Pattern agePattern = Pattern.compile("<\\s*string\\s*[^>]*?\\s*>(.*?)<\\s*/\\s*string\\s*>");
		Matcher ageMatcher = agePattern.matcher(strBuf);
		List<String> list = new ArrayList<String>();
		while (ageMatcher.find()) {
			list.add(ageMatcher.group(1));
		}
		reader.close();
		connection.disconnect();
		return list;
	}

	/**
	 * post获取发送信息的状态报告接口 
	 * return 
	 * 返回值(list集合)：
	 * 	1.null 无状态报告
	 * 	2.接收状态报告内容列表(最高维数为500)，返回格式：日期,时间,信息编号,*,状态值,详细错误原因
	 * 例：2008-01-23,15:43:34,0518153837115735,*,123456,234567,0,DELIVRD
	 *  注：格式中*是备用字段
	 */
	public static List<String> MongateCsGetStatusReportExExPost() throws Exception{
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(SmsConst.STATUSREPORTEXEX_URL);
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair("userId", SmsConst.userId));
	    nameValuePairs.add(new BasicNameValuePair("password", SmsConst.password));
	    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
	    HttpResponse response = httpclient.execute(httppost);
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				response.getEntity().getContent())); 
		StringBuffer strBuf = new StringBuffer();
		String line = null;
		while ((line = reader.readLine()) != null) {
			strBuf.append(line).append("\n");
		}
		Pattern agePattern = Pattern.compile("<\\s*string\\s*[^>]*?\\s*>(.*?)<\\s*/\\s*string\\s*>");
		Matcher ageMatcher = agePattern.matcher(strBuf);
		List<String> list = new ArrayList<String>();
		while (ageMatcher.find()) {
			list.add(ageMatcher.group(1));
		}
		reader.close();    
		return list;  
	}

	/**
	   * get获取上行/状态报告等
	   * @param type 请求类型  (0:上行&状态报告 1:上行 2:状态报告)
	   * @return   
	   * 返回值：
			null 无信息
			接收信息内容列表(最高维数为500)格式说明：
			
			信息类型(上行标志1),日期,时间,上行源号码,上行目标通道号,上行扩展子号,*,上行信息内容 
			或
			信息类型(状态报告标志2),日期,时间,信息编号,通道号,手机号, 发送短信时所填的MsgId, 发送短信时时所填的ModuleId,状态值,详细错误原因
	   */
	public static List<String> MongateGetDeliverGet(int type) throws Exception{
		String url = SmsConst.DELIVER_URL+"?" +
				"userId="+SmsConst.userId+"&password="+SmsConst.password+
				"&iReqType="+type;
		URL getUrl =new URL(url);
		HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection();    
		connection.connect();
		BufferedReader reader=new BufferedReader(new InputStreamReader(connection.getInputStream()));
		StringBuffer strBuf = new StringBuffer();
		String line = null;
		while ((line = reader.readLine()) != null) {
			strBuf.append(line).append("\n");
		}
		Pattern agePattern = Pattern.compile("<\\s*string\\s*[^>]*?\\s*>(.*?)<\\s*/\\s*string\\s*>");
		Matcher ageMatcher = agePattern.matcher(strBuf);
		List<String> list = new ArrayList<String>();
		while (ageMatcher.find()) {
			list.add(ageMatcher.group(1));
		}
		reader.close();
		connection.disconnect();
		return list;
	}

	/**
	   * post获取上行/状态报告等
	   * @param type 请求类型  (0:上行&状态报告 1:上行 2:状态报告)
	   * @return   
	   * 返回值：
			null 无信息
			接收信息内容列表(最高维数为500)格式说明：
			
			信息类型(上行标志1),日期,时间,上行源号码,上行目标通道号,上行扩展子号,*,上行信息内容 
			或
			信息类型(状态报告标志2),日期,时间,信息编号,通道号,手机号, 发送短信时所填的MsgId, 发送短信时时所填的ModuleId,状态值,详细错误原因
	   */
	public static List<String> MongateGetDeliverPost(int type) throws Exception{
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(SmsConst.DELIVER_URL);
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair("userId", SmsConst.userId));
	    nameValuePairs.add(new BasicNameValuePair("password", SmsConst.password));
	    nameValuePairs.add(new BasicNameValuePair("iReqType", type + ""));
	    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
	    HttpResponse response = httpclient.execute(httppost);
		
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				response.getEntity().getContent())); 
		StringBuffer strBuf = new StringBuffer();
		String line = null;
		while ((line = reader.readLine()) != null) {
			strBuf.append(line).append("\n");
		}
		Pattern agePattern = Pattern.compile("<\\s*string\\s*[^>]*?\\s*>(.*?)<\\s*/\\s*string\\s*>");
		Matcher ageMatcher = agePattern.matcher(strBuf);
		List<String> list = new ArrayList<String>();
		while (ageMatcher.find()) {
			list.add(ageMatcher.group(1));
		}
		reader.close();    
		return list;  
	}
	
	 /**
	   * post 接收上行信息接口
	   * return 
	   * 返回值：
			 null 无上行信息
			  接收信息内容列表(最高维数为500)格式说明：  日期,时间,上行源号码,上行目标通道号,上行扩展子号,信息内容
			  例如：2008-01-23,15:43:34,15986756631,10657302056780408,408,信息内容
	   */
	  public static List<String> MongateCsGetSmsExExPost() throws Exception{
		  	HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(SmsConst.SMSEXEX_URL);
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			nameValuePairs.add(new BasicNameValuePair("userId", SmsConst.userId));
		    nameValuePairs.add(new BasicNameValuePair("password", SmsConst.password));
		    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		    HttpResponse response = httpclient.execute(httppost);
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent(),"utf-8")); 
			StringBuffer strBuf = new StringBuffer();
			String line = null;
			while ((line = reader.readLine()) != null) {
				strBuf.append(line).append("\n");
			}
			Pattern agePattern = Pattern.compile("<\\s*string\\s*[^>]*?\\s*>(.*?)<\\s*/\\s*string\\s*>");
			Matcher ageMatcher = agePattern.matcher(strBuf);
			List<String> list = new ArrayList<String>();
			while (ageMatcher.find()) {
				list.add(ageMatcher.group(1));
			}
			reader.close();    
			return list;  
		}
	  
	  /**
		 * @param 错误返回值
		 * @return
		 */
		public static Map<String,Object> verifyValue(String msgid){
			Map<String, Object> map = new HashMap<String, Object>();
			
			if(msgid.equals("-1")){
				map.put("status", SmsConst.FAILURE);
				map.put("message","参数为空。信息、电话号码等有空指针、登陆失败。");
			}else if(msgid.equals("-11")){
				map.put("status", SmsConst.FAILURE);
				map.put("message","电话号码中有非数字字符");
			}else if(msgid.equals("-12")){
				map.put("status", SmsConst.FAILURE);
				map.put("message","有异常电话号码");
			}else if(msgid.equals("-101")){
				map.put("status", SmsConst.FAILURE);
				map.put("message","发送消息等待超时");
			}else if(msgid.equals("-102")){
				map.put("status", SmsConst.FAILURE);
				map.put("message","发送或接收消息失败");
			}else if(msgid.equals("-103")){
				map.put("status", SmsConst.FAILURE);
				map.put("message","接收消息超时");
			}else if(msgid.equals("-200")){
				map.put("status", SmsConst.FAILURE);
				map.put("message","其他错误");
			}else if(msgid.equals("-999")){
				map.put("status", SmsConst.FAILURE);
				map.put("message","服务器内部错误");
			}else if(msgid.equals("-10001")){
				map.put("status", SmsConst.FAILURE);
				map.put("message","用户登陆不成功(帐号密码错误)");
			}else if(msgid.equals("-10002")){
				map.put("status", SmsConst.FAILURE);
				map.put("message","提交格式不正确");
			}else if(msgid.equals("-10003")){
				map.put("status", SmsConst.FAILURE);
				map.put("message","用户余额不足");
			}else if(msgid.equals("-10004")){
				map.put("status", SmsConst.FAILURE);
				map.put("message","手机号码不正确");
			}else if(msgid.equals("-10005")){
				map.put("status", SmsConst.FAILURE);
				map.put("message","计费用户帐号错误");
			}else if(msgid.equals("-10006")){
				map.put("status", SmsConst.FAILURE);
				map.put("message","计费用户密码错");
			}else if(msgid.equals("-10007")){
				map.put("status", SmsConst.FAILURE);
				map.put("message","账号已经被停用");
			}else if(msgid.equals("-10008")){
				map.put("status", SmsConst.FAILURE);
				map.put("message","账号类型不支持该功能");
			}else if(msgid.equals("-10009")){
				map.put("status", SmsConst.FAILURE);
				map.put("message","其它错误");
			}else if(msgid.equals("-10010")){
				map.put("status", SmsConst.FAILURE);
				map.put("message","企业代码不正确");
			}else if(msgid.equals("-10011")){
				map.put("status", SmsConst.FAILURE);
				map.put("message","信息内容超长");
			}else if(msgid.equals("-10012")){
				map.put("status", SmsConst.FAILURE);
				map.put("message","不能发送联通号码");
			}else if(msgid.equals("-10013")){
				map.put("status", SmsConst.FAILURE);
				map.put("message","操作员权限不够");
			}else if(msgid.equals("-10014")){
				map.put("status", SmsConst.FAILURE);
				map.put("message","费率代码不正确");
			}else if(msgid.equals("-10015")){
				map.put("status", SmsConst.FAILURE);
				map.put("message","服务器繁忙");
			}else if(msgid.equals("-10016")){
				map.put("status", SmsConst.FAILURE);
				map.put("message","企业权限不够");
			}else if(msgid.equals("-10017")){
				map.put("status", SmsConst.FAILURE);
				map.put("message","此时间段不允许发送");
			}else if(msgid.equals("-10018")){
				map.put("status", SmsConst.FAILURE);
				map.put("message","经销商用户名或密码错");
			}else if(msgid.equals("-10019")){
				map.put("status", SmsConst.FAILURE);
				map.put("message","手机列表或规则错误");
			}else if(msgid.equals("-10021")){
				map.put("status", SmsConst.FAILURE);
				map.put("message","没有开停户权限");
			}else if(msgid.equals("-10022")){
				map.put("status", SmsConst.FAILURE);
				map.put("message","没有转换用户类型的权限");
			}else if(msgid.equals("-10023")){
				map.put("status", SmsConst.FAILURE);
				map.put("message","没有修改用户所属经销商的权限");
			}else if(msgid.equals("-10024")){
				map.put("status", SmsConst.FAILURE);
				map.put("message","经销商用户名或密码错");
			}else if(msgid.equals("-10025")){
				map.put("status", SmsConst.FAILURE);
				map.put("message","操作员登陆名或密码错误");
			}else if(msgid.equals("-10026")){
				map.put("status", SmsConst.FAILURE);
				map.put("message","操作员所充值的用户不存在");
			}else if(msgid.equals("-10027")){
				map.put("status", SmsConst.FAILURE);
				map.put("message","操作员没有充值商务版的权限");
			}else if(msgid.equals("-10028")){
				map.put("status", SmsConst.FAILURE);
				map.put("message","该用户没有转正不能充值");
			}else if(msgid.equals("-10029")){
				map.put("status", SmsConst.FAILURE);
				map.put("message","此用户没有权限从此通道发送信息");
			}else if(msgid.equals("-10030")){
				map.put("status", SmsConst.FAILURE);
				map.put("message","不能发送移动号码");
			}else if(msgid.equals("-10031")){
				map.put("status", SmsConst.FAILURE);
				map.put("message","手机号码(字段)非法");
			}else if(msgid.equals("-10032")){
				map.put("status", SmsConst.FAILURE);
				map.put("message","用户使用的费率代码错误");
			}else if(msgid.equals("-10033")){
				map.put("status", SmsConst.FAILURE);
				map.put("message","非法关键词");
			}else if(msgid.equals("-10057")){
				map.put("status", SmsConst.FAILURE);
				map.put("message","非法IP地址");//还有一些暂时不列举出来
			}else{
				map.put("status", SmsConst.SUCCESS);
				map.put("message",msgid);
			}
			return map;
		}
		
}
