package cn.myapps.support.sms;

import java.io.Serializable;
import java.net.URLEncoder;

import cn.myapps.authtime.common.dao.PersistenceUtils;
import cn.myapps.common.auth.IUser;
import cn.myapps.common.util.PropertyUtil;
import cn.myapps.common.util.StringUtil;
import cn.myapps.runtime.dynaform.document.model.IDocument;
import cn.myapps.runtime.workflow.notification.ejb.SendMode;
import cn.myapps.support.sms.teemlink.TeemLinkSMSManager;
import cn.myapps.util.http.HttpRequestUtil;
import cn.myapps.webservice.client.TeemLinkSMS;
import net.sf.json.JSONObject;

public class SMSMode implements SendMode {

//	private final static Logger log = LoggerFactory.getLogger(SendMode.class);

//	private String content;
//	private String[] receiver;
//	private String sign;
//	private String application;
//	private String domainid;
//	private String from;
//
//	private String receiverUserId;
//
//	private String replyCode;

	public static String sms_url = "http://sms.teemlink.com/sms/member/sendMessage.action?telephone={telephone}&account={account}&password={password}&content={content}&signatureId={signatureId}&templateId={templateId}";

	public SMSMode(){
		super();
	}

//	public SMSMode(IUser user) {
//		this("", user);
//	}
//
//	public SMSMode(String sign, IUser user) {
//		this(user.getTelephone(), sign, user.getDefaultApplication(), user.getDomainid());
//	}
//
//	public SMSMode(String sign, String application, String domainid) {
//		this("70104", sign, application, domainid);
//	}

//	public SMSMode(String from, String sign, String application, String domainid) {
//		this.from = from;
//		this.sign = sign;
//		this.application = application;
//		this.domainid = domainid;
//	}

//	public String getContent() {
//		return content;
//	}
//
//	public String[] getReceiver() {
//		return receiver;
//	}
//
//	public String getSign() {
//		return sign;
//	}
//
//	public void setContent(String content) {
//		this.content = content;
//	}
//
//	public void setReceiver(String[] receiver) {
//		this.receiver = receiver;
//	}
//
//	public void setSign(String sign) {
//		this.sign = sign;
//	}

	/**
	 * 发送短信息给responsible用户
	 * 
	 * @param subject
	 * @param content
	 * @param responsible
	 * @throws Exception
	 */
//	public boolean send(String subject, String content, IUser responsible) throws Exception {
//		return send(subject, content, responsible.getTelephone());
//	}

	/**
	 * 发送短信到reciever
	 * 
	 * @param subject :
	 *            主题
	 * @param content :
	 *            内容
	 * @param receiver :
	 *            为接收者电话号码,可为多个.如果有多个时,以","分隔.
	 * @throws Exception
	 */
//	public boolean send(String subject, String content, String receiver) throws Exception {
//		return send(subject, content, receiver, false);
//	}

	/**
	 * 发送短信到reciever
	 * 
	 * @param subject :
	 *            主题
	 * @param content :
	 *            内容
	 * @param receiver :
	 *            为接收者电话号码,可为多个.如果有多个时,以","分隔.
	 * @param mass :
	 *            是否群发
	 * @throws Exception
	 */
//	public boolean send(String subject, String content, String receiver, boolean mass) throws Exception {
//		return send(subject, content, receiver, null, mass);
//	}

	/**
	 * 发送短信到reciever
	 * 
	 * @param subject :
	 *            主题
	 * @param content :
	 *            内容
	 * @param receiver :
	 *            为接收者电话号码,可为多个.如果有多个时,以","分隔.
	 * @param replyPrompt :
	 *            回复提示信息
	 * @param code :
	 *            要求回复的内容
	 * @param mass :
	 *            是否群发
	 * @throws Exception
	 */
//	public boolean send(String subject, String content, String receiver, String replyPrompt, String code, boolean mass)
//			throws Exception {
//		return send(null, subject, content, receiver, replyPrompt, code, mass);
//	}

//	public boolean send(int type, String docid, String subject, String content, String receiver, String replyPrompt,
//			String code, boolean mass) throws Exception {
//		String body = "";/*MessageType.getName(type);*/
//		boolean falg = false;
//		SMSQueueOperator operator = SMSQueueOperator.getInstance();
//		
//		if (!StringUtil.isBlank(subject)) {
//			body += subject.trim();
//		}
//		body += content.trim();
//
//		replyCode = code;
//
//		this.content = body;
//		this.receiver = receiver.trim().split(",");
//		try {
//			
//			SMSParcels parcels = new SMSParcels(this.content, this.receiver, this.sign, this.application, this.domainid);
//			
//			operator.add(parcels);
//			operator.send();
//		} catch (Exception e) {
//			throw e;
//		} finally {
//			PersistenceUtils.closeSessionAndConnection();
//		}
//		return falg;
//	}

	/**
	 * 发送短信到reciever
	 * 
	 * @param subject :
	 *            主题
	 * @param content :
	 *            内容
	 * @param receiver :
	 *            为接收者电话号码,可为多个.如果有多个时,以","分隔.
	 * @param defineReply :
	 *            提供多种回复要求时,使用键值对做参数.以回复提示信息和要求回复的内容组成多个键值对.
	 * @param mass :
	 *            是否群发
	 * @throws Exception
	 */
//	public boolean send(String subject, String content, String receiver, Map<String, String> defineReply, boolean mass)
//			throws Exception {
//		return send(null, subject, content, receiver, defineReply, mass);
//	}

	/**
	 * 发送短信到reciever
	 * 
	 * @param docId :
	 *            表单记录ID
	 * @param subject :
	 *            主题
	 * @param content :
	 *            内容
	 * @param receiver :
	 *            为接收者电话号码,可为多个.如果有多个时,以","分隔.
	 * @param defineReply :
	 *            提供多种回复要求时,使用键值对做参数.以回复提示信息和要求回复的内容组成多个键值对.
	 * @param mass :
	 *            是否群发
	 * @param applicationid :
	 *            应用ID
	 * @throws Exception
	 */
//	public boolean send(int type, String docId, String subject, String content, String receiver,
//			Map<String, String> defineReply, boolean mass) throws Exception {
//		boolean falg = false;
//		SMSQueueOperator operator = SMSQueueOperator.getInstance();
//		
//		if (!StringUtil.isBlank(receiver)) {
//
//			String body = "";/*MessageType.getName(type);*/
//			if (!StringUtil.isBlank(subject)) {
//				body += subject.trim();
//			}
//			body += content.trim();
//
//			if (defineReply != null && defineReply.size() > 0)
//				replyCode = (String) defineReply.values().toArray()[0];
//			this.content = body;
//			this.receiver = receiver.trim().split(",");
//			try {
//				SMSParcels parcels = new SMSParcels(this.content, this.receiver, this.sign, this.application,this.domainid);
//				operator.add(parcels);
//				operator.send();
//			} catch (Exception e) {
//				throw e;
//			} finally {
//				PersistenceUtils.closeSessionAndConnection();
//			}
//		}
//		return falg;
//	}

	@SuppressWarnings("unused")
	private void send() throws Exception {
		SMSQueueOperator.getInstance().send();
	}

//	public boolean send(int type, String docid, String subject, String content, String receiver, boolean isNeedReply,
//			boolean mass) throws Exception {
//		Calendar cld = Calendar.getInstance();
//		if (isNeedReply)
//			if (mass) {
//				return send(type, docid, subject, content, receiver, "收到请回短信", "", mass);
//			} else {
//
//				return send(type, docid, subject, content, receiver, "收到请回短信", "", mass);
//			}
//		else
//			return send(type, docid, subject, content, receiver, new HashMap<String, String>(), mass);
//
//	}

//	public boolean send(int type, String subject, String content, String receiver, boolean isNeedReply, boolean mass)
//			throws Exception {
//		return send(type, null, subject, content, receiver, isNeedReply, mass);
//	}

//	public boolean send(String docid, String subject, String content, String receiver, boolean isNeedReply, boolean mass)
//			throws Exception {
//		return send(0, docid, subject, content, receiver, isNeedReply, mass);
//	}

//	public String getApplication() {
//		return application;
//	}
//
//	public String getDomainid() {
//		return domainid;
//	}
//
//	public void setApplication(String application) {
//		this.application = application;
//	}
//
//	public void setDomainid(String domainid) {
//		this.domainid = domainid;
//	}

//	public boolean send(String docid, String subject, String content, IUser responsible) throws Exception {
//		return send(docid, subject, content, responsible.getTelephone());
//	}

//	public boolean send(String docid, String subject, String content, String receiver) throws Exception {
//		return send(docid, subject, content, receiver, new HashMap<String, String>(), false);
//	}

//	public boolean send(String docid, String subject, String content, String receiver, String replyPrompt, String code,
//			boolean mass) throws Exception {
//		return send(0, docid, subject, content, receiver, replyPrompt, code, mass);
//	}

//	public boolean send(String docid, String subject, String content, String receiver, Map<String, String> defineReply,
//			boolean mass) throws Exception {
//		return send(0, docid, subject, content, receiver, defineReply, mass);
//	}

//	public String getReceiverUserId() {
//		return receiverUserId;
//	}
//
//	public void setReceiverUserId(String receiverUserId) {
//		this.receiverUserId = receiverUserId;
//	}

//	public static void main(String[] args) {
//		String content = "TH0004455单据审批超期，请及时处理。客户信息：广州国美，金额：20000，产品：热水器。";
//		String receiver = "13434237751";
//		String applicationid = "11e1-7326-36a83451-9f50-bd5c844c7a70";
//		String domainid = "11de-c138-782d2f26-9a62-8bacb70a86e1";
//		for(int i=0;i<1;i++){
//			try {
//				SMSMode sender = new SMSMode("", domainid, applicationid);
//				Map<String, String> map = new HashMap<String, String>();
//				map.put("收到", "");
//				sender.send("", content, receiver, map, false);
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//		}
//	}

//	public boolean send(SummaryCfgVO summaryCfg, IDocument doc, IUser responsible) throws Exception {
//		return send(summaryCfg.getTitle(), summaryCfg, doc, responsible);
//	}

	/**
	 * 流程短信发送
	 */
//	public boolean send(String subject, SummaryCfgVO summaryCfg, IDocument doc, IUser responsible) throws Exception {
//		return send(subject, summaryCfg, doc, responsible, false);
//	}
	
	/**
	 * 流程短信发送
	 * @param subject 标题
	 * @param summaryCfg 摘要
	 * @param doc 文档
	 * @param responsible 接收人
	 * @param approval 是否开启短信审批
	 * @return
	 * @throws Exception
	 */
//	public boolean send(String subject, SummaryCfgVO summaryCfg, IDocument doc, IUser responsible, boolean approval) throws Exception {
//		subject = subject + "[" + responsible.getName() + "]";
//
//		if (doc == null) throw new Exception("Cound not send with null document");
//		
//		String content = summaryCfg.toText(doc,null);
//		if (approval) {
//			content += ".短信审批方式: 回复码:0(回退)或1(提交),如AA0001:0";
//			String replyCode = "";
//			return send(doc.getId(), subject, content, responsible.getTelephone(), "", replyCode, false);
//		} else {
//			return send(doc.getId(), subject, content, responsible.getTelephone());
//		}
//	}
	
	/**
	 * 同步的方式发送信息但不产生日志记录（用于短信发送测试）
	 * @param account
	 * 		天翎短信平台帐号
	 * @param password
	 * 		天翎短信平台密码
	 * @param telephone
	 * 		手机号码
	 * @param smsContent
	 * 		短信内容
	 * @return
	 * 		返回发送结果代码
	 * @throws Exception
	 */
	public JSONObject sendWithoutLog(String account,String password,String telephone,String smsContent )throws Exception {
//		TeemLinkSMS teemLinkService = TeemLinkSMSManager.getInstance().getService();
//		return teemLinkService.sendMsg(account, password, telephone, smsContent);
		String signature = (String) PropertyUtil.getProp("myapp").get("sms.signature");
		String url = sms_url.replace("{account}",account).replace("{password}",password).replace("{telephone}",telephone).replace("{content}", URLEncoder.encode(smsContent,"UTF-8")).replace("{signatureId}",signature);
		JSONObject jsonObject = HttpRequestUtil.get(url, null);

		return jsonObject;
	}
	
	/**
	 * 获取天翎短信平台的账户信息
	 * @param account
	 * @param password
	 * @return
	 */
	public String getTeemlinkSMSAccountInformation(String account,String password){
		
		return "";
		
	}
	

	
	
	/**
	 * 短信发送的线程
	 * 
	 * @author Nicholas
	 * 
	 */
	
	/**
	 
	public class SendSMSThread extends Thread {

		String flag = null;

		public void run() {

			try {
				MessageManager manager = MessageManager.getInstance(new Validator(domainid, application));
				ISender sender = manager.getSender();
				if (sender != null) {
					String contents = content + sign.trim();
					contents = contents.replace('\n', ' ');
					contents = contents.replace('\r', ' ');
					contents = contents.replace("&#160;&#160;&#160;", " ");
					contents = contents.replace("</br>", " ");
					int result = -100;
					if (receiver != null && receiver.length == 1) {
						if (StringUtil.isBlank(replyCode))
							result = sender.sendMessage(receiver[0], contents);
						else
							result = sender.sendMessage(receiver[0], contents, replyCode);
					} else if (receiver != null && receiver.length > 1) {
						if (StringUtil.isBlank(replyCode))
							result = sender.battchSendMessage(receiver, contents);
						else
							result = sender.battchSendMessage(receiver, contents, replyCode);
					}

					if (result < 0) {
						flag = "false";
					} else {
						flag = "true";
					}
				}
			} catch (Exception e) {
				flag = "false";
				log.warn("{}", "##" + e.toString() + " ##");
			}

		}

	}
	* 
	 */
	
	
	/**
	 * 短信包裹
	 * <p>将短信的收信人、内容、SubmitMessageVO对象等信息放入包裹 投递到短信发送队列中去处理</p>
	 * @author Happy
	 *
	 */
	public static class SMSParcels implements Serializable {

		/**
		 * 
		 */
		private static final long serialVersionUID = -4485440734185069877L;
		
		private String content;
		private String[] receiver;
		private String sign;
		private String application;
		private String domainid;
		
		
		
		
		public String getContent() {
			return content;
		}

		public String[] getReceiver() {
			return receiver;
		}


		public String getApplication() {
			return application;
		}

		public String getDomainid() {
			return domainid;
		}

		public String getSign() {
			return sign;
		}

		public SMSParcels(String content, String[] receiver,String sign,
				 String application, String domainid) {
			super();
			this.content = content;
			this.receiver = receiver;
			this.sign = sign;
			this.application = application;
			this.domainid = domainid;
		}
		
		/**
		 * 回馈短信的发送结果
		 * @param result
		 * 		是否发送成功
		 * @throws Exception
		 */
		public void feedback(boolean result) throws Exception{
		}
		
	}


	@Override
	public boolean send(String subject, int subjectType, String summary, IUser responsible, IDocument document,
			IUser webUser) {
		
		String body = "";/*MessageType.getName(type);*/
		boolean falg = false;
		SMSQueueOperator operator = SMSQueueOperator.getInstance();
		
		if (!StringUtil.isBlank(subject)) {
			body += subject.trim();
		}
		body += summary;

//		replyCode = code;

//		this.content = body;
//		this.receiver = receiver.trim().split(",");
		try {
			
			SMSParcels parcels = new SMSParcels(body, new String[] {responsible.getTelephone()}, "", webUser.getDefaultApplication(), webUser.getDomainid());
			
			operator.add(parcels);
			operator.send();
		} catch (Exception e) {
			throw e;
		} finally {
			try {
				PersistenceUtils.closeSessionAndConnection();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return falg;
		}

}
