package com.ekexiu.portal.mobile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import org.jfw.apt.annotation.Bean;
import org.jfw.util.ConstData;
import org.jfw.util.DateUtil;
import org.jfw.util.StringUtil;
import org.jfw.util.io.IoUtil;
import org.jfw.util.json.JsonService;

@Bean
public class MobilePhoneService {
	private static final Map<String, String> errorReason = new HashMap<String, String>();

	private String accountSid = "a9e818c5ffb547c6a1db15ce45381ab0";
	private String authToken = "d34f7d9bccd74d67abe8a62263a73fda";
	private String restUrl = "https://api.miaodiyun.com/20150822/industrySMS/sendSMS";
	private int sendTimeout = 10 * 1000;
	private int readTimeout = 10 * 1000;

	public int getSendTimeout() {
		return sendTimeout;
	}

	public void setSendTimeout(int sendTimeout) {
		this.sendTimeout = sendTimeout;
	}

	public int getReadTimeout() {
		return readTimeout;
	}

	public void setReadTimeout(int readTimeout) {
		this.readTimeout = readTimeout;
	}

	public String getRestUrl() {
		return restUrl;
	}

	public void setRestUrl(String restUrl) {
		this.restUrl = restUrl;
	}

	public String getAccountSid() {
		return accountSid;
	}

	public void setAccountSid(String accountSid) {
		this.accountSid = accountSid;
	}

	public String getAuthToken() {
		return authToken;
	}

	public void setAuthToken(String authToken) {
		this.authToken = authToken;
	}

	private byte[] send(String content) throws IOException {
		URL url = new URL(this.restUrl);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("POST");// 提交模式
		conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
		conn.setConnectTimeout(this.sendTimeout);// 连接超时 单位毫秒
		conn.setReadTimeout(this.readTimeout);// 读取超时 单位毫秒
		conn.setDoOutput(true);// 是否输入参数
		byte[] bypes = content.getBytes(ConstData.UTF8);
		OutputStream out = conn.getOutputStream();
		try {
			out.write(bypes);
			out.flush();
		} finally {
			out.close();
		}
		InputStream inStream = conn.getInputStream();
		return IoUtil.readStream(inStream, true);
	}

	private MobilePhoneResult parse(byte[] bytes) {
		return JsonService.fromJson(new InputStreamReader(new ByteArrayInputStream(bytes), ConstData.UTF8), MobilePhoneResult.class);
	}

	public void sendMessage(String to, String contentTemplate, String replateKey, String value) throws Exception {
		String content = contentTemplate.replaceAll(replateKey, value);
		String dateStr = DateUtil.formatDateTime(System.currentTimeMillis());
		StringBuilder sb = new StringBuilder();
		sb.append("accountSid=").append(this.accountSid).append("&smsContent=").append(URLEncoder.encode(content, "UTF-8")).append("&to=").append(to)
				.append("&timestamp=").append(dateStr).append("&sig=");
		String md5 = StringUtil.md5(this.accountSid + this.authToken + dateStr).toLowerCase(Locale.US);
		sb.append(md5);
		MobilePhoneResult mpr = this.parse(this.send(sb.toString()));
		if (!MobilePhoneResult.SUCCESS.equals(mpr.getRespCode())) {
			String reason = errorReason.get(mpr.getRespCode());
			if(reason==null) reason="未知错误，请联系技术客服。";
			throw new Exception(mpr.getRespCode()+"-"+reason);
		}
	}
	
	
	public static void main(String[] args) throws Exception{
		MobilePhoneService mps = new MobilePhoneService();
		mps.sendMessage("18601149468","【科袖科技】请输入验证码yzm，完成手机绑定。请于1分钟内正确输入验证码。如非本人操作，请忽略本短信。科袖科技","yzm","122234");
	}

	static {
		errorReason.put("00001", "未知错误，请联系技术客服。");
		errorReason.put("00002", "未知的方法名");
		errorReason.put("00003", "请求方式错误");
		errorReason.put("00004", "参数非法，如request parameter (key) is missing");
		errorReason.put("00005", "timestamp已过期");
		errorReason.put("00006", "sign错误");
		errorReason.put("00007", "重复提交");
		errorReason.put("00008", "操作频繁");
		errorReason.put("00011", "请求的xml格式不对");
		errorReason.put("00012", "不支持get请求，请使用post");
		errorReason.put("00013", "请求url格式不正确");
		errorReason.put("00015", "时间戳超出有效时间范围");
		errorReason.put("00016", "请求json格式不对");
		errorReason.put("00017", "数据库操作失败");
		errorReason.put("00018", "参数为空");
		errorReason.put("00019", "订单已存在");
		errorReason.put("00020", "用户不存在");
		errorReason.put("00021", "子账号余额不足");
		errorReason.put("00022", "操作频繁");
		errorReason.put("00023", "开发者余额不足");
		errorReason.put("00025", "手机格式不对");
		errorReason.put("00026", "手机号存在");
		errorReason.put("00027", "子账号名称已存在");
		errorReason.put("00028", "子账号名称过长");
		errorReason.put("00029", "回调开发者服务器异常");
		errorReason.put("00030", "回调地址为空");
		errorReason.put("00031", "appId为空或者没有传值");
		errorReason.put("00032", "主叫号码为空或者没有传值");
		errorReason.put("00033", "被叫号码为空或者没有传值");
		errorReason.put("00034", "子账号为空或者没有传值");
		errorReason.put("00035", "主叫号码和被叫号码相同");
		errorReason.put("00036", "验证码格式不对（4-8位数字）");
		errorReason.put("00037", "limit格式不对");
		errorReason.put("00038", "start格式不对");
		errorReason.put("00039", "验证码为空或者缺少此参数");
		errorReason.put("00040", "用户名或者密码错误");
		errorReason.put("00050", "短信或者语音验证码错误");
		errorReason.put("00051", "显示号码与被叫号码一样，不允许呼叫");
		errorReason.put("00052", "回拨主叫号码格式错误");
		errorReason.put("00053", "被叫号码格式错误");
		errorReason.put("00054", "显号格式错误");
		errorReason.put("00055", "应用不包含此子账号");
		errorReason.put("00056", "开发者不包含此应用");
		errorReason.put("00060", "请求数据不存在");
		errorReason.put("00061", "app不存在");
		errorReason.put("00062", "developerId 请求错误");
		errorReason.put("00063", "app未上线");
		errorReason.put("00064", "请求Content-Type错误");
		errorReason.put("00065", "请求Accept错误");
		errorReason.put("00066", "开发者余额已被冻结");
		errorReason.put("00070", "手机号未绑定");
		errorReason.put("00071", "通知类型已停用或者未创建");
		errorReason.put("00072", "balance格式不对（必须为大于等于0的double）");
		errorReason.put("00073", "charge格式不对（必须为大于等于0的double）");
		errorReason.put("00074", "主叫和子账户绑定的手机号不相同");
		errorReason.put("00075", "子账户没有绑定手机号");
		errorReason.put("00076", "时间格式不对");
		errorReason.put("00077", "开始时间小于结束时间");
		errorReason.put("00078", "开始时间和結束時間必須是同一天");
		errorReason.put("00079", "服务器内部异常");
		errorReason.put("00080", "子账号不存在");
		errorReason.put("00081", "通知计费系统失败");
		errorReason.put("00082", "参数校验失败");
		errorReason.put("00083", "充值失败");
		errorReason.put("00084", "子账号没有托管 不能进行充值");
		errorReason.put("00085", "开发者不包含子帐号");
		errorReason.put("00086", "DEMO不能进行充值");
		errorReason.put("00087", "IQ类型错误");
		errorReason.put("00090", "回调地址为空");
		errorReason.put("00091", "没有语音");
		errorReason.put("00093", "没有这个语音文件或者审核没通过");
		errorReason.put("00094", "每批发送的手机号数量不得超过100个");
		errorReason.put("00095", "未开通邮件短信功能");
		errorReason.put("00096", "邮件模板未审核通过");
		errorReason.put("00097", "邮件模板未启用");
		errorReason.put("00098", "同一手机号每天只能发送n条相同的内容");
		errorReason.put("00099", "相同的应用每天只能给同一手机号发送n条不同的内容");
		errorReason.put("00100", "短信内容不能含有关键字");
		errorReason.put("00101", "配置短信端口号失败");
		errorReason.put("00102", "一个开发者只能配置一个端口");
		errorReason.put("00103", "应用的邮件模板不存在");
		errorReason.put("00104", "相同的应用当天给同一手机号发送短信的条数小于等于n");
		errorReason.put("00105", "本开发者只能发短信给移动手机");
		errorReason.put("00106", "时间戳(timestamp)参数为空");
		errorReason.put("00107", "签名(sig)参数为空");
		errorReason.put("00108", "时间戳(timestamp)格式错误");
		errorReason.put("00109", "子账号已被关闭");
		errorReason.put("00110", "解析post数据失败，post数据不符合格式要求");
		errorReason.put("00111", "匹配到黑名单");
		errorReason.put("00112", "accountSid参数为空");
		errorReason.put("00113", "短信内容和模板匹配度过低");
		errorReason.put("00114", "clientNumber参数为空");
		errorReason.put("00115", "charge参数为空");
		errorReason.put("00116", "charge格式不对，不能解析成double");
		errorReason.put("00117", "fromTime参数为空");
		errorReason.put("00118", "toTime参数为空");
		errorReason.put("00119", "fromTime参数格式不正确");
		errorReason.put("00120", "toTime参数格式不正确");
		errorReason.put("00122", "date参数为空");
		errorReason.put("00123", "date的值不在指定范围内");
		errorReason.put("00124", "没有查询到话单（所以没有生成下载地址）");
		errorReason.put("00125", "emailTemplateId参数为空");
		errorReason.put("00126", "to参数为空");
		errorReason.put("00127", "param参数为空");
		errorReason.put("00128", "templateId参数为空");
		errorReason.put("00129", "模板类型错误");
		errorReason.put("00130", "serviceType参数为空");
		errorReason.put("00131", "content参数为空");
		errorReason.put("00132", "本接口的邮件短信业务只能发送移动手机");
		errorReason.put("00133", "错误的业务类型");
		errorReason.put("00134", "没有和内容匹配的模板");
		errorReason.put("00135", "应用没有属于指定类型业务并且已审核通过、已启用的模板");
		errorReason.put("00136", "开发者不能调用此接口");
		errorReason.put("00137", "没有权限自定义邮件内容");
		errorReason.put("00138", "短信没有签名不能发送");
		errorReason.put("00139", "短信签名已进入黑名单不能发送");
		errorReason.put("00140", "邮件短信发送间隔太小");
		errorReason.put("00141", "一小时内发送给单个手机次数超过限制");
		errorReason.put("00142", "一天内发送给单个手机次数超过限制");
		errorReason.put("00143", "含有非法关键字");
		errorReason.put("00144", "mobile参数为空");
		errorReason.put("00145", "新手机号和旧手机号相同，不必修改");
		errorReason.put("00146", "minutes格式不对（必须为大于等于0的double）");
		errorReason.put("00147", "被叫次数超限");
		errorReason.put("00148", "主叫次数超限");
		errorReason.put("00149", "流量包大小格式错误");
		errorReason.put("00150", "找不到匹配的流量包");
		errorReason.put("00151", "该签名下的手机号码黑名单");
		errorReason.put("00152", "端口号已被关闭");
		errorReason.put("00153", "未知的手机号运营商");
		errorReason.put("00154", "开发者无权限给此号码发短信");
		errorReason.put("00155", "流量充值提交失败");
		errorReason.put("00156", "packageId为空或者没有传值");
		errorReason.put("00157", "packageId不存在");
		errorReason.put("00158", "不允许发验证码");
		errorReason.put("00159", "超过每秒发送频率限制");
		errorReason.put("00160", "没有发送会员通知推广类短信权限");
		errorReason.put("00161", "短信签名没有报备");
		errorReason.put("00162", "没有发送营销短信权限");
		errorReason.put("00163", "会员营销短信内容必须包含退订");
		errorReason.put("00164", "端口号非法");
	}
}
