package com.chinacreator.process.service;

import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.chinacreator.common.exception.BusinessException;
import com.chinacreator.common.util.URLUtil;
import com.chinacreator.process.bean.EcbLogBean;
import com.chinacreator.process.bean.EcbProductInfo;
import com.chinacreator.process.bean.EcbResponseBean;
import com.chinacreator.process.dao.DictionaryDao;
import com.chinacreator.process.dao.EcbProductDao;
import com.chinacreator.process.dao.SPDao;
import com.chinacreator.process.util.JsonUtil;

@Component
public class EcbService
{
	
	private static Logger log = Logger.getLogger(EcbService.class);
	
	@Autowired
	private DictionaryDao dictionaryDao;
	
	@Autowired
	private SPDao spDao;
	
	@Autowired
	private EcbProductDao ecbProductDao;
	
  
  public String order(String userid,String cpid,String spid) throws Exception{
	  String resultCode = "0";
	  String errorInfo = "";
	  int temp = 0;
	  long begintime = System.currentTimeMillis();
	  try{
		  EcbResponseBean ecbResponseBean =  queryPorduct(userid, cpid, spid,"0");
		  EcbProductInfo info  =ecbResponseBean.getUserProductInfo().getProductInfos().get(0);
		  if(StringUtils.isEmpty(info.getDiscntStartDate()) || NumberUtils.toLong(info.getDiscntStartDate()) < NumberUtils.toLong(DateFormatUtils.format(new Date(), "yyyyMMddHHmmss"))){
			  info.setDiscntStartDate(DateFormatUtils.format(new Date(), "yyyyMMddHHmmss"));
		  }
		  if(StringUtils.isEmpty(info.getDiscntEndDate()) || NumberUtils.toLong(info.getDiscntEndDate()) < NumberUtils.toLong("20170831235959")){
			  info.setDiscntEndDate("20170831235959");
		  	}
		  temp =1;
		  ecb(info,"0",userid,cpid,spid);
		  //ecbProductDao.saveProductInfo(getProductInfo(info));
	  }catch(Exception e){
		  log.error(userid+"订购失败",e);
		  if(e instanceof BusinessException){
			  resultCode = ((BusinessException) e).getCode();
			  errorInfo =  ((BusinessException) e).getMessage();
		  }else{
			  resultCode = "8000";
			  errorInfo = "系统忙！";
		  }
		  if(spDao.getValue(spid) == 1){
			  throw e;
		  }
	  }finally {
		  saveLog(userid, resultCode, "0", errorInfo, cpid, spid, temp+"",(System.currentTimeMillis()-begintime)+"");
	}
	  return resultCode;
  }
  
  
  public String cancelOrder(String userid,String cpid,String spid,String ordertime) throws Exception{
	  String resultCode = "0";
	  String errorInfo = "";
	  int temp = 0;
	  long begintime = System.currentTimeMillis();
	  try{
		  EcbResponseBean ecbResponseBean = queryPorduct(userid, cpid, spid,"1");
		  EcbProductInfo info = ecbResponseBean.getUserProductInfo().getProductInfos().get(0);
		  if( (StringUtils.isEmpty(info.getDiscntCode()) && StringUtils.isEmpty(info.getPackageCode()) && StringUtils.isEmpty(info.getProductId()))){
				 EcbProductInfo ecbProductInfo = ecbProductDao.queryEcbProductByUser(userid);
				 if(ecbProductInfo == null){
					  throw new BusinessException("9032","ecb退订失败,本地无资费信息" );
				 }
			 }
		  if(info.getDiscntOrderState() != null && info.getDiscntOrderState().equals("2")){
			  throw new BusinessException("9031","ecb禁止用户退订" );
		  }
		 info.setDiscntStartDate(ordertime); 
		 info.setDiscntEndDate(getLastDay(ordertime));
		 temp = 1;
		 ecb(info,"1",userid,cpid,spid);
	  }catch(Exception e){
		  log.error(userid+"退订失败",e);
			  if(e instanceof BusinessException){
				  resultCode = ((BusinessException) e).getCode();
				  errorInfo =  ((BusinessException) e).getMessage();
			  }else{
				  resultCode = "8000";
				  errorInfo = "系统忙！";
			  }
			  if(spDao.getValue(spid) == 1){
				  throw e;
			  }
	  }finally {
		  saveLog(userid, resultCode, "1", errorInfo, cpid, spid, temp+"",(System.currentTimeMillis()-begintime)+"");
	}
	  return resultCode;
  }
  
  public void ecb(EcbProductInfo info,String type,String userid,String cpid,String spid) throws Exception{
	  String resultstr = URLUtil.get(dictionaryDao.getValue("ecbOrderUrl")+"?userid="+userid+"&cpid="+cpid+"&spid="+spid+"&productId="+info.getProductId()
				 +"&packageCode="+info.getPackageCode()+"&discntCode="+info.getDiscntCode()+"&type="+type+"&starttime="+info.getDiscntStartDate()
				+"&endtime="+info.getDiscntEndDate() , NumberUtils.toInt(dictionaryDao.getValue("ecbTimeout")));
		  Map<?,?>  resultMap = JsonUtil.jsonToMap(resultstr);
		 if(!((String) resultMap.get("resultCode")).equals("0")){
			 throw new BusinessException((String)resultMap.get("resultCode"), ((String)resultMap.get("errorInfo")));
		 }
  }
  
  public EcbResponseBean  queryPorduct(String userid,String cpid,String spid,String type) throws Exception{
	  String  result =  URLUtil.get(dictionaryDao.getValue("ecbProductUrl")+"?userid="+userid+"&cpid="+cpid+"&spid="+spid, NumberUtils.toInt(dictionaryDao.getValue("ecbTimeout")));
	  log.info("result===="+result);
	  EcbResponseBean infos = (EcbResponseBean) JsonUtil.jsonToBean(result, EcbResponseBean.class);
	  log.info("infos===="+JsonUtil.objectToJson(infos));
	  if(!infos.getResultCode().equals("0") && !(type.equals("1") && infos.getCode().equals("8888"))){
		  throw new BusinessException(infos.getResultCode(), infos.getErrorInfo());
	  }
	  if(infos.getUserProductInfo() ==null){
		  throw new BusinessException("9036","无产品信息" );
	  }
	  if(infos.getUserProductInfo().getProductInfos()  == null || infos.getUserProductInfo().getProductInfos().size()==0){
		  throw new BusinessException("9034","资费信息信息不全" );
	  }
	  EcbProductInfo info = choseProduct(infos.getUserProductInfo().getProductInfos());
	  log.info("info===="+JsonUtil.objectToJson(info));
	  List<EcbProductInfo> list = new ArrayList<EcbProductInfo>();
	  list.add(info);
	  infos.getUserProductInfo().setProductInfos(list);
	  if(info  == null){
		  throw new BusinessException("9035","未查询出用户资费信息" );
	  }
	  return infos;
  }
  
  public EcbProductInfo choseProduct(List<EcbProductInfo> infos){
	  EcbProductInfo returnBean = null;
	  for (EcbProductInfo ecbProductInfo : infos) {
		  String discntstartime = ecbProductInfo.getDiscntStartDate();
		  String discntendtime = ecbProductInfo.getDiscntEndDate();
			if(StringUtils.isEmpty(discntstartime) ||StringUtils.isEmpty(discntendtime) ){
				continue;
			}
			discntstartime = format(discntstartime);
			discntendtime = format(discntendtime);
			if(NumberUtils.toLong(discntstartime)<= NumberUtils.toLong(getStartdate())  && NumberUtils.toLong(discntendtime)>= NumberUtils.toLong(DateFormatUtils.format(new Date(), "yyyyMMddHHmmss")) ){
				ecbProductInfo.setDiscntStartDate(discntstartime);
				ecbProductInfo.setDiscntEndDate(discntendtime);
				if(returnBean == null){
					 returnBean = ecbProductInfo;
				  }else{
					  if(NumberUtils.toInt(returnBean.getDiscntFee()) > NumberUtils.toInt(ecbProductInfo.getDiscntFee())){
						  returnBean = ecbProductInfo;
					  }else if(NumberUtils.toInt(returnBean.getDiscntFee()) == NumberUtils.toInt(ecbProductInfo.getDiscntFee())){
						  if(NumberUtils.toLong(discntendtime) > NumberUtils.toLong(returnBean.getDiscntEndDate())){
							  returnBean = ecbProductInfo;
						  }
					  }
				  }
			}
	  }
	  if(returnBean != null){
		  if(StringUtils.isEmpty(returnBean.getDiscntValue()) || returnBean.getDiscntValue().equals("0")){
			  returnBean.setSpid("10040");
		  }else if(returnBean.getDiscntValue().equals("1")){
			  returnBean.setSpid("10041");
		  }
	  }
	  return returnBean;
  }
  
  public static String getStartdate(){
	  return  DateFormatUtils.format(DateUtils.addMinutes(new Date(), 5),"yyyyMMddHHmmss");
  }
  
  public static String format(String numstr){
	   int size =14;
	   int neednum = 0;
	   if(numstr.length() < 14){
		   neednum = size - numstr.length() ;
		   StringBuffer strb = new StringBuffer();
		   for (int i = 0; i <neednum; i++) {
			   strb.append("0");
		}
		   return numstr+strb;
	   }
	  return numstr;
 } 
  
  public void saveLog(String userid,String resultCode,String type,String errorInfo,String cpid,String spid,String handle,String times){
	  EcbLogBean info = new EcbLogBean();
	  info.setTimes(times);
	  info.setCpid(cpid);
	  info.setSpid(spid);
	  info.setUserid(userid);
	  info.setResultCode(resultCode);
	  info.setErrorInfo(errorInfo);
	  info.setType(type);
	  info.setHandle(handle);
	  try {
		ecbProductDao.saveLogDao(info);
	} catch (SQLException e) {
		e.printStackTrace();
	}
  }
  
  public static String getLastDay(String timeStr) throws ParseException{
	  Calendar calendar = Calendar.getInstance();  
	  if(!StringUtils.isEmpty(timeStr)){
		 calendar.setTime(DateUtils.parseDate(timeStr, new String[]{"yyyyMMddHHmmss"}));
	  }
	  calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));  
	  return DateFormatUtils.format(calendar, "yyyyMMdd")+"235959";
  }
  
  public static void main(String[] args) {
	String str = "{\"errorInfo\":\"成功\",\"resultCode\":\"0\",\"code\":\"0000\",\"userProductInfo\":{\"productInfos\":[{\"productId\":\"90155946\",\"productName\":\"腾讯天王卡\",\"packageCode\":\"51900772\",\"packageName\":\"普通产品畅视资费包\",\"discntCode\":\"8193753\",\"discntName\":\"标清畅视0元体验套餐\",\"discntFee\":\"0\",\"discntStartDate\":\"20170815233438\",\"discntEndDate\":\"20170831235959\",\"discntOrderState\":\"0\",\"discntValue\":\"\"}],\"userProductId\":\"90155946\",\"userProductName\":\"腾讯天王卡\"}}";
	EcbResponseBean infos = (EcbResponseBean) JsonUtil.jsonToBean(str, EcbResponseBean.class);
  }
}