package com.chinacreator.video.validate;

import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.chinacreator.video.bean.ChannelBean;
import com.chinacreator.video.bean.OrderInfo;
import com.chinacreator.video.exception.BussinessException;
import com.chinacreator.video.mapper.ChannelDao;
import com.chinacreator.video.mapper.CommConfDao;
import com.chinacreator.video.util.DesUtil;
import com.chinacreator.video.util.IpAddrUtil;
import com.chinacreator.video.util.MD5;

@Component
public class BusiValidate {
	
	public Logger logger = Logger.getLogger(BusiValidate.class);
	
	@Autowired
	private CommConfDao commConfDao;
	
	@Autowired
	private ChannelDao channelDao;
	
    @Autowired
    private IpValidate ipValidate;
	
	/**
	 * 验证时间戳
	 * @param
	 * @throws BussinessException
	 */
	public void valiTime(OrderInfo orderInfo) throws Exception {
		String timetamp = orderInfo.getTimestamp();
		if(StringUtils.isEmpty(timetamp)) {
			throw new BussinessException("10001", "timestamp不能为空");
		}
		long localTimestamp = (System.currentTimeMillis())/1000;
		try {
			if((localTimestamp - NumberUtils.toLong(timetamp)) >300 || (localTimestamp - NumberUtils.toLong(timetamp)) <-300) {
				System.out.println("====================="+(localTimestamp - NumberUtils.toLong(timetamp)));
				throw new BussinessException("10002", "timestamp已失效");
			}
		} catch (Exception e) {
			if(e instanceof BussinessException) {
				throw e;
			}else {
				throw new BussinessException("10002", "timestamp已失效");
			}
		}
	}
	
	/**
	 * 验证渠道
	 * @param orderInfo
	 * @throws Exception
	 */
	public void valiChannel(OrderInfo orderInfo) throws Exception {
		if(StringUtils.isEmpty(orderInfo.getChannel())) {
			throw new BussinessException("10023", "渠道参数不能为空");
		}
		ChannelBean channelBean = channelDao.queryChannel(orderInfo.getChannel());
		if(channelBean == null) {
			throw new BussinessException("10024", "渠道参数错误");
		}
	}
	
	/**
	 * 验证手机号码
	 * @param orderInfo
	 * @throws BussinessException
	 */
	public void valiMob(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.setEnuserid(orderInfo.getUserid()); //保存加密的手机顺驰，用于参数返回
				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}).*");	    
	}
	
	/**
	 * 签名验证
	 * @param orderInfo
	 * @throws BussinessException
	 */
	public void valiSign(OrderInfo orderInfo) throws BussinessException{
		try {
			String lcalsign = getSign(orderInfo);
			lcalsign += channelDao.queryChannel(orderInfo.getChannel()).getPassword();
			lcalsign = MD5.MD5Encode(lcalsign);
			if(!lcalsign.equals(orderInfo.getSignature())) {
				throw new BussinessException("10006", "签名校验失败");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new BussinessException("10006", "签名校验失败");
		}
	}
	
	/**
	 * 拼接签名信息 cpid+spid+userid+channel+timestamp
	 * @param orderInfo
	 * @return
	 */
	private String getSign(OrderInfo orderInfo) {
		if (orderInfo == null) {
			return "";
		}
		StringBuilder strb = new StringBuilder();
		strb.append(orderInfo.getCpid());
		strb.append(orderInfo.getSpid());
		strb.append(orderInfo.getUserid());
		strb.append(orderInfo.getChannel());
		strb.append(orderInfo.getTimestamp());
		return strb.toString();
	}
	/*
	 * 检查CPID和SPID
	 * 如只验证SPID，匹配上了会设置对应的CPID
	 */
	public void valiCpSp(OrderInfo orderInfo) throws BussinessException{
		List<Map> cpspInfo = commConfDao.getCpSpInfo();
		boolean reuslt = false;
		//CPID限制，SPID不限制
		if(!"0".equals(orderInfo.getCpid()) && "0".equals(orderInfo.getSpid())){
			for(Map map : cpspInfo){
				if(orderInfo.getCpid().equals(map.get("CPID"))){
					reuslt = true;
					break;
				}
			}		
		}else if(!"0".equals(orderInfo.getCpid()) && !"0".equals(orderInfo.getSpid())){ //CPID和SPID都限制
			for(Map map : cpspInfo){
				if(orderInfo.getCpid().equals(map.get("CPID")) && orderInfo.getSpid().equals(map.get("SPID"))){
					reuslt = true;
					break;
				}
			}
		}else if("0".equals(orderInfo.getCpid()) &&  !"0".equals(orderInfo.getSpid())){ //CPID不限制，但SPID要限制
			for(Map map : cpspInfo){
				if(orderInfo.getSpid().equals(map.get("SPID"))){//SPID相同
					orderInfo.setCpid((String)map.get("CPID"));//设置CPID	
					reuslt = true;
					break;
				}
			}		
		}else if("0".equals(orderInfo.getCpid())){ //CPID不限制
			reuslt = true;
		}
		if(!reuslt) {
			throw new BussinessException("10010", "cpid/spid错误");
		}
	}
	
	/**
	 * IP限制验证
	 * @param orderInfo
	 * @param  业务类型，qry查询，tran办理
	 * @return
	 */
	public void valiIp(OrderInfo orderInfo) throws BussinessException{
		ipValidate.volidate(orderInfo, "1");
		/****
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = attributes.getRequest();
		String ip = IpAddrUtil.getIpAddr2(request, orderInfo);
		logger.info("ip:"+ip);
		try {
			//busitype 业务类型，1查询，0办理	 
			List<Map> list = commConfDao.getIpLimitConf("1",orderInfo.getChannel());
			//System.out.println(new Date().toLocaleString());
			//System.out.println("list: "+list);
			if(list == null || list.size() == 0){
				throw new BussinessException("10011", "无业务办理配置信息");
			}else{
				boolean result = false;
				boolean hasExists = false;
				//[{CHANNEL=TX20_wtqd, SPID=1167, IP=172.16.33.16, CPID=youtu}]
				for(Map map : list){
					//CPID级别验证
					if("*".equals(map.get("CPID"))){ //不限CPID
						hasExists = true;
					}else if(orderInfo.getCpid().equals(map.get("CPID")) 
							&& ((orderInfo.getSpid() != null && orderInfo.getSpid().equals(map.get("SPID"))) || "*".equals(map.get("SPID")))){
						hasExists = true;
					}
					
					if(hasExists){
						if("*".equals(map.get("IP"))){
							result = true;
						}else if(map.get("IP") != null && !"".equals(map.get("IP"))){
							String [] ips = map.get("IP").toString().split("\\|");
							logger.info("ips:"+ips);
							for(String str : ips){
								if(str != null && ip != null && str.contains(ip)){
									result = true;
								}
								//如果IP地址配置有*号，访问的IP包含*号前面的部分
								if(!result && str.indexOf("*") != -1 && ip.startsWith(str.split("[*]")[0])){
									result = true;
								}
							}
						}
						
						break;
					}
				}
				if(!hasExists){ //无业务配置
					throw new BussinessException("10011", "无业务办理配置信息");
				}
				if(!result){
					throw new BussinessException("10005", "IP验证失败:"+ip);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			if(e instanceof BussinessException) {
				throw e;
			}else {
				e.printStackTrace();
				if(e.getMessage() != null && e.getMessage().indexOf("SQLException") != 0){
					throw new BussinessException("10014", "IP限制验证出现SQLException异常。");
				}else{
					throw new BussinessException("10015", "IP限制验证出现异常，"+e.getMessage());
				}
			}
		}
		*****/
	}
}
