package com.chinacreator.video.validate;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.chinacreator.video.bean.ChannelBean;
import com.chinacreator.video.bean.CpSpBean;
import com.chinacreator.video.bean.OrderInfo;
import com.chinacreator.video.exception.BussinessException;
import com.chinacreator.video.mapper.ChannelDao;
import com.chinacreator.video.mapper.CpSpDao;
import com.chinacreator.video.util.DesUtil;

@Component
public class MobValidate {
	
	@Autowired
	private CpSpDao CpSpDao;
	
	@Autowired
	private ChannelDao channelDao;
	
	public void validate(OrderInfo orderInfo) throws Exception {
		String userid = orderInfo.getUserid();
		if(StringUtils.isEmpty(userid)) {
			throw new BussinessException("10007", "手机号不能为空");
		}
		CpSpBean cpSpBean = CpSpDao.getCpSp(orderInfo.getCpid(), orderInfo.getSpid());
		if(cpSpBean == null) {
			throw new BussinessException("10010", "cpid/spid错误");
		}
		ChannelBean channelBean = channelDao.queryChannel(orderInfo.getChannel());
		try {
			userid = DesUtil.decode(userid, channelBean.getPassword());
			if(isValid(userid) && userid.length() == 11){
				orderInfo.setUserid(userid);
			}else{
				throw new BussinessException("10009", "手机号错误");
			}	
		} catch (Exception e) {
			if(e instanceof BussinessException) {
				throw e;
			}else {
				throw new BussinessException("10008", "手机号加密错误");
			}
		}
	}
	
	/**
	 * 根据渠道标识验证手机号码，用于无CPID或SPID参数的场景
	 * @param orderInfo
	 * @throws Exception
	 */
	public void validateByChannel(OrderInfo orderInfo) throws Exception {
		String userid = orderInfo.getUserid();
		if(StringUtils.isEmpty(userid)) {
			throw new BussinessException("10007", "手机号不能为空");
		}
		ChannelBean channelBean = channelDao.queryChannel(orderInfo.getChannel());
		try {
			userid = DesUtil.decode(userid, channelBean.getPassword());
			if(isValid(userid) && userid.length() == 11){
				orderInfo.setUserid(userid);
			}else{
				throw new BussinessException("10009", "手机号错误");
			}	
		} catch (Exception e) {
			if(e instanceof BussinessException) {
				throw e;
			}else {
				throw new BussinessException("10008", "手机号验证失败");
			}
		}
	}
	
	private boolean isValid(String usermob){
        if (usermob == null) {
            return false;
        }
        usermob = usermob.replaceAll("[\\s-]", "");
        
        return usermob.matches(".*(1\\d{10}).*");	    
	}
}
