package com.cab.service;

import java.io.IOException;
import java.util.Date;
import java.util.Random;

import org.apache.commons.httpclient.HttpException;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cab.dao.CabSysUserMapper;
import com.cab.dao.ValidationCodeMapper;
import com.cab.model.CabSysUser;
import com.cab.model.ValidationCode;
import com.cku.config.Global;
import com.cku.core.ZAErrorCode;
import com.cku.core.ZAException;
import com.cku.sms.ZtSmsUtil;
import com.cku.util.Debugger;
import com.cku.util.StringUtils;

@Service("validationCodeService")
public class ValidationCodeServiceImpl {
	
	private static final Logger logger = Logger.getLogger(ValidationCodeServiceImpl.class);

	@Autowired
	public ValidationCodeMapper validationCodeMapper;
	
	@Autowired
	public CabSysUserMapper cabSysUserMapper;

	public static int CODE_ALIVE_TIME_MINUTE = 10; // 10 minutes actived for phone code.
	public static int CODE_APPLY_INTERVAL = 1 * 60 * 1000; // 1 minute for apply interval.
	public static String CODE_APPLY_SMS_CONTENT ="您注册宠爱王国的验证码为：";
	public static String CODE_APPLY_SMS_CONTENT2 ="您正在重置宠爱王国密码，验证码为：";
	public static String CODE_APPLY_SMS_CONTENT3 ="您正在绑定宠爱王国账号，验证码为：";
	public static String CODE_APPLY_SMS_CONTENT4 ="您正在设置宠爱王国支付密码，验证码为：";
	public static String CODE_APPLY_SMS_END ="请于10分钟内正确输入验证码（如不是本人操作请忽略此信息）";

	public void verifyCodeAndUse(String phone, String code) throws ZAException
	{
		ValidationCode vc = validationCodeMapper.selectByPrimaryKey(phone);

		Debugger.doAssert(vc != null, ZAErrorCode.ZA_ERC_VALIDATION_CODE_FAILED, "Code not exists");
		if(Global.isDevMode()) {
			Debugger.doAssert(vc.getValidationCode().equals(code) || "6666".equals(code), ZAErrorCode.ZA_ERC_VALIDATION_CODE_FAILED,
					"Error code number");
		}else {
			Debugger.doAssert(vc.getValidationCode().equals(code), ZAErrorCode.ZA_ERC_VALIDATION_CODE_FAILED,
					"Error code number");
		}
		Date now = new Date(), codeTime = vc.getCodeTime();
		Debugger.doAssert(now.getTime() - codeTime.getTime() < CODE_ALIVE_TIME_MINUTE * 60 * 1000,
				ZAErrorCode.ZA_ERC_VALIDATION_CODE_TIMEOUT, "Code time is invalid");

		ValidationCode vc2 = new ValidationCode();
		vc2.setCodeTime(new Date(0));
		vc2.setPhone(phone);

		validationCodeMapper.updateByPrimaryKeySelective(vc2);
	}

	public void applyNewCode(String phone,String uses) throws ZAException, HttpException, IOException
	{
		Debugger.doAssert(StringUtils.isMobile(phone), ZAErrorCode.ZA_ERC_INVALID_PARAMETER, "非法手机号码");
		ValidationCode vc = validationCodeMapper.selectByPrimaryKey(phone);
		CabSysUser user = cabSysUserMapper.selectByUserPhone(phone);
		//判断是否为注册时发送验证码，注册时验证手机号是否被注册。
		if("register".equals(uses)||"bound".equals(uses)){
			Debugger.doAssert(user==null, ZAErrorCode.ZA_ERC_PHONE_REPEAT, "该手机号已注册或已被绑定");
		}
		if("resetPassword".equals(uses)){
			Debugger.doAssert(user!=null, ZAErrorCode.ZA_ERC_KEY_NOT_FOUND, "该手机号未注册");
		}
		boolean insert = true;
		Date now = new Date();
		if (vc != null)
		{
			insert = false;
			Date lastApply = vc.getApplyTime();

			Debugger.doAssert(now.getTime() - lastApply.getTime() > CODE_APPLY_INTERVAL, ZAErrorCode.ZA_ERC_VALIDATION_CODE_FAILED,
					"验证码每隔1分钟才能请求一次");
		}
		else
		{
			vc = new ValidationCode();
			vc.setPhone(phone);
		}

		String code = _createRandomString(4, s_codeCharList);

		String[] params = new String[] { code, String.valueOf(CODE_ALIVE_TIME_MINUTE) };

		//云之讯
		//SmsCode.publishToUCPASS(phone, params);
		String used = CODE_APPLY_SMS_CONTENT;

		if("register".equals(uses)){//注册
			used = CODE_APPLY_SMS_CONTENT;
		}else if("resetPassword".equals(uses)){//重置
			used = CODE_APPLY_SMS_CONTENT2;
		}else if("bound".equals(uses)){//绑定
			used = CODE_APPLY_SMS_CONTENT3;
		}else if("setPayPwd".equals(uses)){//设置支付密码
			used = CODE_APPLY_SMS_CONTENT4;
		}
		// 原短信发送接口
//		String result = ZtSmsCode.sendNote(used+code+" "+CODE_APPLY_SMS_END+"【宠爱王国】",phone);
		// 新短信发送接口
		String result = ZtSmsUtil.sendVerificationCode(used + code, phone, used);
		logger.info("========= send_sms result:" + result);
		vc.setApplyTime(now);
		vc.setCodeTime(now);
		vc.setValidationCode(code);
		//判断手机号是否被注册 001372 762
		if (insert)
		{
			validationCodeMapper.insert(vc);
		}
		else
		{
			validationCodeMapper.updateByPrimaryKey(vc);
		}
	}

	private static String _createRandomString(int number, char[] charList) {
		Random rand = new Random();
		char[] charArr = new char[number];
		for (int i = 0; i < number; ++i) {
			int x = rand.nextInt(charList.length);
			charArr[i] = charList[x];
		}

		return new String(charArr);
	}

	private static char[] s_codeCharList = new char[] { '0', '1', '2', '3',
			'4', '5', '6', '7', '8', '9' };

	public String aa(String phone){
		ValidationCode vc = validationCodeMapper.selectByPrimaryKey(phone);
		return vc.getValidationCode();
	}
}
