package com.lerx.handlers;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lerx.annotation.Token;
import com.lerx.app.util.SafeStrUtil;
import com.lerx.dao.iface.IPortalDao;
import com.lerx.dao.iface.IUserDao;
import com.lerx.entities.Portal;
import com.lerx.mail.obj.SmtpSrv;
import com.lerx.portal.obj.Sms;
import com.lerx.sys.obj.Website;
import com.lerx.sys.util.RandomNumUtil;
import com.lerx.sys.util.StringUtil;
import com.lerx.v6.util.CaptchaUtil;
import com.lerx.v6.util.ConfigUtil;
import com.lerx.v6.util.PortalUtil;

/*
 * 验证码
 */
@RequestMapping("/action_captcha")
@Controller
public class CaptchaHandler {
	
	@Autowired
	private ResourceBundleMessageSource messageSource;
	
	@Value("${sms.account}")
	private String smsAccount;
	
	@Value("${sms.url}")
	private String smsUrl;
	
	@Value("${sms.appid}")
	private String smsAppid;
	
	@Value("${sms.pwd}")
	private String smsPwd;
	
	@Value("${mail.server.host}")
	private String srvhost;
	
	@Value("${mail.server.login.user}")
	private String mailuser;
	
	@Value("${mail.server.login.password}")
	private String mailpwd;
	
	@Value("${mail.server.sender}")
	private String mailsender;
	
	@Value("${mail.server.auth}")
	private String mailauth;
	
	@Value("${mail.charset}")
	private String mailcharset;

	@Autowired
	private IPortalDao portalDaoImpl;
	
	@Autowired
	private IUserDao userDaoImpl;
	
	
	@RequestMapping("/randomNum")
	@Token(ajax=false,csrf=true,contrast = true)
	public void randomNum(HttpServletRequest request,HttpServletResponse response,HttpSession session,String key,@RequestParam(value = "time", required = false) Long time) throws Exception{
		
		String captchaMode = messageSource.getMessage("captcha.mode", null, "blend", null);
		int imgMode;
		if (captchaMode.trim().equalsIgnoreCase("words")){	//
			imgMode=2;
		}else if (captchaMode.trim().equalsIgnoreCase("number")){
			imgMode=1;
		}else{
			imgMode=0;
		}
		
		RandomNumUtil randomNum = new RandomNumUtil(response,60,18,4,18,imgMode);
		String  safeSessionStr=SafeStrUtil.getstr(messageSource, request,key);
		session.setAttribute(safeSessionStr, randomNum.getRandomCode());
		
	}
	
	
	@RequestMapping("/send")
	@ResponseBody
	@Token(ajax=true,csrf=true,contrast = true)
	public int send(String target,@RequestParam(value = "mode", required = false) Integer mode,@RequestParam(value = "lookup", required = false) Integer lookup,HttpServletRequest request,HttpServletResponse response,HttpSession session) throws Exception{
		
		/*
		 * mode & sendM
		 * mode 0:email
		 * mode 1:phone
		 */
		int sendM = -1;
		Portal portal=portalDaoImpl.query_update();
		if (mode!=null) {
			sendM=mode;
		}
		if (sendM == -1) {
			
			if (portal.getCodeSendMode()==0) {	//如果验证码发向邮箱
				sendM=0;
				if (target == null || !StringUtil.emailTest(target)) {
					return -400;
				}
				if (!ConfigUtil.mailChk(messageSource, target)) {
					return -403;
				}
			}else {//如果发向手机
				sendM=1;
				if (!StringUtil.phoneTest(target.trim())) {
					return -400;
				}
			}
		}
		
		if (lookup==null) {
			lookup=0;
		}
		
		if (lookup > 0) {
			if (sendM==1) {	//查找手机
				if (userDaoImpl.findByMobile(target, 0) != null) {
					return -502;
				}
			}else {			//查找邮箱
				if (userDaoImpl.findByEmail(target, 0) != null) {
					return -502;
				}
			}
		}
		
		Sms sms=new Sms();
		sms.setAccount(smsAccount);
		sms.setAppid(Integer.valueOf(smsAppid));
		sms.setPwd(smsPwd);
		sms.setUrl(smsUrl);
		sms.setCharset(messageSource.getMessage("charset", null, "UTF-8", null));
		SmtpSrv srv = new SmtpSrv();
		srv.setHost(srvhost);
		srv.setUser(mailuser);
		srv.setPassword(mailpwd);
		srv.setSender(mailsender);
		
		if (mailauth!=null && mailauth.trim().equalsIgnoreCase("true")) {
			srv.setAuth(true);
		}else {
			srv.setAuth(false);
		}
		
		Website site = PortalUtil.lead(portal);
		
		int r=CaptchaUtil.send(messageSource, request, session,sms,srv, site, sendM, target,"default",mailcharset);
		if (r>=0) {
//			session.setAttribute("sendTarget", target);
			session.setAttribute("targetMode", sendM);
		} 
		return r;
	}
	
	
	@ResponseBody
	@RequestMapping("/validate")
	@Token(ajax=true,csrf=true,contrast = true)
	public int validate(String vcode,String target,HttpServletRequest request,HttpServletResponse response,HttpSession session) throws Exception{
		return CaptchaUtil.valid(messageSource,vcode,target,"default",session);
		
		
	}
	
	
	
	
	/*public static void main(String[] args) throws ParseException, Exception {
		
		System.out.println(phoneTest("15015158766"));
	}*/
	
	
		
		
}
