package com.chinacreator.video.validate;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
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.CpSpBean;
import com.chinacreator.video.exception.BussinessException;
import com.chinacreator.video.mapper.ChannelBusiLimitDao;
import com.chinacreator.video.mapper.ChannelDao;
import com.chinacreator.video.mapper.CpSpDao;
import com.chinacreator.video.mapper.DictionaryDao;
import com.chinacreator.video.util.IpAddrUtil;
import com.chinacreator.video.bean.OrderInfo;

@Component
public class ChannelValidate {
	
	public Logger logger = Logger.getLogger("testredis");

	@Autowired
	private ChannelDao channelDao;
	
	@Autowired
	private CpSpDao CpSpDao;
	
	@Autowired
	private ChannelBusiLimitDao cblDao;
	
	@Autowired
	private DictionaryDao dictionaryDao;
	
	@Autowired
	private IpValidate ipValidate;
	
	public void validate(String channel) throws BussinessException {
		try {
			if(StringUtils.isEmpty(channel)) {
				throw new BussinessException("10023", "渠道参数不能为空");
			}
			ChannelBean channelBean = channelDao.queryChannel(channel);
			if(channelBean == null) {
				throw new BussinessException("10024", "渠道参数错误");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw e;
		}
	}
	

	/**
	 * handle接口渠道验证（分两类，一类为非二级渠道配置验证，另一类为二级渠道配置验证）
	 * @param orderInfo
	 * @return
	 * @throws BussinessException
	 */
	public boolean validate(OrderInfo orderInfo) throws BussinessException {
		//是否为渠道建设的二级渠道
		boolean hasChannelBuild = false;
		try {
			String channel = orderInfo.getChannel();
			String cpid = orderInfo.getCpid();
			String spid = orderInfo.getSpid();
			
			//只能是订购和退订
			if(!"0".equals(orderInfo.getType()) && !"1".equals(orderInfo.getType())){
				throw new BussinessException("10023", "参数不合法=>type");
			}
			//判断参数是否这空
			if(StringUtils.isEmpty(channel)
					|| StringUtils.isEmpty(cpid)
					|| StringUtils.isEmpty(spid)) {
				throw new BussinessException("10023", "参数不合法");
			}
			
			//SPID和CPID是否匹配
			CpSpBean cpSpBean = CpSpDao.getCpSp(cpid, spid);
			if(cpSpBean == null){
				throw new BussinessException("10023", "参数不合法=>cpid&spid");
			}
			
			//渠道是否合法
			ChannelBean channelBean = cblDao.qryChannelConfById(channel);
			if(channelBean == null) {
				throw new BussinessException("10024", "渠道参数错误"+channel);
			}
			
			//是否为后向产品
			/**
			if(cblDao.hasBackBusiConf(cpid, spid) > 0){
				throw new BussinessException("10023", "参数不合法==>"+spid);
			}
			**/
			

						
			//渠道建设新增加的渠道信息验证
			if("1".equals(channelBean.getIspage()) && "对外接口类".equals(channelBean.getShape())){
				
				//是否为普通前向产品，也不是前向合约产品
				if(cblDao.qrySpinfoConf(spid,"1") <= 0 && cblDao.qrySpinfoConf(spid,"3") <= 0){
					throw new BussinessException("10011", "渠道："+channel+"无权限办理业务："+spid);
				}
				//是二级渠道配置
				hasChannelBuild = true;
				//一级渠道ID
				String parentid = channelBean.getParentid();
				ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
				HttpServletRequest request = attributes.getRequest();
				//IP白名单
				String confip = channelBean.getIp();
				//上线时间
				String onlinetime = channelBean.getOnlinetime();
				//下线时间
				String offlinetime = channelBean.getOfflinetime();	
				//当前时间
				String currtime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
				//判断当前时间是否在允许范围内
				if(Long.parseLong(currtime) < Long.parseLong(onlinetime) 
					|| Long.parseLong(currtime) > Long.parseLong(offlinetime)){
					throw new BussinessException("10024", "渠道已失效=>"+channel);
				}
				
				//判断一级渠道是否有效
				if(cblDao.qryOneChannelConf(parentid) <= 0){
					throw new BussinessException("10024", "一级渠道已失效=>"+parentid);
				}
				
				//二级配置渠道IP验证
				ipValidate.volidate(confip, orderInfo);
								
				List<HashMap<String, String>> dataList = cblDao.qryChannelBusiLimitConf(channel, orderInfo.getType());
				
				/*******************************************
				 当TB_CHANNEL_BUSILIMIT_CONF表有允许办理的业务配置，那么就只能办理配置的业务，如果有禁止办理的业务配置，那只要有配置的，都不能办理
				 */
				if(dataList != null && dataList.size() > 0){
					//是否有允许订购限制
					String limittype = "";
					String limittypespid = "";
					//是否包含要办理的SPID
					boolean hascontains = false;
					for(HashMap<String, String> hm : dataList){
						if("".equals(limittype)){
							limittype = hm.get("LIMITTYPE");
						}
						//办理的SPID有配置
						if(spid.equals(hm.get("SPID"))){
							hascontains = true;
							limittypespid = hm.get("LIMITTYPE");
						}
					}
					
					//有配置允许办理的业务，且当前业务没有允许办理的业务内
					if("0".equals(limittype) && !hascontains){
						throw new BussinessException("10011", "渠道："+channel+"无权限办理业务=>"+spid);
					}
					//有配置允许办理的业务，但当前SPID为禁止办理
					if("0".equals(limittype) && "1".equals(limittypespid)){
						throw new BussinessException("10011", "渠道："+channel+"无权限办理业务==>"+spid);
					}
					//有配置禁止办理的业务，且当前业务在禁止办理的业务内
					if("1".equals(limittype) && hascontains){
						throw new BussinessException("10011", "渠道："+channel+"无权限办理业务===>"+spid);
					}
				}
				
				//子渠道为空，则把主渠道标识填充到子渠道，用于统计（黄一鹰的需求）
				if(StringUtils.isEmpty(orderInfo.getSubchannel())){
					orderInfo.setSubchannel(channel);
				}
			}
		} catch (Exception e) {
			if(e instanceof BussinessException) {
				throw e;
			}else{
				e.printStackTrace();
				throw e;
			}		
		}
		
		return hasChannelBuild;
	}
}