package com.chinacreator.process.service;

import com.chinacreator.common.exception.BusinessException;
import com.chinacreator.process.bean.*;
import com.chinacreator.process.dao.*;
import com.chinacreator.process.util.*;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
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 java.net.URLEncoder;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

@Component
public class VacOrderService {

	private static final String CANCELURL = "http://10.199.99.147:8092/videoif/cancelOrder.do?";

	private Logger logger = Logger.getLogger("vacorder");

	private Logger log = Logger.getLogger(VacOrderService.class);

	@Autowired
	private NetOrderDao netOrderDao;

	@Autowired
	private PreOrderDao preOrderDao;

	@Autowired
	private ActivityConfigDao activityConfigDao;

	@Autowired
	private VacActiveDao vacActiveDao;

	@Autowired
	private WhiteDao whiteDao;

	@Autowired
	private VacControlDao vacControlDao;

	@Autowired
	private CctvOrderService cctvOrderService;

	@Autowired
	private VacSyncOrderDao vacSyncOrderDao;

	@Autowired
	private DictionaryDao dictionaryDao;

	public int handlecctv(VacOrderBean vacOrderBean) {
		int result = 0;
		String resultcode = "0";
		String errorinfo = "";
		try {
			if (vacOrderBean.getOrderstatus().equals("0")) {
				NetOrderBean netOrderBean = getNetOrderInfo(vacOrderBean, "0");
				order(netOrderBean, vacOrderBean.getOrdertype());
			} else {
				NetOrderBean netOrderBean = getNetOrderInfo(vacOrderBean, "1");
				cancel(netOrderBean);
			}
			OrderBean orderBean = new OrderBean();
			orderBean.setUserid(vacOrderBean.getUserid());
			orderBean.setCpid(vacOrderBean.getCpid());
			orderBean.setSpid(vacOrderBean.getSpid());
			orderBean.setProvince(vacOrderBean.getProvince());
			orderBean.setArea(vacOrderBean.getArea());
			cctvOrderService.handle(orderBean);
		} catch (Exception e) {
			log.error(vacOrderBean.getUserid(), e);
			resultcode = "8000";
			errorinfo = "系统忙！";
			if (e instanceof BusinessException) {
				resultcode = ((BusinessException) e).getCode();
				errorinfo = ((BusinessException) e).getMessage();
			}
			result = 1;
		} finally {
			vacOrderBean.setResultcode(resultcode);
			vacOrderBean.setErrorinfo(errorinfo);
			logger.info(JsonUtil.objectToJson(vacOrderBean));
		}
		return result;
	}

	public int handle(VacOrderBean vacOrderBean) {
		int result = 0;
		String resultcode = "0";
		String errorinfo = "";
		if (vacOrderBean.getCpid().equals("cctv")) {
			handlecctv(vacOrderBean);
		} else {
			try {
				// if(vacOrderBean.getProvince().equals("重庆")){
				// throw new BusinessException("9069", "省份被限制");
				// }
				if (vacOrderBean.getOrdertype().equals("1") && vacOrderBean.getOrderstatus().equals("0")) {// 0元
					if (StringUtils.isNotEmpty(vacOrderBean.getProvince())) {
						if (vacSyncOrderDao.canOrder(vacOrderBean.getProvince(), "8000652500")) {
							throw new BusinessException("9069", vacOrderBean.getProvince() + "省份被限制");
						}
					}
				} else {
					if (StringUtils.isNotEmpty(vacOrderBean.getProvince())
							&& vacOrderBean.getOrderstatus().equals("0")) {
						if (vacSyncOrderDao.canOrder(vacOrderBean.getProvince(), "8000650900")) {
							throw new BusinessException("9069", vacOrderBean.getProvince() + "省份被限制");
						}
					}
				}
				if (vacOrderBean.getOrderstatus().equals("0")) {
					NetOrderBean orderBeanfor15 = this.netOrderDao.findOrder(vacOrderBean.getCpid(), "6",
							vacOrderBean.getUserid());
					NetOrderBean netOrderBean = getNetOrderInfo(vacOrderBean, "0");
					if (orderBeanfor15 == null || orderBeanfor15.getStatus().equals("2")) {
						order(netOrderBean, vacOrderBean.getOrdertype());
					} else if (orderBeanfor15.getStatus().equals("0")) {// 15元订购
						if (vacOrderBean.getOrdertype().equals("1")) {
							cancel15(netOrderBean);
							// String vacresult =
							// vacorder(netOrderBean.getUserid(),
							// netOrderBean.getCpid().equals("tencent") ? "0" :
							// "1");
							// if (!vacresult.equals("0")) {
							// throw new
							// BusinessException(vacresult,"腾讯20元产品，扣费20元失败",new
							// String[0]);
							// }
						}
						order(netOrderBean, vacOrderBean.getOrdertype());
						// preOrder(netOrderBean);
					} else if (orderBeanfor15.getStatus().equals("1")) {// 15元退订
						// if (vacOrderBean.getOrdertype().equals("1")) {
						// String vacresult = vacorder(netOrderBean.getUserid(),
						// netOrderBean.getCpid().equals("tencent") ? "0" :
						// "1");
						// if (!vacresult.equals("0")) {
						// throw new
						// BusinessException(vacresult,"腾讯20元产品，扣费20元失败",new
						// String[0]);
						// }
						// }
						order(netOrderBean, vacOrderBean.getOrdertype());
						// preOrder(netOrderBean);
					}
					activite(netOrderBean);
				} else {
					NetOrderBean netOrderBean = getNetOrderInfo(vacOrderBean, "1");
					cancel(netOrderBean);
					cancelActivite(netOrderBean);
				}
			} catch (Exception e) {
				log.error(vacOrderBean.getUserid(), e);
				resultcode = "8000";
				errorinfo = "系统忙！";
				if (e instanceof BusinessException) {
					resultcode = ((BusinessException) e).getCode();
					errorinfo = ((BusinessException) e).getMessage();
				}
				result = 1;
			} finally {
				vacOrderBean.setResultcode(resultcode);
				vacOrderBean.setErrorinfo(errorinfo);
				logger.info(JsonUtil.objectToJson(vacOrderBean));
			}
		}
		return result;
	}

	public String vacorder(String userid, String vactype) throws Exception {
		String result = "0";
		if ((vactype.equals("0") && vacControlDao.isOrder(userid, "tencent", "84"))
				|| (vactype.equals("1") && vacControlDao.isOrder(userid, "cctv", "10081"))) {
			throw new BusinessException("8002", "本月重复扣费");
		}
		try {
			if (vactype.equals("0")) {
				if (!whiteDao.isWhiteUser(userid, "tencent")) {
					result = VacUtil.vac(userid, "88226", "8000650900", "0");
					if (result.equals("0")) {
						vacControlDao.saveOrde(userid, "tencent", "84");
					}
				}
			} else {
				if (!whiteDao.isWhiteUser(userid, "cctv")) {
					result = VacUtil.vac(userid, "88226", "8000653500", "0");
					if (result.equals("0")) {
						vacControlDao.saveOrde(userid, "cctv", "10081");
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			result = "8000";
		} finally {
			saveNetLog20(userid, result, vactype);
		}
		return result;
	}

	public void activite(NetOrderBean netOrderBean) throws Exception {
		ActivityConfigBean activityConfigBean = activityConfigDao.findByCallerhead(netOrderBean.getCpid(),
				netOrderBean.getSpid(), "");
		if (activityConfigBean == null) {
			throw new BusinessException("9030", "非活动产品或者活动结束");
		}
		OrderBean oldbean = vacActiveDao.existUser(netOrderBean.getUserid(), netOrderBean.getCpid(),
				netOrderBean.getSpid());
		if (oldbean == null) {
			vacActiveDao.insertBeans(getBusBean(netOrderBean, null));
		} else if (oldbean.getOrderstatus().equals("0")) {
			throw new BusinessException("9031", "腾讯20元产品,活动表已订购");
		} else {
			if (NumberUtils.toLong(oldbean.getCanceltime()) > NumberUtils.toLong(netOrderBean.getOrdertimestr())) {
				throw new BusinessException("9032", "腾讯20元产品,活动表退订>订购");
			}
			netOrderBean.setId(oldbean.getId());
			vacActiveDao.update(getBusBean(netOrderBean, oldbean));
		}
	}

	public void cancelActivite(NetOrderBean netOrderBean) throws Exception {
		ActivityConfigBean activityConfigBean = activityConfigDao.findByCallerhead(netOrderBean.getCpid(),
				netOrderBean.getSpid(), "");
		if (activityConfigBean == null) {
			throw new BusinessException("9030", "非活动产品或者活动结束");
		}
		OrderBean oldbean = vacActiveDao.existUser(netOrderBean.getUserid(), netOrderBean.getCpid(),
				netOrderBean.getSpid());
		if (oldbean == null) {
			throw new BusinessException("9035", "腾讯20元产品,活动表无订购");
		} else if (oldbean.getOrderstatus().equals("1")) {
			throw new BusinessException("9031", "腾讯20元产品,活动表已退订");
		} else {
			if (NumberUtils.toLong(oldbean.getOrdertime()) > NumberUtils.toLong(netOrderBean.getCanceltimestr())) {
				throw new BusinessException("9032", "腾讯20元产品,活动表订购>退订");
			}
			netOrderBean.setId(oldbean.getId());
			vacActiveDao.cancelUpdate(getBusBean(netOrderBean, null));
		}
	}

	public OrderBean getBusBean(NetOrderBean netOrderBean, OrderBean oldbean) {
		OrderBean bean = new OrderBean();
		bean.setId(netOrderBean.getId());
		bean.setUserid(netOrderBean.getUserid());
		bean.setCpid(netOrderBean.getCpid());
		bean.setSpid(netOrderBean.getSpid());
		bean.setProvince(netOrderBean.getProvince());
		bean.setArea(netOrderBean.getArea());
		bean.setOrdertime(netOrderBean.getOrdertimestr());
		bean.setChannel(netOrderBean.getOrderchannel());
		bean.setCanceltime(netOrderBean.getCanceltimestr());
		if (oldbean != null) {
			bean.setVipstatus(oldbean.getVipstatus());
			bean.setViptime(oldbean.getViptime());
		}
		return bean;
	}

	public void cancel15(NetOrderBean netOrderBean) throws Exception {
		String url = CANCELURL;
		url += "userid=" + URLEncoder.encode(DesUtil.encode(netOrderBean.getUserid(), "tenc1234"), "utf-8");
		url += "&cpid=" + netOrderBean.getCpid();
		url += "&apptype=2";
		url += "&channel=vac";
		String result = "";
		try {
			result = URLUtil.get(url, 6000);
		} catch (Exception e) {
			activite(netOrderBean);
			throw new BusinessException("9910", "腾讯20元产品，调用15元退订接口失败", new String[0]);
		}
		Map<?, ?> map = JsonUtil.jsonToMap(result);
		if (!map.get("resultcode").equals("0")) {
			activite(netOrderBean);
			throw new BusinessException("9909", "腾讯20元产品，15元退订失败", new String[0]);
		}
	}

	public void preOrder(NetOrderBean netOrderBean) throws Exception {
		NetOrderBean preOrderBean = preOrderDao.existUser(netOrderBean.getUserid(), netOrderBean.getCpid(),
				netOrderBean.getSpid());
		if (preOrderBean != null && preOrderBean.getStatus().equals("0") && netOrderBean.getStatus().equals("0")) {
			throw new BusinessException("9905", "腾讯20元产品，已预订购", new String[0]);
		}
		if (preOrderBean != null && preOrderBean.getStatus().equals("1") && netOrderBean.getStatus().equals("0")
				&& NumberUtils.toLong(netOrderBean.getOrdertimestr()) < NumberUtils
						.toLong(preOrderBean.getCanceltimestr())) {
			throw new BusinessException("9907", "腾讯20元产品，预订购晚于本地预退订", new String[0]);
		}
		preOrderDao.order(netOrderBean);
	}

	public void cancel(NetOrderBean netOrderBean) throws Exception {
		String errorcode = "0";
		String errorinfo = "";
		try {
			NetOrderBean oldOrderBean = this.netOrderDao.findOrder(netOrderBean.getCpid(), netOrderBean.getSpid(),
					netOrderBean.getUserid());
			if (oldOrderBean == null) {
				if (netOrderBean.equals("cctv")) {
					throw new BusinessException("9901", "CCTV12元0元产品，本地无订购", new String[0]);
				} else {
					throw new BusinessException("9901", "腾讯20元0元产品，本地无订购", new String[0]);
				}
			}
			if (!oldOrderBean.getStatus().equals("0")) {
				if (netOrderBean.equals("cctv")) {
					throw new BusinessException("9902", "CCTV12元0元产品，本地已退订", new String[0]);
				} else {
					throw new BusinessException("9902", "腾讯20元0元产品，本地已退订", new String[0]);
				}
			}
			if (NumberUtils.toLong(oldOrderBean.getOrdertimestr()) >= NumberUtils
					.toLong(netOrderBean.getCanceltimestr())) {
				if (netOrderBean.equals("cctv")) {
					throw new BusinessException("9902", "CCTV12元0元产品，vac退订时间早于本地订购时间", new String[0]);
				} else {
					throw new BusinessException("9902", "腾讯20元0元产品，vac退订时间早于本地订购时间", new String[0]);
				}
			}
			netOrderDao.cancelOrder(netOrderBean);
			inserSmstMq(netOrderBean, "1");
		} catch (Exception e) {
			errorcode = "8000";
			errorinfo = "系统忙";
			if (e instanceof BusinessException) {
				errorcode = ((BusinessException) e).getCode();
				errorinfo = ((BusinessException) e).getMessage();
			}
			throw e;
		} finally {
			try {
				saveNetLog(netOrderBean, errorcode, errorinfo, "1");
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public void order(NetOrderBean netOrderBean, String ordertype) throws Exception {
		String errorcode = "0";
		String errorinfo = "";
		try {
			if (netOrderBean.getCpid().equals("cctv") && ordertype.equals("1")) {
				throw new BusinessException("9904", "0元订购不处理", new String[0]);
			}
			boolean vacOrder = true;
			NetOrderBean oldOrderBean = this.netOrderDao.findOrder(netOrderBean.getCpid(), netOrderBean.getSpid(),
					netOrderBean.getUserid());
			if (oldOrderBean != null) {// 本地无订购关系
				if (oldOrderBean.getStatus().equals("0") && netOrderBean.getStatus().equals("0")) {
					throw new BusinessException("9901", "vac重复订购", new String[0]);
				} else if ((oldOrderBean.getStatus().equals("1") || oldOrderBean.getStatus().equals("2"))
						&& netOrderBean.getStatus().equals("0")) {
					if (NumberUtils.toLong(oldOrderBean.getCanceltimestr()) >= NumberUtils
							.toLong(netOrderBean.getOrdertimestr())) {
						throw new BusinessException("9902", "vac订购时间晚于本地退订时间", new String[0]);
					}
					if (oldOrderBean.getStatus().equals("1")) {
						if (oldOrderBean.getCancelchannel() != null) {
							if (!oldOrderBean.getCancelchannel().equals("lvac")
									&& !oldOrderBean.getCancelchannel().equals("ecb")) {
								vacOrder = false;
							}
						} else {
							vacOrder = false;
						}
					}
				}
			}
			if (ordertype.equals("1")) {
				if (netOrderBean.getCpid().equals("tencent") && netOrderBean.getSpid().equals("84")) {
					EcbUtils.queryEcb(netOrderBean.getCpid(), netOrderBean.getSpid(), netOrderBean.getProvince(),
							netOrderBean.getUserid());
				}
				if (vacOrder) {
					String result = vacorder(netOrderBean.getUserid(),
							netOrderBean.getCpid().equals("tencent") ? "0" : "1");
					if (!result.equals("0")) {
						throw new BusinessException(result,
								netOrderBean.getCpid().equals("tencent") ? "腾讯20元产品，扣费20元失败" : "CCTV12元产品，扣费12元失败",
								new String[0]);
					}
				}
				netOrderDao.order(netOrderBean);
			} else {
				if (netOrderBean.getCpid().equals("tencent") && netOrderBean.getSpid().equals("84")) {
					try {
						EcbUtils.queryEcb(netOrderBean.getCpid(), netOrderBean.getSpid(), netOrderBean.getProvince(),
								netOrderBean.getUserid());
					} catch (Exception e) {
						netOrderDao.order(netOrderBean);
						throw e;
					}
				}
				netOrderDao.order(netOrderBean);
			}
			if (ordertype.equals("0")) {
				inserOrderMq(netOrderBean);
			}
			inserSmstMq(netOrderBean, "0");
		} catch (Exception e) {
			errorcode = "8000";
			errorinfo = "系统忙";
			if (e instanceof BusinessException) {
				errorcode = ((BusinessException) e).getCode();
				errorinfo = ((BusinessException) e).getMessage();
			}
			throw e;
		} finally {
			try {
				if (ordertype.equals("1") && errorcode.equals("0")) {
					errorinfo = "受理成功（预受理0元）";
				} else if (ordertype.equals("1")) {
					errorinfo = "（预受理0元）";
				}
				saveNetLog(netOrderBean, errorcode, errorinfo, "0");
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public void saveNetLog20(String userid, String result, String vactype) throws SQLException {
		OrderLog orderLog = new OrderLog();
		orderLog.setApptype("");
		orderLog.setOrderstatus(3);
		orderLog.setStatus(0);
		if (vactype.equals("0")) {
			orderLog.setCpid("tencent");
			orderLog.setSpid("84");
			orderLog.setErrorinfo(result.equals("0") ? "腾讯20元扣费成功" : "腾讯20元扣费失败");
		} else {
			orderLog.setCpid("cctv");
			orderLog.setSpid("10081");
			orderLog.setErrorinfo(result.equals("0") ? "CCTV12元扣费成功" : "CCTV12元扣费失败");
		}
		orderLog.setIsexperience(0);
		orderLog.setOrdertype("vac");
		orderLog.setProvince("");
		orderLog.setArea("");
		orderLog.setUserid(userid);
		orderLog.setErrorcode(result);
		orderLog.setChannel("vac");
		this.netOrderDao.addOrderLog(orderLog);
	}

	public void saveNetLog(NetOrderBean orderInfo, String errorcode, String errorinfo, String ordertype)
			throws SQLException {
		OrderLog orderLog = new OrderLog();
		orderLog.setApptype(orderInfo.getApptype());
		orderLog.setOrderstatus(orderInfo.getOrderstatus());
		orderLog.setStatus(Integer.valueOf(orderInfo.getStatus()).intValue());
		orderLog.setCpid(orderInfo.getCpid());
		orderLog.setIsexperience(orderInfo.getIsexperience());
		orderLog.setOrdertype(orderInfo.getOrdertype());
		orderLog.setProvince(orderInfo.getProvince());
		orderLog.setArea(orderInfo.getArea());
		orderLog.setSpid(orderInfo.getSpid());
		orderLog.setUserid(orderInfo.getUserid());
		orderLog.setErrorcode(errorcode);
		orderLog.setErrorinfo(errorinfo);
		if (ordertype.equals("0")) {
			orderLog.setChannel(orderInfo.getOrderchannel());
		} else {
			orderLog.setChannel(orderInfo.getCancelchannel());
		}
		this.netOrderDao.addOrderLog(orderLog);
	}

	public NetOrderBean getNetOrderInfo(VacOrderBean vacOrderBean, String type) throws Exception {
		NetOrderBean netOrderBean = new NetOrderBean();
		netOrderBean.setUserid(vacOrderBean.getUserid());
		netOrderBean.setCpid(vacOrderBean.getCpid());
		netOrderBean.setSpid(vacOrderBean.getSpid());
		netOrderBean.setProvince(vacOrderBean.getProvince());
		netOrderBean.setArea(vacOrderBean.getArea());
		netOrderBean.setStaffid(vacOrderBean.getStaffid());
		netOrderBean.setDepartid(vacOrderBean.getDepartid());
		if (type.equals("0")) {
			netOrderBean.setStatus("0");
			netOrderBean
					.setOrdertime(DateUtils.parseDate(vacOrderBean.getOrdertime(), new String[] { "yyyyMMddHHmmss" }));
			netOrderBean.setOrderchannel(vacOrderBean.getChannel());
			netOrderBean.setOrderstatus(3);
		} else {
			netOrderBean.setStatus("1");
			netOrderBean.setCanceltime(
					DateUtils.parseDate(vacOrderBean.getCanceltime(), new String[] { "yyyyMMddHHmmss" }));
			netOrderBean.setCancelchannel(vacOrderBean.getChannel());
			netOrderBean.setOrderstatus(5);
		}
		return netOrderBean;
	}

	public void inserOrderMq(NetOrderBean netOrderBean) {
		try {
			if (netOrderBean.getCpid().equals("cctv")) {
				Map<String, String> map = new HashMap<String, String>();
				map.put("userid", netOrderBean.getUserid());
				map.put("cpid", netOrderBean.getCpid());
				map.put("spid", netOrderBean.getSpid());
				map.put("status", "0");
				map.put("ordertime", netOrderBean.getOrdertimestr());
				map.put("channel", netOrderBean.getOrderchannel());
				map.put("type", "vacorder");
				//URLUtil.post("http://10.199.99.144:8090/mq-service/recive.do", JsonUtil.objectToJson(map));
				URLUtil.post(dictionaryDao.getValue("mqReciveUrl"), JsonUtil.objectToJson(map));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void inserSmstMq(NetOrderBean netOrderBean, String type) {
		try {
			if (netOrderBean.getCpid().equals("tencent")) {
				Map<String, String> map = new HashMap<String, String>();
				map.put("userid", netOrderBean.getUserid());
				map.put("cpid", netOrderBean.getCpid());
				map.put("spid", netOrderBean.getSpid());
				map.put("result", "0");
				map.put("channel", "");
				if (type.equals("0")) {
					map.put("style", "7");
				} else {
					map.put("style", "8");
				}
				map.put("times", "");
				map.put("orderType", "");
				map.put("type", "cssms");
				//URLUtil.post("http://10.199.99.144:8090/mq-service/recive.do", JsonUtil.objectToJson(map));
				URLUtil.post(dictionaryDao.getValue("mqReciveUrl"), JsonUtil.objectToJson(map));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}