package xiaoqu.home.open.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/***********
 * 短信发送工具
 * 
 * @author wh 2019年1月10日
 */
@Component

public class SmsUtil {
	private static Logger log = LoggerFactory.getLogger("SmsUtil");
	
	public  static String smsUserName;
	
	public static String smsPassword;
	
	public static String smsUrl;
	
	public static String smsSign;
	

	public  String getSmsUserName() {
		return smsUserName;
	}
	@Value("${smsUserName}")
	public  void setSmsUserName(String smsUserName) {
		SmsUtil.smsUserName = smsUserName;
	}

	public  String getSmsPassword() {
		return smsPassword;
	}
	@Value("${smsPassword}")
	public  void setSmsPassword(String smsPassword) {
		SmsUtil.smsPassword = smsPassword;
	}

	public  String getSmsUrl() {
		return smsUrl;
	}
	@Value("${smsUrl}")
	public  void setSmsUrl(String smsUrl) {
		SmsUtil.smsUrl = smsUrl;
	}

	public  String getSmsSign() {
		return smsSign;
	}
	@Value("${smsSign}")
	public  void setSmsSign(String smsSign) {
		SmsUtil.smsSign = smsSign;
	}

	public static String getKey(String userName, String password, String timestemp) {
		String key = "";
		try {
			MessageDigest mdTemp = MessageDigest.getInstance("MD5");
			mdTemp.update(userName.getBytes());
			mdTemp.update(password.getBytes());
			mdTemp.update(timestemp.getBytes());
			key = bytesToHexString(mdTemp.digest());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return key;
	}

	public static String getTimestemp() {
		return (new SimpleDateFormat("MMddHHmmss")).format(new Date());
	}

	public static String bytesToHexString(byte[] src) {
		String resultString = "";
		StringBuilder stringBuilder = new StringBuilder("");
		if (src == null || src.length <= 0) {
			return null;
		}
		for (int i = 0; i < src.length; i++) {
			int v = src[i] & 0xFF;
			String hv = Integer.toHexString(v);
			if (hv.length() < 2) {
				stringBuilder.append(0);
			}
			stringBuilder.append(hv);
		}
		resultString = stringBuilder.toString();
		stringBuilder = null;
		return resultString;
	}

	/*****************
	 * 短信发送服务
	 * 
	 * @param code   验证码
	 * @param number 手机号 sendSms
	 */
	public static boolean sendSms(String code, String number,Long smsId) {
		boolean flag = false;
		String userName = smsUserName;
		String password = smsPassword;
		String timestemp = getTimestemp();
		String key = getKey(userName, password, timestemp);
		String serverAddress = smsUrl;
		// 短信内容。RLEncoder.encode utf-8编码，500个字或字符以内
		String content = smsSign.replace("code", code);
		// 多个手机号码用“,”隔开。（半角逗号）1000个以内（不可有空号）
		String mobiles = number;
		// 1~5的整数 从低到高
		int priority = 5;
		// 短信唯一标识 长整型数字。短信ID，用来匹配状态报告（必须数字类型）
		StringBuffer paramters = new StringBuffer();
		paramters.append("UserName=" + userName + "&");
		paramters.append("Key=" + key + "&");
		paramters.append("Timestemp=" + timestemp + "&");
		try {
			paramters.append("Content=" + URLEncoder.encode(content, "utf-8") + "&");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		paramters.append("CharSet=utf-8&");
		paramters.append("Mobiles=" + mobiles + "&");
		paramters.append("Priority=" + priority + "&");
		paramters.append("SMSID=" + smsId);

		StringBuffer response = new StringBuffer();
		try {
			URL url = new URL(serverAddress + "?" + paramters);
			InputStream is = url.openStream();
			InputStreamReader isr = new InputStreamReader(is, "utf-8");
			BufferedReader reader = new BufferedReader(isr);
			String lines;
			while ((lines = reader.readLine()) != null) {
				lines = new String(lines.getBytes(), "utf-8");
				response.append(lines);
			}
			is.close();
			log.info("短信发送日志记录=" + serverAddress + "?" + paramters);
			log.info("短信发送结果=" + response);
			JSONObject resJson = JSON.parseObject(response.toString());
			String result = "result";
			if (resJson.getInteger(result) == 0) {
				flag = true;
			}
		} catch (IOException e) {
			log.error("短信发送异常" + e + serverAddress + "?" + paramters);
		}
		return flag;
	}
	/*****************
	 * 直接发送短信
	 * 
	 * @param Content   内容
	 * @param number 手机号 sendSms
	 */
	public static boolean sendSms(String Content, String number) {
		boolean flag = false;
		String userName = smsUserName;
		String password = smsPassword;
		String timestemp = getTimestemp();
		String key = getKey(userName, password, timestemp);
		String serverAddress = smsUrl;
		Long smsId = System.nanoTime();
		// 短信内容。RLEncoder.encode utf-8编码，500个字或字符以内
		String content = Content;
		// 多个手机号码用“,”隔开。（半角逗号）1000个以内（不可有空号）
		String mobiles = number;
		// 1~5的整数 从低到高
		int priority = 5;
		// 短信唯一标识 长整型数字。短信ID，用来匹配状态报告（必须数字类型）
		StringBuffer paramters = new StringBuffer();
		paramters.append("UserName=" + userName + "&");
		paramters.append("Key=" + key + "&");
		paramters.append("Timestemp=" + timestemp + "&");
		try {
			paramters.append("Content=" + URLEncoder.encode(content, "utf-8") + "&");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		paramters.append("CharSet=utf-8&");
		paramters.append("Mobiles=" + mobiles + "&");
		paramters.append("Priority=" + priority + "&");
		paramters.append("SMSID=" + smsId);

		StringBuffer response = new StringBuffer();
		try {
			URL url = new URL(serverAddress + "?" + paramters);
			InputStream is = url.openStream();
			InputStreamReader isr = new InputStreamReader(is, "utf-8");
			BufferedReader reader = new BufferedReader(isr);
			String lines;
			while ((lines = reader.readLine()) != null) {
				lines = new String(lines.getBytes(), "utf-8");
				response.append(lines);
			}
			is.close();
			log.info("短信发送日志记录=" + serverAddress + "?" + paramters);
			log.info("短信发送结果=" + response);
			JSONObject resJson = JSON.parseObject(response.toString());
			String result = "result";
			if (resJson.getInteger(result) == 0) {
				flag = true;
			}
		} catch (IOException e) {
			log.error("短信发送异常" + e + serverAddress + "?" + paramters);
		}
		return flag;
	}

}
