package com.cab.controller;

import java.awt.Color;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

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

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.cab.controller.CaptchaFactory.CaptchaFactory;
import com.cab.service.ValidationCodeServiceImpl;
import com.cku.config.Global;
import com.cku.core.RESTResponse;
import com.cku.core.ZAErrorCode;
import com.cku.core.ZAException;
import com.cku.patchca.color.SingleColorFactory;
import com.cku.patchca.filter.predefined.CurvesRippleFilterFactory;
import com.cku.patchca.service.ConfigurableCaptchaService;
import com.cku.service.IpAddressServiceImpl;
import com.cku.sms.ZtSmsUtil;
import com.cku.util.Debugger;
import com.cku.util.ServletUtils;
import com.sys.util.CacheUtils;
import com.sys.util.IPLimitUtil;
import com.wf.captcha.base.Captcha;
import com.wf.captcha.utils.CaptchaUtil;

@Controller
@RequestMapping(value = "utils")
public class ValidationCodeController {

	
	@Autowired
	public ValidationCodeServiceImpl validationService;
	@Autowired
	private IPLimitUtil IPLimitUtil;
	
//	private String captchaArray [] = { "png","gif","arithmetic","chineseGif"};
	
	private String captchaArray [] = {"gif"};
	
	@Autowired
	private IpAddressServiceImpl ipAddressService;
	
	@Autowired
	private CacheUtils cacheUtils;
	
	@RequestMapping(value = "/sendNoteYX")
	public void x() {
//		sendNoteYX
		String notification = "您于" + new SimpleDateFormat("yyyy年MM月dd日  HH时mm分").format(new Date()) 
        		+ "已取消了订单号为:" + "123" + "的订单。如非您本人操作，请尽快登录CKU会员中心进行重新报名，以免耽误您的参赛安排。";
		ZtSmsUtil.sendNoteYX(notification, "15652388352");
	}
	
	@RequestMapping(value = "/apply-code")
	public void api_apply(HttpServletResponse response, HttpServletRequest request) throws IOException
	{
		RESTResponse result = new RESTResponse();
		try
		{
			
			String ip = IPLimitUtil.getIpAddr(request);
			// 添加到ipAddressS
			ipAddressService.addIpAddress(ip);
			// 验证ip是否在黑名单
			if(ipAddressService.isBlackList(ip)) {
				throw new ZAException(-1, "该ip已列为黑名单，请联系客服，致电400-660-7000");
			}
			String phone = ServletUtils.getParameter(request, "phone");
			
			String uses = ServletUtils.getParameter(request, "register",null);
			String code = ServletUtils.getParameter(request, "validateCode");
			Debugger.doAssert(StringUtils.isNotBlank(code), ZAErrorCode.ZA_ERC_UNKNOWN, "请输入验证码");
			HttpSession session = request.getSession();
			String validateCode = session.getAttribute("validateCode").toString();
			Debugger.doAssert(StringUtils.isNotBlank(validateCode), ZAErrorCode.ZA_ERC_UNKNOWN, "验证码无效，请从新获取验证码");
			Debugger.doAssert(validateCode.equals(code), ZAErrorCode.ZA_ERC_UNKNOWN, "验证码有误");
			session.setAttribute("validateCode",null);
			// 相同的ip，一天调用10次
			IPLimitUtil.CheckLimit("register", request, 10);
			validationService.applyNewCode(phone,uses);
			
			result = new RESTResponse();
		}
		catch (ZAException e)
		{
			result = new RESTResponse(e.get_code(),e.getMessage());
		}
		
		ServletUtils.writeResponse(response, result);
	}

	@RequestMapping(value = "/apply-code-new")
	public void api_apply_new(HttpServletResponse response, HttpServletRequest request) throws IOException {
		RESTResponse result = new RESTResponse();
		try {
			String ip = IPLimitUtil.getIpAddr(request);
			// 添加到ipAddress
			ipAddressService.addIpAddress(ip);
			// 验证ip是否在黑名单
			if(ipAddressService.isBlackList(ip)) {
				throw new ZAException(-1, "该ip已列为黑名单，请联系客服，致电400-660-7000");
			}
			String phone = ServletUtils.getParameter(request, "phone");
			String uses = ServletUtils.getParameter(request, "register", null);
			String code = ServletUtils.getParameter(request, "validateCode");
			
			Debugger.doAssert(StringUtils.isNotBlank(code), ZAErrorCode.ZA_ERC_UNKNOWN, "请输入验证码");
			String deviceCode = ServletUtils.getParameter(request, "deviceCode");
			Debugger.doAssert(StringUtils.isNotBlank(deviceCode), ZAErrorCode.ZA_ERC_UNKNOWN, "参数错误");
			String validateCode = (String) cacheUtils.get(deviceCode);
			
			Debugger.doAssert(StringUtils.isNotBlank(validateCode), ZAErrorCode.ZA_ERC_UNKNOWN, "验证码无效，请从新获取验证码");
			if(Global.isDevMode()) {
				Debugger.doAssert(validateCode.equals(code) || "6666".equals(code), ZAErrorCode.ZA_ERC_UNKNOWN, "验证码有误");
			}else {
				Debugger.doAssert(validateCode.equals(code), ZAErrorCode.ZA_ERC_UNKNOWN, "验证码有误");
			}
			// 相同的ip，一天调用10次
			IPLimitUtil.CheckLimit("register", request, 10);
			validationService.applyNewCode(phone, uses);
			cacheUtils.remove(deviceCode);
			result = new RESTResponse();
		} catch (ZAException e) {
			result = new RESTResponse(e.get_code(), e.getMessage());
		}

		ServletUtils.writeResponse(response, result);
	}
	
	@RequestMapping(value = "/getCode")
	public void getCode(HttpServletResponse response, HttpServletRequest request) throws IOException {
		RESTResponse result = new RESTResponse();
		try {
			String phone = ServletUtils.getParameter(request, "phone");

			String code = validationService.aa(phone);

			result = new RESTResponse("msg", code);
		} catch (Exception e) {
			result = new RESTResponse(e);
		}

		ServletUtils.writeResponse(response, result);
	}

	
	@RequestMapping(value = "/validateCode")
	public void validateCode(HttpServletRequest request,HttpServletResponse response) throws Exception{
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType("image/jpeg");
		
		ConfigurableCaptchaService cs = new ConfigurableCaptchaService();
		cs.setColorFactory(new SingleColorFactory(new Color(25, 60, 170)));
		cs.setFilterFactory(new CurvesRippleFilterFactory(cs.getColorFactory()));
		
		com.cku.patchca.service.Captcha captcha = cs.getCaptcha();
		HttpSession session = request.getSession();
		session.setAttribute("validateCode",captcha.getChallenge());
		
		ImageIO.write(captcha.getImage(),"png", response.getOutputStream()); 
	}
	
	
	@RequestMapping(value = "/validateCodeGif")
	public void validateCodeGif(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String deviceCode = ServletUtils.getParameter(request, "deviceCode");
		Debugger.doAssert(StringUtils.isNotBlank(deviceCode), ZAErrorCode.ZA_ERC_UNKNOWN, "缺少必要参数");
		CaptchaFactory captchaFactory = new CaptchaFactory();
		Captcha captcha = captchaFactory.getCaptcha(getCaptchaString());
		captcha.setCharType(Captcha.TYPE_ONLY_NUMBER);
		captcha.setFont(Captcha.FONT_9);	
		cacheUtils.put(deviceCode, captcha.text().toLowerCase());
		CaptchaUtil.out(captcha, request, response);
	}
	
	private String getCaptchaString() {
		int random = new Random().nextInt(captchaArray.length);
		return captchaArray[random];
	}
}
