package com.lerx.v6.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.context.support.ResourceBundleMessageSource;

import com.lerx.analyze.util.AnalyzeUtil;
import com.lerx.mail.obj.Mail;
import com.lerx.mail.obj.Message;
import com.lerx.mail.obj.SmtpSrv;
import com.lerx.mail.util.MailUtil;
import com.lerx.portal.obj.Sms;
import com.lerx.sys.obj.TimeSpanUnit;
import com.lerx.sys.obj.Website;
import com.lerx.sys.util.FileUtil;
import com.lerx.sys.util.HttpUtil;
import com.lerx.sys.util.SecurityUtil;
import com.lerx.sys.util.StringUtil;
import com.lerx.sys.util.TimeUtil;

public class CaptchaUtil {

	public static int send(ResourceBundleMessageSource messageSource, HttpServletRequest request, HttpSession session,
			Sms sms,SmtpSrv srv,Website portal, int targetType, String target,String position,String charset) {
		position="_"+position;
		String vcode=SysUtil.vcode(messageSource);
		/*
		 * 根据配置文件获得允许的截止时间剩余
		 */
		String vartmp = messageSource.getMessage("vcode.sendchar.effective", null, "30m", null);
		TimeSpanUnit tsu = TimeUtil.unixLenAtFmt(vartmp);
		if (session.getAttribute("lastSend"+position) != null) {
			long lastSend = (long) session.getAttribute("lastSend"+position);
			if (lastSend > 0 && (System.currentTimeMillis() - lastSend < tsu.getSeconds())) {
				return -409;
			}
		}
		

		/*
		 * 获取本服务器的安全字符串 security(无则自动生成并读取)
		 */
		String securityStr = SecurityUtil.readWords(messageSource);

		//结束时间
		long endTime = System.currentTimeMillis() + tsu.getSeconds();

		
		/*
		 * 生成加密字符
		 */
		String md5 = StringUtil.md5(String.valueOf(endTime) + "|" + vcode + "|" + securityStr);
		String encryptedStr = String.valueOf(endTime) + "|" + vcode + "|" + md5;
		
		/*encryptedStr=SysUtil.encrypt(vcode, messageSource, session);
		if (encryptedStr==null) {
			return -409;
		}*/

		session.setAttribute("validateEnd"+position, endTime);
		session.setAttribute("encryptedStr"+position, encryptedStr);
		String content;
		if (targetType == 0) {
			content = FileUtil.readRes(messageSource, "template_verify_mail");
		} else {
			content = FileUtil.readRes(messageSource, "template_verify_sms");
		}
		
//		System.out.println("content1:"+content);

		content = AnalyzeUtil.replace(content, "tag", "vcode", vcode);
		String dtfmt = messageSource.getMessage("datetime.fmt.default", null, "yyyy-MM-dd HH:mm:ss", null);
		content = AnalyzeUtil.replace(content, "tag", "effective", TimeUtil.coverLongToStr(endTime, dtfmt));
		String spanTitle = messageSource.getMessage("title.date.span." + tsu.getSpanTitle(), null, " ", null);

		content = AnalyzeUtil.replace(content, "tag", "period", tsu.getSpanSize() + spanTitle);
		content = AnalyzeUtil.replace(content, "tag", "encryptedStr", encryptedStr);
		
		content=HttpUtil.siteImplant(content, portal, request);
//		System.out.println("content2:"+content);
		// 发送
		int r = -1;
		if (targetType == 0) { // 如果验证码发向邮箱

			session.setAttribute("targetMode"+position, 0);

			Mail m = new Mail();
			Message mes = new Message();
			mes.setRecipient(target);
			mes.setBody(content);
			String subject = messageSource.getMessage("mail.subject.title.default", null,
					"New mail from {$tag:sender$}", null);
			subject = AnalyzeUtil.replace(subject, "tag", "portalName", portal.getName());
			mes.setSubject(subject);

			m.setMessage(mes);
			m.setSmtpSrv(srv);
			m.setCharset(charset);

			r = MailUtil.send(m, messageSource,srv, true);
			
		} else { // 如果采用手机验证
			session.setAttribute("targetMode"+position, 1);
			if (sms.getPwd() == null || sms.getPwd().trim().equals("")) {
				r = -11;
			}else {
				if (sms.getUrl() == null || sms.getUrl().trim().equals("")) {
					r = SmsUtil.sendOnTencent(sms, target, content).getResult();
				} else {
					r = SmsUtil.sendOnIhuyi(sms, target, content).getResult();
				}
			}

		}
		
		if (r == 0) {
			session.setAttribute("sendTarget", target);
			session.setAttribute("targetMode", targetType);
			session.setAttribute("lastSend"+position, System.currentTimeMillis());
			if (targetType == 0) {
				session.setAttribute("validateEnd"+"_mailchk", endTime);
				session.setAttribute("encryptedStr"+"_mailchk", encryptedStr);
				session.setAttribute("mail"+"_mailchk", target);
			}else {
				session.setAttribute("validateEnd"+"_mobilechk", endTime);
				session.setAttribute("encryptedStr"+"_mobilechk", encryptedStr);
				session.setAttribute("mobile"+"_mobilechk", target);
			}
			
		}
		
		
		return r;

	}
	
	
	public static int sendmail(ResourceBundleMessageSource messageSource, HttpServletRequest request, HttpSession session,
			Mail mail,Website portal, String position) {
		
		position="_"+position;
		
		
		/*
		 * 根据配置文件获得允许的截止时间剩余
		 */
		String vartmp = messageSource.getMessage("vcode.sendchar.effective", null, "30m", null);
		TimeSpanUnit tsu = TimeUtil.unixLenAtFmt(vartmp);
		if (session.getAttribute("lastSend"+position) != null) {
			long lastSend = (long) session.getAttribute("lastSend"+position);
			if (lastSend > 0 && (System.currentTimeMillis() - lastSend < tsu.getSeconds())) {
				return -409;
			}
		}

		

		// 发送
		int r = MailUtil.send(mail, messageSource,mail.getSmtpSrv(), true);
		
		if (r == 0) {
			session.setAttribute("sendTarget", mail.getMessage().getRecipient());
			session.setAttribute("lastSend"+position, System.currentTimeMillis());
		}
		
		
		return r;

	}
	
	
	public static int valid(ResourceBundleMessageSource messageSource,String vcode,String target,String position,HttpSession session) {
		if (session.getAttribute("sendTarget")==null) {
			return -401;
		}
		String starget=(String) session.getAttribute("sendTarget");
		
		if (starget.indexOf(starget) <0 ) {
			return -416;
		}
		position="_"+position;
		String securityStr = SecurityUtil.readWords(messageSource);
		long endTime=System.currentTimeMillis();
		if (session.getAttribute("validateEnd"+position)!=null) {
			endTime = (long) session.getAttribute("validateEnd"+position);
		}
		long currTime = System.currentTimeMillis();
		if (currTime > endTime) {
			return -409;
		}

		String md5 = StringUtil.md5(String.valueOf(endTime) + "|" + vcode + "|" + securityStr);
		String encryptedStr = String.valueOf(endTime) + "|" + vcode + "|" + md5;

		String encryptedStrSrv = (String) session.getAttribute("encryptedStr"+position);
		if (encryptedStr.equals(encryptedStrSrv)) {
			session.removeAttribute("encryptedStr"+position);
			session.removeAttribute("validateEnd"+position);
			session.removeAttribute("lastSend"+position);
			session.setAttribute("validateSuccess"+position, true);
			return 0;
		} else {
			return -1;
		}
	}

}
