package com.chinacreator.video.restful.service;

import com.chinacreator.video.bean.OrderInfo;
import com.chinacreator.video.exception.BussinessException;
import com.chinacreator.video.mapper.CommConfDao;
import com.chinacreator.video.service.CommonService;
import com.chinacreator.video.validate.*;

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

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

/**
 * 深报订购关系同步服务类
 * @author xu.zhou
 * @date 20220214
 */
@Component
public class SbSyncService {
	
	@Autowired
	private ChannelValidate channelValidate;
	
	@Autowired
	private IpValidate ipValidate;
	
	@Autowired
	private MobValidate mobValidate;
	
	@Autowired
	private TimetampValidate timetampValidate;
	
	@Autowired
	private SignValidate signValidate;
	
	@Autowired
	private ParamValidate paramValidate;
	
	@Autowired
	private CommConfDao commConfDao;
	
	@Autowired
	private CommonService commonService;
	
	private static Logger logger = Logger.getLogger(SbSyncService.class);
	
	private static Logger log = Logger.getLogger("muorder");
	
	public void busiCheck(OrderInfo orderInfo) throws Exception{
		//深报免流支撑
		//200000000033
		if("200000000033".equals(orderInfo.getChannel())){
			/**
			      深报免流
			  cpid：sbml
			  spid：1196
			 */
			orderInfo.setCpid("sbml");
			orderInfo.setSpid("1196");
			
			HashMap<String, String> params = new HashMap<String, String>();
			params.put("channel", "");
			params.put("userid", "");
			params.put("cpid", ""); 
			params.put("spid", "");
			params.put("opertime", "");
			params.put("type", "0,1"); //此参数只能是0或1
			params.put("timestamp", "");
			params.put("signature", "");
			paramValidate.validate(orderInfo,params);
			SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
			try {
				formatter.parse(orderInfo.getOpertime());
			} catch (Exception e) {
				throw new BussinessException("80015", "参数异常，opertime=>"+orderInfo.getOpertime());
			}
		}else{
			//paramValidate.validate(orderInfo,null);
		    throw new BussinessException("80015", "参数异常，channel");
		}


		//timetamp验证
		timetampValidate.validate(orderInfo.getTimestamp());
		//渠道验证
		channelValidate.validate(orderInfo.getChannel());
		//ip验证
		ipValidate.volidate(orderInfo);
		//深报免流支撑
		//200000000033
		if("200000000033".equals(orderInfo.getChannel())){
			String signstr = this.getSign(orderInfo);
			//签名验证
			signValidate.validate(orderInfo, signstr);
		}else{
			//签名验证
			signValidate.validate(orderInfo);
		}

		//手机号码验证
		mobValidate.validate(orderInfo);
		//并发访问控制
		vistVali(orderInfo);
	}
	
	/**
	 * 拼接签名信息 cpid+spid+userid+type+channel+timestamp
	 * @param orderInfo
	 * @return
	 */
	private String getSign(OrderInfo orderInfo) {
		if (orderInfo == null) {
			return "";
		}
		StringBuilder strb = new StringBuilder();
		if(orderInfo.getOrderid() != null && !"".equals(orderInfo.getOrderid())){
			strb.append(orderInfo.getOrderid());
		}
		//channel+userid+type+opertime+timestamp

		strb.append(orderInfo.getChannel());
		strb.append(orderInfo.getUserid());
		strb.append(orderInfo.getType());
		strb.append(orderInfo.getOpertime());
		strb.append(orderInfo.getTimestamp());
		return strb.toString();
	}
	
	/**
	 * 业务处理
	 * @param orderInfo
	 */
	public void busiOper(OrderInfo orderInfo)throws Exception{
		String errorcode = "0";
		String errorinfo = "";
		try {
			orderInfo.setOrderstatus("2");
			if("200000000033".equals(orderInfo.getChannel())){//深报免流
				orderInfo.setEffecttime(orderInfo.getOpertime());
				if("0".equals(orderInfo.getType())){
					orderInfo.setStatus("0");
					orderInfo.setOrderchannel(orderInfo.getChannel());
					orderInfo.setOrdertime(orderInfo.getOpertime());	//设置订购时间				
				}else{
					orderInfo.setStatus("1");
					orderInfo.setCancelchannel(orderInfo.getChannel());
					orderInfo.setCanceltime(orderInfo.getOpertime());   //设置退订时间		
					orderInfo.setEndtime(commConfDao.getEndDayOfOpertime(orderInfo.getOpertime()));
				}
			}else{
				commonService.setOperTime(orderInfo);
			}

			commonService.setAreaInfo(orderInfo);
			HashMap<String, Object> remap = commonService.getOrderStatus(orderInfo.getUserid(),orderInfo.getSpid());
			log.info("remap:"+remap);
			String relid = (String)remap.get("RELID"); //订购关系表ID
			if(relid == null || "".equals(relid)){
				relid = commConfDao.generateId();
			}
			orderInfo.setId(relid);
			
			if("200000000033".equals(orderInfo.getChannel())){//深报免流，订购时间和退订时间是传值过来的
				orderInfo.setChannel(""); //设置订购关系表渠道字段为空
				if("0".equals(orderInfo.getType())){ //订购
					if("0".equals(remap.get("ORDERSTATUS"))){//当前是订购状态
						throw new BussinessException("9080", "已订购该产品，请勿重复订购");
					}else if(remap.get("cancelTime") != null && (remap.get("cancelTime")+"").length() == 14
							&& Long.parseLong(remap.get("cancelTime").toString()) > Long.parseLong(orderInfo.getOrdertime())){ //已退订，但退订时间大于此次订购时间
						throw new BussinessException("9096", "订购时间小于本地退订时间，不处理");
					}else{//生成订购关系
						commConfDao.addOrderRal(orderInfo);
					}
				}else{//退订
					if("1".equals(remap.get("ORDERSTATUS"))){ //已退订
						throw new BussinessException("9017", "已退订该产品");
					}else if("0".equals(remap.get("ORDERSTATUS")) 
							&& remap.get("orderTime") != null 
							&& (remap.get("orderTime")+"").length() == 14
							&& Long.parseLong(orderInfo.getCanceltime()) < Long.parseLong(remap.get("orderTime").toString()) ){ //已订购，但此次退订时间小于订购时间
						throw new BussinessException("9025", "退订时间小于本地订购时间，不处理");
					}else if("0".equals(remap.get("ORDERSTATUS"))){
						commConfDao.addCancelRal(orderInfo);
					}else{
						throw new BussinessException("9118", "未订购或者已失效");
					}
				}
			}else{//公共操作，退订时间和订购时间取的是当前时间
				orderInfo.setChannel(""); //设置订购关系表渠道字段为空
				if("0".equals(orderInfo.getType())){ //订购
					if("0".equals(remap.get("ORDERSTATUS"))){//当前是订购状态
						throw new BussinessException("9080", "已订购该产品，请勿重复订购");
					}else{//生成订购关系
						commConfDao.addOrderRal(orderInfo);
					}
				}else{//退订
					if("1".equals(remap.get("ORDERSTATUS"))){ //已退订
						throw new BussinessException("9017", "已退订该产品");
					}else if("0".equals(remap.get("ORDERSTATUS"))){
						commConfDao.addCancelRal(orderInfo);
					}else{
						throw new BussinessException("9118", "未订购或者已失效");
					}
				}
			}

		} catch (Exception e) {
			if(e instanceof BussinessException) {
				errorcode = ((BussinessException) e).getCode();
				errorinfo = ((BussinessException) e).getMessage();
			}else {
				e.printStackTrace();
				log.error("出现异常，"+e.getMessage(),e);
				errorcode = "8000";
				errorinfo = "出现异常，"+e.getMessage();
			}
			throw e;
		} finally{
			//记录订购日志
		    commonService.saveLog(orderInfo, errorcode, errorinfo);
		    if("0".equals(errorcode) && !StringUtils.isEmpty(orderInfo.getOrderid())){
			    //添加订单ID与订购关系的关联记录
			    commonService.addRelidRec(orderInfo);
		    }
		}
	}
	
	/**
	 * 验证访问限制，1分钟内同一业务只能办理一次
	 * @param orderInfo
	 * @throws Exception
	 */
	private void vistVali(OrderInfo orderInfo) throws Exception {
		String [] params = new String [3];
		params[0] = orderInfo.getChannel();
		params[1] = orderInfo.getUserid();
		params[2] = orderInfo.getSpid();
		if(commonService.vistVali2(params, "syncorder")){
			throw new BussinessException("8001", "指定时间内重复请求");
		}
	}
}
