package com.chinacreator.video.service;

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

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.chinacreator.video.bean.ChannelBean;
import com.chinacreator.video.bean.FtpOrderBean;
import com.chinacreator.video.bean.TrafficOrderInfo;
import com.chinacreator.video.exception.BussinessException;
import com.chinacreator.video.mapper.ChannelDao;
import com.chinacreator.video.mapper.TrafficOrderDao;
import com.chinacreator.video.util.DesUtil;
import com.chinacreator.video.util.MD5;
import com.chinacreator.video.util.TrafficOrderProperties;
import com.chinacreator.video.validate.ChannelValidate;
import com.chinacreator.video.validate.IpValidate;
import com.chinacreator.video.validate.TimetampValidate;

/**
 * 手网厅订购关系实时同步-服务类
 * @author zhouxu
 * @date 20190719
 */
@Component
public class TrafficOrderService {
	
	private static final  Logger logger = LoggerFactory.getLogger(TrafficOrderService.class);
	
	private static final  Logger log = LoggerFactory.getLogger("trafficOrder");
	
	@Autowired
	private TimetampValidate timetampValidate;
	
	@Autowired
	private ChannelValidate channelValidate;
	
	@Autowired
	private IpValidate ipValidate;
	
	@Autowired
	private ChannelDao channelDao;
	
	@Autowired
	private TrafficOrderProperties tOProperties;
	
	@Autowired
	private TrafficOrderDao trafficOrderDao;
	
	/**
	 * 业务验证
	 * @param orderInfo
	 * @throws Exception
	 */
	public void checkBusi(TrafficOrderInfo orderInfo) throws Exception {
		this.paramVali(orderInfo); 								//验证参数
		timetampValidate.validate(orderInfo.getTimestamp()); 	//验证时间戳
		channelValidate.validate(orderInfo.getChannel());		//验证渠道
		this.valiMob(orderInfo);								//验证手机号码
		this.valiSign(orderInfo);								//验证签名
		ipValidate.volidate(orderInfo);							//验证ip
	}
	
	/**
	 * 真正业务处理
	 * @param orderInfo
	 * @return
	 */
	public String busiOper(TrafficOrderInfo orderInfo) throws Exception {
		String result = "-1";
		FtpOrderBean foBean = this.parseData(orderInfo);
		String id = trafficOrderDao.getID();
		foBean.setId(id);
		trafficOrderDao.addFtpOrder(foBean); //添加数据到表TD_CHANNEL_FTP_ORDER
		trafficOrderDao.addFtpDq(foBean);	//添加数据到表TD_CHANNEL_FTP_DQ
		result = "0";
		return result;
	}
	
	/**
	 * 获取productid
	 * @param orderInfo
	 * @throws Exception
	 */
	private String getProductId(TrafficOrderInfo orderInfo){
		String productid = "";
		try {
			//productid = tOProperties.getEnv().getProperty(orderInfo.getProductid());
			//20220211改为查数据库表获取计费点
			List<HashMap> confList = trafficOrderDao.getSjyytProductidConf();
			if(confList != null && confList.size()>0){
				for(HashMap hm : confList){
					if(orderInfo.getProductid().equals(hm.get("SRCPRODUCTID"))
							&& "0".equals(hm.get("STATUS"))){
						productid = hm.get("MAPPRODUCTID").toString();
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(productid == null){
			productid = "";
		}
		log.info("productid=>"+productid);
		return productid;
	}
	
	/**
	 * 验证手机号码
	 * @param orderInfo
	 * @throws Exception
	 */
	private void valiMob(TrafficOrderInfo orderInfo)throws Exception{
		String userid = orderInfo.getSerialnumber();
		if(StringUtils.isEmpty(userid)) {
			throw new BussinessException("10007", "手机号不能为空");
		}
		ChannelBean channelBean = channelDao.queryChannel(orderInfo.getChannel());
		try {
			userid = DesUtil.decode(userid, channelBean.getPassword());
			if(isValid(userid) && userid.length() == 11){
				orderInfo.setEnuserid(orderInfo.getSerialnumber()); //保存加密的手机顺驰，用于参数返回
				orderInfo.setUserid(userid);
			}else{
				throw new BussinessException("10009", "手机号错误");
			}	
		} catch (Exception e) {
			if(e instanceof BussinessException) {
				throw e;
			}else {
				throw new BussinessException("10008", "手机号加密错误");
			}
		}
	}
	
	private boolean isValid(String usermob){
        if (usermob == null) {
            return false;
        }
        usermob = usermob.replaceAll("[\\s-]", "");       
        return usermob.matches(".*(1\\d{10}).*");	    
	}
	
	/**
	 * 验证参数
	 * @param orderInfo
	 * @throws BussinessException
	 */
	private void paramVali(TrafficOrderInfo orderInfo)throws Exception{
		if(StringUtils.isEmpty(orderInfo.getTimestamp())
				|| StringUtils.isEmpty(orderInfo.getChannel())
				|| StringUtils.isEmpty(orderInfo.getDepart())
				|| StringUtils.isEmpty(orderInfo.getOrderid())
				|| StringUtils.isEmpty(orderInfo.getOrderstatus())
				|| StringUtils.isEmpty(orderInfo.getOrdertime())
				|| StringUtils.isEmpty(orderInfo.getSignature())
				|| StringUtils.isEmpty(orderInfo.getSerialnumber())
				|| StringUtils.isEmpty(orderInfo.getNettypecode())
				|| StringUtils.isEmpty(orderInfo.getProvincecode())) {
			throw new BussinessException("80015", "参数不合法");
		}
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
			sdf.parse(orderInfo.getOrdertime());
		} catch (Exception e) {
			throw new BussinessException("80015", "参数不合法，ordertime");
		}
		if(!"0".equals(orderInfo.getOrderstatus()) && !"1".equals(orderInfo.getOrderstatus())){
			throw new BussinessException("80015", "参数不合法，orderstatus");
		}
		if(!"01".equals(orderInfo.getDepart()) && !"02".equals(orderInfo.getDepart())
				&& !"03".equals(orderInfo.getDepart()) && !"04".equals(orderInfo.getDepart())){
			throw new BussinessException("80015", "参数不合法，depart");
		}
	}
	
	/**
	 * 签名验证
	 * @param orderInfo
	 * @throws BussinessException
	 */
	private void valiSign(TrafficOrderInfo orderInfo) throws BussinessException{
		try {
			String lcalsign = getSign(orderInfo);
			lcalsign += channelDao.queryChannel(orderInfo.getChannel()).getPassword();
			//Md5(接入渠道+手机号码伪码+订单号+订单状态+产品编码+时间戳+密码)
			lcalsign = MD5.MD5Encode(lcalsign);
			if(!lcalsign.equals(orderInfo.getSignature())) {
				throw new BussinessException("10006", "签名校验失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new BussinessException("10006", "签名校验失败");
		}
	}
	
	/**
	 * 拼接签名信息 cpid+spid+userid+channel+timestamp
	 * @param orderInfo
	 * @return
	 */
	private String getSign(TrafficOrderInfo orderInfo) {
		if (orderInfo == null) {
			return "";
		}
		//signature = MD5.MD5Encode(channel + serialnumber + orderid + orderstatus + productid +timestamp + pwd);
		StringBuilder strb = new StringBuilder();
		strb.append(orderInfo.getChannel());
		strb.append(orderInfo.getSerialnumber());
		strb.append(orderInfo.getOrderid());
		strb.append(orderInfo.getOrderstatus());
		strb.append(orderInfo.getProductid());
		strb.append(orderInfo.getTimestamp());
		return strb.toString();
	}
	
	/**
	 * 解析输入参数
	 * @param orderInfo
	 * @return
	 */
	private FtpOrderBean parseData(TrafficOrderInfo orderInfo)throws Exception{
		FtpOrderBean obj = new FtpOrderBean();
		SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
		String userId = orderInfo.getUserid(); 	//手机号
		String channel = orderInfo.getDepart(); 		//渠道
		obj.setUserid("null".equals(userId)?"":userId);
		String orderDate = orderInfo.getOrdertime(); 	//订购时间
		obj.setInserttime(sdf.format(new Date()));
		obj.setStatus("1");
		obj.setType("");
		if("01".equals(channel)){
			obj.setType("6");
		}else if("02".equals(channel)){
			obj.setType("7");
		}else if("03".equals(channel)){
			obj.setType("8");
		}else if("04".equals(channel)){
			obj.setType("9");
		}
		obj.setFilename("trafficOrder");
		obj.setSynctime("");//
		obj.setChannel("");
		if("01".equals(channel)){
			obj.setChannel("9");
		}else if("02".equals(channel)){
			obj.setChannel("10");
		}else if("03".equals(channel)){
			obj.setChannel("11");
		}else if("04".equals(channel)){
			obj.setChannel("12");
		}
		obj.setSquenceid("");
		String provinceCode = orderInfo.getProvincecode(); //省份编码
		obj.setProvinceCode("null".equals(provinceCode)?"":provinceCode);
		String typeCode = orderInfo.getNettypecode(); 		//网别
		obj.setNettypeCode("null".equals(typeCode)?"":typeCode);
		String orderId = orderInfo.getOrderid(); //自助服务订单号
		obj.setOrderId("null".equals(orderId)?"":orderId);
		String orderStatus = orderInfo.getOrderstatus(); //订单状态
//		obj.setIstimeout("null".equals(orderStatus)?"":orderStatus);
		obj.setUpdatetype(0);
		if("0".equals(orderStatus)){
			obj.setUpdatetype(1);
		}else if("1".equals(orderStatus)){
			obj.setUpdatetype(2);
		}
		String productId = orderInfo.getProductid(); //产品编码
		obj.setOrdertime("");
		obj.setCanceltime("");
		if("0".equals(orderStatus)){
			obj.setOrdertime(orderDate);
		}else if("1".equals(orderStatus)){
			obj.setCanceltime(orderDate);
		}
		//设置原始产品ID，用于查询比对
		obj.setElementId(orderInfo.getProductid());
		productId = getProductId(orderInfo);
		obj.setProductId(productId);
		return obj;
	}
}
