package com.iamberry.wechat.handles.pay;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.net.URLDecoder;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.iamberry.wechat.service.ImberryConfig;
import org.apache.commons.lang3.StringUtils;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.xml.sax.InputSource;

import com.iamberry.app.tool.log.RatFWLogger;
import com.iamberry.wechat.core.entity.AdminUtils;
import com.iamberry.wechat.core.entity.admin.ShopSystemRule;
import com.iamberry.wechat.core.entity.coupon.CouponItem;
import com.iamberry.wechat.core.entity.giftCard.AgentInfo;
import com.iamberry.wechat.core.entity.giftCard.AgentMachine;
import com.iamberry.wechat.core.entity.giftCard.AgentPayLogs;
import com.iamberry.wechat.core.entity.lease.LeaseOrder;
import com.iamberry.wechat.core.entity.machine.Machine;
import com.iamberry.wechat.core.entity.member.CashLog;
import com.iamberry.wechat.core.entity.member.Member;
import com.iamberry.wechat.core.entity.mq.MQMessage;
import com.iamberry.wechat.core.entity.order.Order;
import com.iamberry.wechat.core.entity.order.ProbationOrder;
import com.iamberry.wechat.core.entity.order.ProbationOrderDto;
import com.iamberry.wechat.core.entity.probation.ProbationAwardRelu;
import com.iamberry.wechat.core.entity.qrcode.QrcodeResult;
import com.iamberry.wechat.core.entity.rent.RentApply;
import com.iamberry.wechat.core.entity.wx.WxPayResult;
import com.iamberry.wechat.face.admin.SystemService;
import com.iamberry.wechat.face.cart.CartService;
import com.iamberry.wechat.face.coupon.CouponItemService;
import com.iamberry.wechat.face.giftCard.AgentMachineService;
import com.iamberry.wechat.face.giftCard.AgentService;
import com.iamberry.wechat.face.giftCard.GiftCardService;
import com.iamberry.wechat.face.home.HomeService;
import com.iamberry.wechat.face.lease.LeaseOrderService;
import com.iamberry.wechat.face.member.CashLogService;
import com.iamberry.wechat.face.member.MemberService;
import com.iamberry.wechat.face.mq.EfastOrderService;
import com.iamberry.wechat.face.order.AdminProbationOrderService;
import com.iamberry.wechat.face.order.CodeService;
import com.iamberry.wechat.face.order.ProbationShopOrderService;
import com.iamberry.wechat.face.qrcode.TemporaryQrcodeService;
import com.iamberry.wechat.handles.mq.MQServiceProxy;
import com.iamberry.wechat.tools.DateTimeUtil;
import com.iamberry.wechat.tools.NameUtils;
import com.iamberry.wechat.tools.ResultInfo;
import com.iamberry.wechat.tools.StaticInfo;
import com.iamberry.wechat.tools.StrUtils;
import com.iamberry.wechat.utils.SendMessageUtil;

/**
 * @author 何秀刚
 * Class Description: 微信支付回调handler,所有的支付回调，都在本类完成
 * Create Date:2016年4月19日
 * Update Date:2016年4月19日
 */
@Controller
@RequestMapping("/callback")
public class ResponseWechatPayHandler {

	@Autowired
	private RatFWLogger ratFWLogger;
	
	private Object lock = new Object();
	
	@Autowired
	private CartService cartService;
	
	@Autowired
	private MemberService memberService;
	
	@Autowired
	private MQServiceProxy mQservice;
	
	@Autowired
	CashLogService cashLogService;
	@Autowired
	CouponItemService couponItemService;
	@Autowired
	private AdminProbationOrderService adminProbationOrderService;
	@Autowired
	private ProbationShopOrderService probationShopOrderService;
	@Autowired
	private SendMessageUtil sendMessageUtil;
	@Autowired
	private HomeService homeService;
	@Autowired
	private TemporaryQrcodeService temporaryQrcodeService;
	@Autowired
	private RatFWLogger inLongLogger;
	@Autowired
	private LeaseOrderService leaseOrderService;
	@Autowired
	private AdminUtils adminUtils;
	@Autowired
	private CodeService codeService;
	@Autowired
	private AgentService agentService;
	@Autowired
	private GiftCardService cardService;
	@Autowired
	private AgentMachineService agentMachineService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private EfastOrderService efastOrderService;

	/**
	 * 销售订单支付回调方法
	 */
	@RequestMapping("/orderPayBack")
	public synchronized void orderPayBack(HttpServletRequest request, 
			HttpServletResponse response) throws IOException {
		String inputLine;
		String notityXml = "";
		String resXml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
		try {
			//获取XML参数
			while ((inputLine = request.getReader().readLine()) != null) {
				notityXml += inputLine;
			}
			request.getReader().close();
			//解析XML格式的数据
			Map<String, String> m = parseXmlToList2(notityXml);
			WxPayResult wpr = new WxPayResult();
			wpr=setWxPayResultObj(wpr,m);
			//判断
			if("SUCCESS".equalsIgnoreCase(wpr.getResultCode())){
				//resXml:返回给微信服务器的数据
				resXml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
				String orderIdMD5 = StaticInfo.orderIdMD5.decrypt(wpr.getAttach());
//System.out.println("===========pay 117==============");
				
				if (orderIdMD5.equals(wpr.getOutTradeNo())) {
					Date nowDate = new Date();
					// 组装数据
					Order order = new Order();
					order.setSalesOrderid(orderIdMD5);
					order.setSalesStatus(2); // 已支付
					order.setSalesTransactionId(wpr.getTransactionId()); // 微信支付ID
					order.setSalesTransactionDate(new Date()); // 微信支付时间
					order.setSalesOpenid(wpr.getOpenid());
					
					// 修改订单状态
					int count = cartService.updateOrderStatus(order);

					//发送短信给运营部
					ShopSystemRule rule = cartService.getReluByRid(241);
					try {
						String text = MessageFormat.format(ImberryConfig.ORDER_UPDATE_STATUS_TEXT, "发货");
						codeService.informShipping(rule.getRuleDesc(),text);
					} catch (Exception e) {
						System.out.println("订单换货发送消息失败!");
					}
					
//System.out.println("===========pay 132 修改订单状态==============");
					//修改优惠券状态
					order=cartService.selectOrderInfoById(order);
					
//System.out.println("===========pay 136 修改订单状态=============="+order.getSalesOrderid());
					String couponId=order.getCouponId();
					
					if(couponId!=null && !couponId.equals("")){
						CouponItem couponItem=new CouponItem();
						couponItem.setCouponItemId(couponId);
						couponItem.setCouponUseStatus(2);
						couponItem.setCouponUseDate(new Date());
						couponItemService.updateCouponItemById(couponItem);
					}
					//更新账户余额
					int balancePayAmount=order.getBalancePayAmount();
					if(balancePayAmount>0){
						Member member=new Member();
						member.setUserOpenid(order.getSalesOpenid());
						member.setUserIncome(-balancePayAmount);
						memberService.updateUserIncomeByOpenId(member);
						
						//现金使用记录
						CashLog log=new CashLog();
						log.setCashLogsIntroduction("订单支出");
						log.setCashLogsNum(balancePayAmount);
						log.setCashLogsOpenid(member.getUserOpenid());
						log.setCashLogsType(2);
						log.setCashLogsResType(3);
						log.setCashLogsOrderid(order.getSalesOrderid());
						log.setCashLogsCreateDate(nowDate);
						count=cashLogService.addCashLog(log);
					}
					if (count < 1) {
						resXml = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[报文有误]]></return_msg></xml>";
					}
//System.out.println("===========pay 168 快速插入=============="+count);
					// 给订单的回调修改状态
					try {
						MQMessage message = new MQMessage();
						message.setServiceToMessage(orderIdMD5);
						message.setServiceOtherMessage(wpr.getTransactionId());
						message.setServiceIsSend(2);			// 没有推送的信息
						message.setServiceStatus(1); 			// 推送成功
						message.setServiceHandlerObjectName("cartServiceImpl");
						message.setServiceHandlerMethodName("supdateStateByOrderId");
						message.setServiceType(1);
						mQservice.insertMQMessage(message);
					} catch (Exception e) {
						// TODO: handle exception
					}
//System.out.println("===========pay 182  插入返利到mq=============="+count);
					//rebackServices.loadSingleOrderReward(order);
					
					//添加到返利表
					//rebackServices.loadSingleOrderReward(order);
					// 给百胜推送信息
					try {
						MQMessage message = new MQMessage();
						message.setServiceToMessage(orderIdMD5);
						message.setServiceOtherMessage("efast.trade.new.add");
						message.setServiceIsSend(2);			// 没有推送的信息
						message.setServiceStatus(1); 			// 推送成功
						message.setServiceType(1); 				// 添加订单信息
						message.setServiceHandlerObjectName("efastOrderServiceImpl");
						message.setServiceHandlerMethodName("addOrderInfoToEfast");
						mQservice.insertMQMessage(message);
					} catch (Exception e) {
//System.out.println("===========pay 201  插入返利到百胜失败==============");		
					}
//System.out.println("===========pay 201  插入返利到百胜完成==============");		
					try {	//修改用户购买记录为已购买
						memberService.updateIsBaughtByOpenid(wpr.getOpenid(), 2);
						//更新用户绑定状态
						Member member = memberService.getMemberByUserOpenId(order.getSalesOpenid());
						if (member.getUserIsFlag()!= null && member.getUserIsFlag() == 1) {
							member.setUserIsFlag(2);//终身绑定
							homeService.updateMemberIsFlagByOpenid(member);
						}
						QrcodeResult qr = temporaryQrcodeService.applyTempQrcode(order.getSalesOpenid());//为用户生成二维码
						inLongLogger.info("为用户-->" + order.getSalesOpenid() + ",生成二维码:" + qr.getQroceUrl());
					} catch (Exception e) {
						System.out.println("修改已购买状态和终身绑定失败!");
						e.printStackTrace();
					}
					
				} else {
					resXml = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[报文有误]]></return_msg></xml>";
					ratFWLogger.error(this, "订单:" + orderIdMD5 + "支付成功，但是没有通过校验!");
				}
			}else{
				resXml = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[报文为空]]></return_msg></xml>";
			}
			BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
			out.write(resXml.getBytes());
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 解析xml片段为Map
	 * @param xml
	 * @return
	 */
	@SuppressWarnings({"unchecked"})
	private Map<String, String> parseXmlToList2(String xml) {
		Map<String, String> retMap = new HashMap<String, String>();
		try {
			StringReader read = new StringReader(xml);
			// 创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
			InputSource source = new InputSource(read);
			// 创建一个新的SAXBuilder
			SAXBuilder sb = new SAXBuilder();
			// 通过输入源构造一个Document
			Document doc = (Document) sb.build(source);
			Element root = doc.getRootElement();// 指向根节点
			List<Element> es = root.getChildren();
			if (es != null && es.size() != 0) {
				for (Element element : es) {
					retMap.put(element.getName(), element.getValue());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return retMap;
	}
    
	//封装参数
	public WxPayResult setWxPayResultObj(WxPayResult wpr ,Map<String, String> m){
		//解析参数
		wpr.setAppid(m.get("appid").toString());
		wpr.setBankType(m.get("bank_type").toString());
		wpr.setCashFee(m.get("cash_fee").toString());
		wpr.setFeeType(m.get("fee_type").toString());
		wpr.setIsSubscribe(m.get("is_subscribe").toString());
		wpr.setMchId(m.get("mch_id").toString());
		wpr.setNonceStr(m.get("nonce_str").toString());
		wpr.setOpenid(m.get("openid").toString());
		wpr.setOutTradeNo(m.get("out_trade_no").toString());
		wpr.setAttach(m.get("attach").toString());
		wpr.setResultCode(m.get("result_code").toString());
		wpr.setReturnCode(m.get("return_code").toString());
		wpr.setSign(m.get("sign").toString());
		wpr.setTimeEnd(m.get("time_end").toString());
		wpr.setTotalFee(m.get("total_fee").toString());
		wpr.setTradeType(m.get("trade_type").toString());
		wpr.setTransactionId(m.get("transaction_id").toString());
		return wpr;
	}
	
	/**
	 * 试用订单支付回调方法
	 */
	@RequestMapping("/probationOrderPayBack")
	public synchronized void probationOrderPayBack(HttpServletRequest request, 
			HttpServletResponse response) throws IOException {
		String inputLine;
		String notityXml = "";
		String resXml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
		try {
			//获取XML参数
			while ((inputLine = request.getReader().readLine()) != null) {
				notityXml += inputLine;
			}
			request.getReader().close();
			//解析XML格式的数据
			Map<String, String> m = parseXmlToList2(notityXml);
			WxPayResult wpr = new WxPayResult();
			wpr=setWxPayResultObj(wpr,m);
			//判断
			if("SUCCESS".equalsIgnoreCase(wpr.getResultCode())){
				//resXml:返回给微信服务器的数据
				resXml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
				String orderIdMD5 = StaticInfo.orderIdMD5.decrypt(wpr.getAttach());
				if (orderIdMD5.equals(wpr.getOutTradeNo())) {
					// 组装数据
					ProbationOrder order = new ProbationOrder();
					order.setProbationOrderid(orderIdMD5);
					order.setProbationStatus(5);// 已支付
					order.setProbationTransactionId(wpr.getTransactionId());// 微信支付ID
					order.setProbationTransactionTime(new Date());// 微信支付时间
					order.setProbationOpenid(wpr.getOpenid());
					
					ProbationOrderDto orderDto = probationShopOrderService.selectProbationOrderByOrderId(orderIdMD5);
					/*计算保存用户订单备注*/
					if(orderDto != null && orderDto.getProbationEndTime() != null){
						/*
						 * 1.试用结束时间减去当前时间，为试用剩余时间
						 * 2.试用总天数(30)减去试用剩余时间，为实际已经试用天数(不含暂停天数)
						 * 3.判断实际已经试用天数 符合最早的则奖励
						 */
						long remainingTime = DateTimeUtil.getDiffTimeMinutes(new Date(), orderDto.getProbationEndTime());
						
						long pastTime = 21 * 24 *60 - remainingTime;
						List< ProbationAwardRelu> list = probationShopOrderService.selectProbationAwardRelu();
						for (ProbationAwardRelu awardRelu : list) {
							if((int)pastTime + 1 < awardRelu.getAwardNum().intValue()){
								order.setProbationUserRemark(awardRelu.getAwardInfo());
								break;
							}
						}
					}
					
					// 修改订单状态 及前台备注
					boolean flag = adminProbationOrderService.updateProbationOrderStatus(order);
					
					try {	//修改用户购买记录为已购买
						memberService.updateIsBaughtByOpenid(wpr.getOpenid(), 2);
						//更新用户绑定状态
						Member member = memberService.getMemberByUserOpenId(order.getProbationOpenid());
						if (member.getUserIsFlag()!= null && member.getUserIsFlag() == 1) {
							member.setUserIsFlag(2);//终身绑定
							homeService.updateMemberIsFlagByOpenid(member);
						}
						try {
						QrcodeResult qr = temporaryQrcodeService.applyTempQrcode(order.getProbationOpenid());//为用户生成二维码
						inLongLogger.info("为用户-->" + order.getProbationOpenid() + ",生成二维码:" + qr.getQroceUrl());
						} catch (Exception e) {
							System.out.println("为用户生成二维码失败!");
						}
					} catch (Exception e) {
						System.out.println("修改已购买状态失败!");
						e.printStackTrace();
					}

					try {
						Member member = memberService.getMemberByUserOpenId(order.getProbationOpenid()); // 当前用户
						probationShopOrderService.insertSalesOrder(orderIdMD5, member.getUserId());
					} catch (Exception e) {
						System.out.println("试用订单转存到订单表出错!");
					}
					
					double money = orderDto.getProbationYetAmount().intValue() / 100;
					try {
						sendMessageUtil.probationPaySuccess(
								ResultInfo.PAYSUCCESS, 
								money + "元", 
								orderDto.getProductName(), 
								ResultInfo.PAYSUCCESSFOOT, 
								order.getProbationOpenid(), 
								ResultInfo.TRY_ORDER_DETAIL + "?orderId=" + orderIdMD5);
					} catch (Exception e) {
						System.out.println("推送支付成功消息失败!");
					}
					
					if (!flag) {
						resXml = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[报文有误]]></return_msg></xml>";
					}
				} else {
					resXml = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[报文有误]]></return_msg></xml>";
					ratFWLogger.error(this, "订单:" + orderIdMD5 + "支付成功，但是没有通过校验!");
				}
			}else{
				resXml = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[报文为空]]></return_msg></xml>";
			}
			BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
			out.write(resXml.getBytes());
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 销售订单支付回调方法
	 */
	@RequestMapping("/leaseOrderPayBack")
	public void leaseOrderPayBack(HttpServletRequest request, 
			HttpServletResponse response) throws IOException {
		synchronized (lock) {
			String inputLine;
			String notityXml = "";
			String resXml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
			try {
				//获取XML参数
				while ((inputLine = request.getReader().readLine()) != null) {
					notityXml += inputLine;
				}
				request.getReader().close();
				//解析XML格式的数据
				Map<String, String> m = parseXmlToList2(notityXml);
				WxPayResult wpr = new WxPayResult();
				wpr=setWxPayResultObj(wpr,m);
				//判断
				if("SUCCESS".equalsIgnoreCase(wpr.getResultCode())){
					//resXml:返回给微信服务器的数据
					resXml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
					String orderIdMD5 = StaticInfo.orderIdMD5.decrypt(wpr.getAttach());
//System.out.println("===========pay 117==============");
					
					if (orderIdMD5.equals(wpr.getOutTradeNo())) {
						Date nowDate = new Date();
						SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						// 组装订单数据
						LeaseOrder order = new LeaseOrder();
						order.setOrderId(orderIdMD5);
						order.setOrderStatus(2); // 已支付
						order.setOrderTransactionId(wpr.getTransactionId()); // 微信支付ID
						order.setOrderTransactionDate(new Date()); // 微信支付时间
						order.setOrderOpenid(wpr.getOpenid());
						
						// 产生安全的code
						String code = adminUtils.byte2hex(adminUtils.createRandomByte());
						try {
							code = NameUtils.getConfig("MACHINE_CODE") + adminUtils.byte2hex(adminUtils.createRandomByte()).substring(0, 10);
						} catch (Exception e) {
							code = NameUtils.getConfig("MACHINE_CODE") + UUID.randomUUID().toString().replaceAll("-", "").substring(0, 10);
						}
						order.setOrderInitCode(code);
						order.setOrderCodeState(1);
						
						//查询购买后机器的初始水量
						ShopSystemRule ShopSystemRule = cartService.getReluByRid(211);
						
						//组装机器数据
						Machine machine = new Machine();
						machine.setMachineOrderId(orderIdMD5);
						machine.setMachineOpenid(order.getOrderOpenid());
						machine.setMachineDeviceId(order.getOrderTransactionId());
						machine.setMachineSurplusWater(ShopSystemRule.getRuleNum().intValue());
						machine.setMachineConnectState(2);
						machine.setMachineInitState(2);
						machine.setMachineState(2);
						machine.setMachineInitCode(code);
						
						
						
						// 修改订单状态即添加激活码
						int count = leaseOrderService.updateLeaseOrderInfo(order,machine);
						
//System.out.println("===========pay 132 修改订单状态==============");
						
						if (count < 1) {
							resXml = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[报文有误]]></return_msg></xml>";
						}
//System.out.println("===========pay 182  插入返利到mq=============="+count);
						//rebackServices.loadSingleOrderReward(order);
						
						//查询订单的收货人和押金
						LeaseOrder leaseOrder = leaseOrderService.selectDepositByOrderId(orderIdMD5);
						
						//发送短信
//						try{
//							codeService.sendLeaseOrderToUser(leaseOrder.getOrderAddressTel(), 
//									format.format(nowDate), leaseOrder.getOrderDeposit(), ShopSystemRule.getRuleNum().intValue());
//						} catch (Exception e) {
//							inLongLogger.info("为订单-->" + order.getOrderId() + ",:" + "发送短信失败");
//						}
						//添加到返利表
						//rebackServices.loadSingleOrderReward(order);
						// 给百胜推送信息
						try {
							MQMessage message = new MQMessage();
							message.setServiceToMessage(orderIdMD5);
							message.setServiceOtherMessage("efast.trade.new.add");
							message.setServiceIsSend(2);			// 没有推送的信息
							message.setServiceStatus(1); 			// 推送成功
							message.setServiceType(1); 				// 添加订单信息
							message.setServiceHandlerObjectName("efastOrderServiceImpl");
							message.setServiceHandlerMethodName("addOrderInfoToEfast");
							mQservice.insertMQMessage(message);
						} catch (Exception e) {
//System.out.println("===========pay 201  插入返利到百胜失败==============");		
						}
//System.out.println("===========pay 201  插入返利到百胜完成==============");		
						try {	//修改用户购买记录为已购买
							memberService.updateIsBaughtByOpenid(wpr.getOpenid(), 2);
							//更新用户绑定状态
							Member member = memberService.getMemberByUserOpenId(order.getOrderId());
							if (member.getUserIsFlag()!= null && member.getUserIsFlag() == 1) {
								member.setUserIsFlag(2);//终身绑定
								homeService.updateMemberIsFlagByOpenid(member);
							}
							QrcodeResult qr = temporaryQrcodeService.applyTempQrcode(order.getOrderId());//为用户生成二维码
							inLongLogger.info("为用户-->" + order.getOrderId() + ",生成二维码:" + qr.getQroceUrl());
						} catch (Exception e) {
							System.out.println("修改已购买状态和终身绑定失败!");
							e.printStackTrace();
						}
						
					} else {
						resXml = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[报文有误]]></return_msg></xml>";
						ratFWLogger.error(this, "订单:" + orderIdMD5 + "支付成功，但是没有通过校验!");
					}
				}else{
					resXml = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[报文为空]]></return_msg></xml>";
				}
				BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
				out.write(resXml.getBytes());
				out.flush();
				out.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 付费代理订单支付回调方法
	 * 2017年2月17日
	 * @author muzx
	 */
	@RequestMapping("/agent_order_pay_back")
	public synchronized void agentOrderPayBack(HttpServletRequest request, 
			HttpServletResponse response) throws IOException {
		String inputLine;
		String notityXml = "";
		String resXml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
		try {
			//获取XML参数
			while ((inputLine = request.getReader().readLine()) != null) {
				notityXml += inputLine;
			}
			request.getReader().close();
			//解析XML格式的数据
			Map<String, String> m = parseXmlToList2(notityXml);
			WxPayResult wpr = new WxPayResult();
			wpr=setWxPayResultObj(wpr,m);
			//判断
			if("SUCCESS".equalsIgnoreCase(wpr.getResultCode())){
				//resXml:返回给微信服务器的数据
				resXml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
				String orderIdMD5 = StaticInfo.orderIdMD5.decrypt(wpr.getAttach());
				inLongLogger.info(this, "orderIdMD5--->>" + orderIdMD5);
				if (orderIdMD5.equals(wpr.getOutTradeNo())) {
					// 组装数据
					AgentPayLogs payLogs = new AgentPayLogs();
					//单号格式：AOID000_ + 支付记录id + "_" + 代理商物流记录id + ("_" + 推荐人物流记录id)<若无推荐人则无此项>
					String[] ids = StrUtils.strToArr(orderIdMD5, "_");
					payLogs.setPayId(Integer.parseInt(ids[1]));
					payLogs.setPayTransactionId(wpr.getTransactionId());// 微信支付ID
					payLogs.setPayTransactionDate(new Date());// 微信支付时间
					payLogs.setPayStatus(2);
					// 修改支付状态
					boolean flag1 = agentService.updatePayLogsById(payLogs);

					//修改当前代理商和推荐人物流记录状态
					Integer agentId1 = Integer.parseInt(ids[2]);
					Integer agentId2 = ids.length > 3 ? Integer.parseInt(ids[3]) : null;
					boolean flag2 = cardService.saveCardAndMachine(1, wpr.getOpenid(), agentId1, agentId2);
					
					try {
						//推送百胜
						AgentMachine agentMachine = agentMachineService.selectAgentMachine(Integer.parseInt(ids[2]));
						efastOrderService.giftCard(agentMachine.getAgentMachineAddressInfo(), "ZS1111111_" + agentMachine.getAgentMachineId(), agentMachine.getAgentMachineColorId(),
								agentMachine.getAgentMachineAddressName(), agentMachine.getAgentMachineAddressTel(), agentMachine.getAgentMachineOpenId());
					} catch (Exception e) {
					    inLongLogger.info(this, "推送百胜失败!");
					    e.printStackTrace();
					}
					
					Member member = memberService.getMemberByUserOpenId(wpr.getOpenid());
					AgentInfo agentInfo = agentService.selectAgentByOpenId(member.getUserOpenid());
					//有推荐人 则推荐人推送消息
					if(agentId2 != null){
						try {
							//从规则表中获取:付费代理商支付金额
							ShopSystemRule shopSystemRule1 =  systemService.selectOneShopRuleById(224);
							int money = shopSystemRule1.getRuleNum().intValue();
							if (agentInfo !=null && StringUtils.isNotEmpty(agentInfo.getAgentReferrerOpenid())) {
								sendMessageUtil.prizeReceivePush(
										"您好，您成功推荐一位代理商，详情为:", 
										URLDecoder.decode(member.getUserNickname(), "UTF-8"),
										"Watero水时代", 
										(money / 100) + "元", 
										DateTimeUtil.format(new Date()), 
										"美国watero净饮水一体机一台",
										"请点击完善收货地址并领取奖励。",
										agentInfo.getAgentReferrerOpenid(), 
										ResultInfo.AGENT_REFERRER_MACHINE_PAGE+"?agentMachineId=" + agentId2
										);
							}
						} catch (Exception e) {
						    inLongLogger.info(this, "给推荐人推送消息失败！");
                            e.printStackTrace();
						}
					}
					if (!(flag1 && flag2)) {
						resXml = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[报文有误]]></return_msg></xml>";
					}
				} else {
					resXml = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[报文有误]]></return_msg></xml>";
					ratFWLogger.error(this, "订单:" + orderIdMD5 + "支付成功，但是没有通过校验!");
				}
			}else{
				resXml = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[报文为空]]></return_msg></xml>";
			}
			BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
			out.write(resXml.getBytes());
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 付费代理订商续费支付回调方法
	 * 2017年2月17日
	 * @author LJK
	 */
	@RequestMapping("/agent_renewal_pay_back")
	public synchronized void agentRenewalPayBack(HttpServletRequest request, 
			HttpServletResponse response) throws IOException {
		String inputLine;
		String notityXml = "";
		String resXml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
		try {
			//获取XML参数
			while ((inputLine = request.getReader().readLine()) != null) {
				notityXml += inputLine;
			}
			request.getReader().close();
			//解析XML格式的数据
			Map<String, String> m = parseXmlToList2(notityXml);
			WxPayResult wpr = new WxPayResult();
			wpr=setWxPayResultObj(wpr,m);
			//判断
			if("SUCCESS".equalsIgnoreCase(wpr.getResultCode())){
				//resXml:返回给微信服务器的数据
				resXml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
				String orderIdMD5 = StaticInfo.orderIdMD5.decrypt(wpr.getAttach());
				System.out.println("orderIdMD5--------------->" + orderIdMD5);
				if (orderIdMD5.equals(wpr.getOutTradeNo())) {
					// 组装数据
					AgentPayLogs payLogs = new AgentPayLogs();
					//单号格式：AOID000_ + 支付记录id + "_" + 代理商物流记录id + ("_" + 推荐人物流记录id)<若无推荐人则无此项>
					String[] ids = StrUtils.strToArr(orderIdMD5, "_");
					payLogs.setPayId(Integer.parseInt(ids[1]));
					payLogs.setPayTransactionId(wpr.getTransactionId());// 微信支付ID
					payLogs.setPayTransactionDate(new Date());// 微信支付时间
					// 修改支付状态
					boolean flag1 = agentService.updatePayLogsById(payLogs);

					//修改当前代理商和推荐人物流记录状态
					Integer agentId1 = Integer.parseInt(ids[2]);
					//Integer agentId2 = ids.length > 3 ? Integer.parseInt(ids[3]) : null;
					AgentInfo agentInfo = agentService.selectAgentByOpenId(wpr.getOpenid());
					int agentType = 1;
					if(agentInfo.getAgentIsHudredAgent() == 1){
					    agentType = 2;
					}
					boolean flag2 = cardService.saveCardAndMachine(agentType, wpr.getOpenid(), agentId1, null);
					
					try {
						//推送百胜
						AgentMachine agentMachine = agentMachineService.selectAgentMachine(Integer.parseInt(ids[2]));
						efastOrderService.giftCard(agentMachine.getAgentMachineAddressInfo(), "ZS1111111_" + agentMachine.getAgentMachineId(), agentMachine.getAgentMachineColorId(),
								agentMachine.getAgentMachineAddressName(), agentMachine.getAgentMachineAddressTel(), agentMachine.getAgentMachineOpenId());
						
					} catch (Exception e) {
						System.out.println("推送百胜失败!");
					}
					if (!(flag1 && flag2)) {
						resXml = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[报文有误]]></return_msg></xml>";
					}
				} else {
					resXml = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[报文有误]]></return_msg></xml>";
					ratFWLogger.error(this, "订单:" + orderIdMD5 + "支付成功，但是没有通过校验!");
				}
			}else{
				resXml = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[报文为空]]></return_msg></xml>";
			}
			BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
			out.write(resXml.getBytes());
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 租赁申请回调
	 * @param request
	 * @param response
	 * @author 献
	 * @Time   2017年3月16日
	 */
	@RequestMapping("/rent_appply")
	public void rentApplyCallback(HttpServletRequest request, 
			HttpServletResponse response) {
		String inputLine;
		String notityXml = "";
		String resXml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
		try {
			//获取XML参数
			while ((inputLine = request.getReader().readLine()) != null) {
				notityXml += inputLine;
			}
			request.getReader().close();
			Map<String, String> m = parseXmlToList2(notityXml);
			WxPayResult wpr = new WxPayResult();
			wpr=setWxPayResultObj(wpr,m);
			//判断
			if("SUCCESS".equalsIgnoreCase(wpr.getResultCode())){
				resXml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
				String orderIdMD5 = StaticInfo.orderIdMD5.decrypt(wpr.getAttach());
				if (orderIdMD5.equals(wpr.getOutTradeNo())) {
					RentApply apply = new RentApply();
					apply.setApplyId(Integer.parseInt(orderIdMD5.replace("DJ00000000", "")));
					apply.setApplyPayMoney(Integer.parseInt(wpr.getTotalFee()));
					leaseOrderService.updateApply(apply);
				} else {
					resXml = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[报文有误]]></return_msg></xml>";
				}
			}else{
				resXml = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[报文为空]]></return_msg></xml>";
			}
			BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
			out.write(resXml.getBytes());
			out.flush();
			out.close();
		} catch (Exception e) {
			
		}
	}
	
	/**
	 * 随机生成一个密码
	 * @param len 密码总长度
	 * @param numLen 需要生成数字的总长度
	 * @return
	 */
	public String getPassward(int len,int numLen) {
		StringBuilder sb = new StringBuilder(len);
		Random rnd = new Random();
		int num = 0;
		//除了数字以外的字母的总长度
		if (len >= numLen) {
			num = len - numLen;
		}
		if (num > 0) {
			String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
			int j = 0;
			while (j < num) {
				//生成一个随机的大写字母
				String letter = String.valueOf(chars.charAt((int)(Math.random() * 26)));
				//该大写字母不能是O,I,L等字母，如果是O,I,L则继续生成并且不添加进sb字符串中
				if (!"O".equals(letter) &&  !"I".equals(letter) && !"L".equals(letter)) {
					sb.append(letter);
					j++;
				}
			}
		}
		for (int i = 0; i < numLen; i++)
			sb.append("0123456789".charAt(rnd.nextInt("0123456789".length())));
		return sb.toString();
	}
}
