package com.chinacreator.process.util;

import java.sql.SQLException;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;

import com.chinacreator.common.exception.BusinessException;
import com.chinacreator.process.bean.ECBBean;
import com.chinacreator.process.dao.DictionaryDao;
import com.chinacreator.process.dao.EcbConfigDao;
import com.chinacreator.process.dao.WhiteDao;

public class EcbUtils {

	public static void queryEcb(String cpid,String spid,String province,String userid) throws SQLException, BusinessException{
		EcbConfigDao ecbConfigDao = SpringUtils.getBean(EcbConfigDao.class);
		ECBBean ecbbean = ecbConfigDao.queryConfig(spid, cpid, province);
		WhiteDao whiteDao = SpringUtils.getBean(WhiteDao.class);
			if(ecbbean != null && ecbbean.getStatus() == 0 && !whiteDao.isWhiteUser(userid, cpid)) {
				  String result = null;
			      try {
			    	  DictionaryDao  dictionaryDao = SpringUtils.getBean(DictionaryDao.class);
			          result = URLUtil.get(
			        		dictionaryDao.getValue("ecbUrl") + "?userid=" + userid + "&cpid=" + cpid + "&spid=" + spid, 
			          NumberUtils.toInt(dictionaryDao.getValue("ecbTimeout")));
			      } catch (Exception e) {
			    	  throw new BusinessException("10005","三户查询异常或超时");
			      }
			      if (result == null) {
			    	  throw new BusinessException("10006","三户查询结果返回异常");
			      }
			    	  Map<?,?> map = JsonUtil.jsonToMap(result);
			          if ((!map.get("resultCode").toString().equals("0"))) {
			            String errorInfo = "用户三户查询结果异常";
			            throw new BusinessException(map.get("resultCode").toString(),errorInfo);
			          }
			          if(StringUtils.isNotEmpty(ecbbean.getLimit()) && map.get("pacakge") != null && StringUtils.isNotEmpty(map.get("pacakge").toString())) {
				    	  String[] strLimt = ecbbean.getLimit().split("\\|\\|");
				    	  if(strLimt != null && strLimt.length>0) {
				    		  for (String string : strLimt) {
								if(map.get("pacakge").toString().contains(string.replaceAll("\\*", ""))) {
									 throw new BusinessException("10004","三户套餐限制");
								}
							}
				    	  }
				      }
			}
	}
}
