package com.chinacreator.video.restful.service;

import java.text.SimpleDateFormat;
import java.util.TimeZone;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chinacreator.video.exception.BussinessException;
import com.chinacreator.video.bean.OrderInfo;
import com.chinacreator.video.mapper.CapReverseDao;
import com.chinacreator.video.restful.bean.CapRevBean;
import com.chinacreator.video.validate.IpValidate;

/**
 * CAP平台VAC反向通知数据入库
 * @author zhouxu
 * @date 20190829
 */
@Component
public class CapReverseService {
	
	private static final  Logger logger = LoggerFactory.getLogger(CapReverseService.class);
	
	private static final  Logger log = LoggerFactory.getLogger("capreverse");
	
	@Autowired
	private IpValidate ipValidate;
	
	@Autowired
	CapReverseDao capReverseDao;
	
	/**
	 * 业务验证
	 * @param crBean
	 * @param inputParams
	 * @throws Exception
	 */
	public void busiVali(CapRevBean crBean, String inputParams)throws Exception{
		crBean.setTxid(this.getRequestId());
		this.paramVali(crBean,inputParams); 
	}
	
	/**
	 * 业务验证
	 * @param inparams
	 * @throws Exception
	 */
	public String operBusi(CapRevBean crBean) throws Exception {
		OrderInfo orderInfo = new OrderInfo();
		orderInfo.setChannel("CAP");
		orderInfo.setCpid("reverse");
		orderInfo.setInvokeface("reverseOrdering");
		//验证IP
		ipValidate.volidate(orderInfo);
		String result = "-1";
		crBean.setId(capReverseDao.getId());
		capReverseDao.addCapInfo(crBean);
		result = "0";
		return result;
	}
	
	/**
	 * 获取请求ID
	 * @return
	 */
	public String getRequestId(){
		String requestId = this.getSystemTime()+this.getRandNum();
		return requestId;
	}
	
	/**
	 * 获取系统时间，精确到毫秒
	 * @return
	 */
	private String getSystemTime(){
		SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		dateformat.setTimeZone(TimeZone.getDefault());
		String systemTime = String.valueOf(dateformat.format(System.currentTimeMillis()));
		return systemTime;
	}
	
	/**
	 * 获取6位随机数
	 * @return
	 */
	private String getRandNum(){
		int romNum = (int)((Math.random()*9+1)*100000);
		return romNum+"";
	}

	
	/**
	 * 验证手机号码
	 * @param orderInfo
	 * @throws Exception
	 */
	private void valiMob(CapRevBean crBean)throws Exception{
		String userid = crBean.getMdn();
		if(StringUtils.isEmpty(userid) //为空
				|| !isValid(userid)  //非全数字
				|| userid.length() != 11) { //不是11位
			throw new BussinessException("10009", "手机号错误");
		}	
	}
	
	private boolean isValid(String usermob){
        if (usermob == null) {
            return false;
        }
        usermob = usermob.replaceAll("[\\s-]", "");       
        return usermob.matches(".*(1\\d{10}).*");	    
	}
	
	/**
	 * 验证参数
	 * @param inputParams 输出参数
	 * @throws BussinessException
	 */
	private void paramVali(CapRevBean crBean, String inputParams)throws Exception{
		try {
			//JSONObject jsonObj = JSON.parseObject(inputParams);
			//JSONObject ubbObj =  (JSONObject)jsonObj.get("UNI_BSS_BODY");
			//JSONObject rorObj =  (JSONObject)ubbObj.get("REVERSE_ORDERING_REQ");
			JSONObject rorObj =  JSON.parseObject(inputParams);
			JSONObject siObj =  (JSONObject)rorObj.get("SP_INFO");
			
			crBean.setAcceptTime(rorObj.getString("ACCEPT_TIME"));
			crBean.setInModeCode(rorObj.getString("IN_MODE_CODE"));
			crBean.setMdn(rorObj.getString("MDN"));
			crBean.setOrderId(rorObj.getString("ORDER_ID"));
			crBean.setSequenceId(rorObj.getString("SEQUENCE_ID"));
			crBean.setSourcedeviceId(rorObj.getString("SOURCEDEVICE_ID"));
			crBean.setUpdateType(rorObj.getString("UPDATE_TYPE"));
			
			crBean.setSpId(siObj.getString("SP_ID"));
			crBean.setSpProductId(siObj.getString("SP_PRODUCT_ID"));
			crBean.setStartDate(siObj.getString("START_DATE"));
			crBean.setEndDate(siObj.getString("END_DATE"));
			crBean.setDepartId(rorObj.getString("DEPART_ID") == null?"":rorObj.getString("DEPART_ID"));
			crBean.setStaffId(rorObj.getString("STAFF_ID") == null?"":rorObj.getString("STAFF_ID"));

			valiMob(crBean);
		} catch (Exception e1) {
			e1.printStackTrace();
			log.error("参数不合法，解析异常，"+e1);
			throw new BussinessException("80015", "参数不合法，解析异常，"+e1.getMessage());			
		}
		if(crBean.getSpProductId() == null || crBean.getSpId() == null){
			throw new BussinessException("80015", "参数为空");	
		}
	}
	
	/**
	 * 获取流水号
	 * @param inputParams
	 * @return
	 */
	public String getSequencdId(String inputParams){
		String sequencdId = ""; //流水号，与请求流水号一致
		JSONObject jsonObj = JSON.parseObject(inputParams);
		JSONObject ubbObj =  (JSONObject)jsonObj.get("UNI_BSS_BODY");
		JSONObject rorObj =  (JSONObject)ubbObj.get("REVERSE_ORDERING_REQ");
		sequencdId = rorObj.getString("SEQUENCE_ID");
		return sequencdId;
	}
}
