package com.palmnest.webapp.controller.wechat;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.wxpay.sdk.WXPay;
import com.palmnest.application.core.util.*;
import com.palmnest.dao.wechat.ReplayContentDao;
import com.palmnest.model.estateserve.*;
import com.palmnest.service.AsynchronousDataService;
import com.palmnest.service.estateserve.*;
import com.palmnest.service.wechat.RechargeManager;
import com.palmnest.service.wechat.WeChatApiManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ExtendedModelMap;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletInputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;


@Slf4j
@Controller
@RequestMapping(value = "/wechat/recharge*")
public class RechargeController {


	//public static String BaseUrl = "http://120.76.98.95/";
	//11.21号修改，主要是针对https
	public static String BaseUrl = PropertiesKit.readPropertiesValue("rechargeBaseUrl", "wechat.properties");

	public static String                  webUrl = PropertiesKit.readPropertiesValue("callbackWebUrl", "wechat.properties");
	//支付api的密钥
	public static String                  appkey = PropertiesKit.readPropertiesValue("ClientAppKey", "wechat.properties");
	@Autowired
	private       RechargeManager         rechargeManager;
	@Autowired
	private       WeChatApiManager        weChatApiManager;
	@Autowired
	private       PublicNoManager         publicNoManager;
	@Autowired
	private       AsynchronousDataService asynchronousWorkService;
	@Autowired
	private       RechargeWebManager      rechargeWebManager;
	@Autowired
	private       AppUserManager          appUserManager;
	@Autowired
	private       ServicePackManager      servicePackManager;
	@Autowired
	private       ScWxuserManager         scWxuserManager;


	@Autowired
	private ReplayContentDao replayContentDao;

	/**
	 * 支付返回url
	 */
	public static String notifyUrl        = webUrl + "/wechat/wxcallback/notifyUrl";
	/**
	 * 充值返回url
	 */
	public static String callbackUrl      = webUrl + "/wechat/recharge/callbackUrl";
	/**
	 * 充值返回url
	 */
	public static String callbackVideoUrl = webUrl + "/wechat/recharge/callbackVideoUrl";

	public static String palmpay = PropertiesKit.readPropertiesValue("palmpay", "wechat.properties");

	/**
	 * 跳转充值页面
	 *
	 * @param params
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "toFlowRecharge")
	public String toFlowRecharge(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {

		log.info("RechargeController toFlowRecharge request.getRequestURI()====" + request.getRequestURI());

		String   token   = "";
		Cookie[] Cookies = request.getCookies();
		if (null != Cookies) {
			for (int i = 0; i < Cookies.length; i++) {
				Cookie cookie = Cookies[i];
				log.info("toFlowRecharge cookie " + cookie.getName() + "===:" + cookie.getValue() + "===");
				if (StringUtils.isNotEmpty(cookie.getName()) && cookie.getName().equals("superDesk")) {
					token = cookie.getValue();
					continue;
				}

			}
		}


		Enumeration reqNames = request.getParameterNames();
		for (Enumeration e = reqNames; e.hasMoreElements(); ) {
			String reqName  = e.nextElement().toString();
			String reqValue = request.getParameter(reqName);
			log.info("toFlowRecharge " + reqName + "===:" + reqValue + "===");
		}

		String developId     = request.getParameter("developId");    //微信公众号id
		String openId        = request.getParameter("openId");            //用户标识
		String operationType = request.getParameter("operationType");
		String channelCode   = request.getParameter("channelCode");    //渠道

		String redirectUrl = "";
		request.setAttribute("developId", developId);
		request.setAttribute("openId", openId);
		request.setAttribute("payWay", "wxpay");
		request.setAttribute("tradeType", "JSAPI");
		request.setAttribute("operationType", operationType);
		request.setAttribute("webUrl", webUrl);
		request.setAttribute("channelCode", channelCode);
		//流量
		if (operationType.equals("0")) {
			redirectUrl = "wechat/flowRecharge";
		}
		//话费
		if (operationType.equals("1")) {
			redirectUrl = "wechat/phoneRecharge";
		}
		//话费
		if (operationType.equals("h5")) {
			redirectUrl = "wechat/phoneRecharge_h5";
		}
		//11.29新增 令令开门生成二维码
		if (operationType.equals("2")) {
			redirectUrl = "wechat/lingLOpen";
		}
		//加油卡
		if ("JYK".equals(operationType)) {
			List<ProductCategories> categoriesList = servicePackManager.queryCategoriesListByServiceCode(operationType);
			request.setAttribute("categoriesList", categoriesList);
			request.setAttribute("imageServer", FileUploadUtils.getVisitPrefix());
			redirectUrl = "wechat/fuelcardRecharge";
		}
		return redirectUrl;
	}

	@RequestMapping(value = "rechargeUserAuthor")
	public ModelAndView rechargeUserAuthor(HttpServletRequest request, HttpServletResponse response) throws Exception {
		try {
			String     developId     = request.getParameter("developId");
			String     operationType = request.getParameter("operationType");
			String     channelCode   = request.getParameter("channelCode");
			WxPublicno wxPublicno    = publicNoManager.getByDevelopId(developId);
			String     url           = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + wxPublicno.getAppId();
			String     authorUrl     = webUrl + "/wechat/frontSecurity/auth?redirectUrl=/wechat/recharge/toFlowRecharge&operationType=" + operationType + "&channelCode=" + channelCode;
			url += "&redirect_uri=" + URLEncoder.encode(authorUrl, "UTF-8") + "&response_type=code&scope=snsapi_base&state=" + wxPublicno.getId() + "#wechat_redirect";
			return new ModelAndView("redirect:" + url);
		} catch (Exception e) {
			log.error("visitorUserAuthor:" + e.getMessage());
		}
		return null;
	}

	/**
	 * 查询产品
	 *
	 * @param params
	 * @return
	 */
	@RequestMapping(value = "findProduct")
	public String findProduct(HttpServletRequest request, HttpServletResponse response) {
		String     mobile        = request.getParameter("mobile");
		String     operationType = request.getParameter("operationType");
		JSONObject json          = new JSONObject();
		try {
			if (operationType.equals("0") || operationType.equals("1") || operationType.equals("h5")) {
				json = StringUtil.getMobileAddressTaoBao(mobile);
				if (null != json) {
					String        carrieroperator = json.getString("carrier");
					String        province        = json.getString("province");
					List<Product> product         = rechargeManager.findProduct(province, carrieroperator, operationType, "1");
					json = new JSONObject();
					json.put("carrieroperator", carrieroperator);
					json.put("list", product);
					StringUtil.charSet(json, request, response);
				}
			} else {
				List<Product> product = rechargeManager.findProduct("全国", "全国", operationType, "1");
				json = new JSONObject();
				json.put("list", product);
				StringUtil.charSet(json, request, response);
			}
		} catch (Exception e) {
			log.error("findProduct occur error." + LogExceptionStackUtil.LogExceptionStack(e));
		}
		return null;
	}

	/**
	 * 生成订单号
	 *
	 * @param params
	 * @return
	 */
	@RequestMapping(value = "createOrdId")
	public String createOrdId(HttpServletRequest request, HttpServletResponse response) {
		Map<String, String> map         = new HashMap<String, String>();
		String              productId   = request.getParameter("productId");
		String              developId   = request.getParameter("developId");
		String              mobile      = request.getParameter("mobile");
		String              type        = request.getParameter("type");            //0流量，1话费
		String              openId      = request.getParameter("openId");
		String              payWay      = request.getParameter("payWay");
		String              channelCode = request.getParameter("channelCode");
		log.info("==createOrdId==");
		log.info("openId:" + openId);
		log.info("productId:" + productId);
		log.info("mobile:" + mobile);
		log.info("channelCode:" + channelCode);

		JSONObject json = new JSONObject();
		if (StringUtils.isEmpty(type)) {
			type = "0";
		}
		if (StringUtils.isEmpty(mobile) && (type.equals("0") || type.equals("1"))) {
			json.put("code", -1);
			json.put("msg", "请填写手机号码");
			StringUtil.charSet(json, request, response);
			return null;
		}
		if (StringUtils.isEmpty(productId)) {
			json.put("code", -1);
			json.put("msg", "请选择产品");
			StringUtil.charSet(json, request, response);
			return null;
		}
		Map<String, String> mapPt = rechargeManager.findProductById(Integer.valueOf(productId));
		String              body  = "";
		String              ordId = "";
		if (mapPt.get("type").equals("0")) {
			ordId = StringUtil.getOrderId("CG");//生成订单号
			body = mapPt.get("productName") + "流量-" + mobile;
			map.put("type", "0");//私有字段，原路返回
		}
		if (mapPt.get("type").equals("1")) {
			ordId = StringUtil.getOrderId("CG");//生成订单号
			body = mapPt.get("productName") + "元话费-" + mobile;
			map.put("type", "1");//私有字段，原路返回
		}
		map.put("outTradeNo", ordId);
		map.put("totalFee", String.valueOf(mapPt.get("realPrice")));
		map.put("notifyUrl", notifyUrl);
		map.put("mobile", mobile);
		map.put("body", body);
		map.put("type", type);
		map.put("productId", productId);
		map.put("openId", openId);
		map.put("developId", developId);
		map.put("tradeType", "JSAPI");
		map.put("appkey", appkey);
		map.put("payWay", payWay);
		String timeStamp = DateUtils.getTime("");
		map.put("timeStamp", timeStamp);
		//附加数据
		String attach = "{'sbpillCreateIp':'" + StringUtil.getIpAddr(request) + "','openId':'" + openId + "','type':'" + type + "'}";
		map.put("timeStamp", timeStamp);
		map.put("attach", attach);
		try {
			AppUser appUser = appUserManager.getAppUserByOpenId(developId, openId);
			if (appUser != null) {
				log.info("appUser's id:" + appUser.getId());
				if (appUser.getOrganizationId() != null) {
					log.info("organizationId:" + appUser.getOrganizationId());
					map.put("organizationId", appUser.getOrganizationId() + "");
				}
				if (appUser.getVirtualArchId() != null) {
					map.put("virtualArchitectureId", appUser.getVirtualArchId() + "");
				}
			} else {
				WxUser wxUser = scWxuserManager.getScWxuserByOpenId(openId);
				if (wxUser != null && wxUser.getOrganizationId() != null) {
					log.info("wxUser's id:" + wxUser.getId());
					log.info("organizationId:" + wxUser.getOrganizationId());
					map.put("organizationId", wxUser.getOrganizationId() + "");
				}
			}
			map.put("channelCode", channelCode);
			//添加充值记录
			int result = rechargeManager.addRecharge(map);
			if (result < 0) {
				json.put("code", -1);
				json.put("msg", "系统异常，请稍后再试");
				json.put("wxPayMap", "");
				StringUtil.charSet(json, request, response);
				return null;
			}
			json.put("code", 0);
			json.put("rechargeId", result);
			WxPublicno wx = publicNoManager.getByDevelopId(developId);
			map.put("appId", wx.getAppId());
			map.put("subject", "subject");
			map.put("palmpay", palmpay + "/unifiedorder");
			BigDecimal realPrice = new BigDecimal(String.valueOf(mapPt.get("realPrice")));
			//调用接口
			map.put("totalFee", realPrice.multiply(new BigDecimal(100)).intValue() + "");
			//调用微信支付接口
			String jsonStr = StringUtil.rechargePay(map);
			if (StringUtils.isEmpty(jsonStr)) {
				json.put("code", -1);
				json.put("msg", "支付失败");
				StringUtil.charSet(json, request, response);
				return null;
			}
			json = JSON.parseObject(jsonStr);
			StringUtil.charSet(json, request, response);
			return null;
		} catch (Exception e) {
			json.put("code", -1);
			json.put("msg", "系统异常，请稍后再试");
			StringUtil.charSet(json, request, response);
			log.error("createOrdId occur error." + LogExceptionStackUtil.LogExceptionStack(e));
		}
		return null;
	}

	/**
	 * 手机充值回调
	 *
	 * @return
	 */
	@RequestMapping(value = "callbackUrl")
	public String callbackUrl(HttpServletRequest request, HttpServletResponse response) {
		try {
			ServletInputStream in     = request.getInputStream();
			String             xmlMsg = Tools.inputStream2String(in);
			log.info("StringUtil.xmlToJSON(xmlMsg)=========" + StringUtil.xmlToJSON(xmlMsg));

			JSONObject jsonObject = JSON.parseObject(StringUtil.xmlToJSON(xmlMsg));
			JSONObject body       = jsonObject.getJSONObject("body");
			JSONObject json       = body.getJSONObject("result");
			log.info("手机充值回调开始====" + json.getString("rechargeStatus"));
			//rechargeDesc--增加回调充值失败原因
			if (json.getString("rechargeStatus").equals("0")) {
				//查询支付状态
				Recharge re        = rechargeManager.findRechargeByOrdId(json.getString("orderid"));
				String   openId    = re.getOpenId();
				String   price     = re.getPrice() + "元";
				String   developId = re.getDevelopId();
				String   productId = re.getProductId() + "";
				String   mobile    = re.getMobile();
				if (re.getStatus().equals("0") && re.getPayStatus().equals("0") && re.getType().equals("0")) {
					String rechargeDesc = "暂无";
					if (null != json.getString("rechargeDesc") && !json.getString("rechargeDesc").equals("") && !json.getString("rechargeDesc").equals("(null)")) {
						rechargeDesc = json.getString("rechargeDesc");
					}
					re.setRecharTime(DateUtils.formatDate(new Date()));
					re.setRechargeDesc(rechargeDesc);
					re.setStatus("1");
					//更新充值状态
					int result = rechargeManager.updateRecharge(re);
					if (result > 0) {
						//查询支付状态
//						re = rechargeManager.findRecharge(jsonObject.getString("orderid"));
						Map<String, String> map   = rechargeManager.findProductById(Integer.valueOf(productId));
						String              title = "您成功充值流量" + map.get("productName") + "，请留意到账短信通知";
						title += "手机号码:" + mobile + "\\n";
						title += "金额:" + price;
						String remark = "如有问题请微信留言，小超将第一时间为您服务！";
						// 调用支付成功微信通知
						Map<String, String> paramMap = new HashMap<String, String>();
						List<Map<String, Object>> templateList = replayContentDao
								.getWxTemplate("7", 0);
						if (templateList != null) {
							String templateId = (String) templateList.get(0)
									.get("templateId");
							String webUrl = PropertiesKit.readPropertiesValue("callbackWebUrl", "wechat.properties");
							String url    = webUrl + "/wechat/recharge/getRechareRecordInfo?id=" + re.getId() + "&developId=" + re.getDevelopId() + "&operationType=" + map.get("type") + "&oepnId=" + re.getOpenId() + "&channelCode=" + re.getChannelCode();
							paramMap.put("developId", developId);
							paramMap.put("templateId", templateId);
							paramMap.put("mobile", mobile);
							paramMap.put("openId", openId);
							paramMap.put("title", title);
							paramMap.put("statusName", "流量");
							paramMap.put("createTime", re.getRecharTime());
							paramMap.put("price", price);
							paramMap.put("remark", remark);
							paramMap.put("url", url);
							paramMap.put("orderNo", re.getOutTradeNo());
							weChatApiManager.sendTemplateMsg07(paramMap);
						}
						response.getWriter().write("success");
						return null;
					}
				}
			} else {
				//查询支付状态
				Recharge re = rechargeManager.findRechargeByOrdId(json.getString("orderid"));
				//已经退款
				if (null != re && re.getStatus().equals("2")) {
					response.getWriter().write("success");
					return null;
				}
				String rechargeDesc = "暂无";
				if (null != json.getString("rechargeDesc") && !json.getString("rechargeDesc").equals("") && !json.getString("rechargeDesc").equals("(null)")) {
					rechargeDesc = json.getString("rechargeDesc");
				}
				re.setRecharTime(DateUtils.formatDate(new Date()));
				re.setRechargeDesc(rechargeDesc);
				re.setStatus("2");

				rechargeManager.updateRecharge(re);
				//根据订单号查询充值信息
				String     jsonStr     = StringUtil.getRecharge(re.getOutTradeNo(), "1");
				JSONObject jsonObjects = JSON.parseObject(StringUtil.xmlToJSON(jsonStr));
				JSONObject bodyJson    = jsonObjects.getJSONObject("body");
				JSONObject resultJson  = bodyJson.getJSONObject("result");
				if (!resultJson.getString("rechargeStatus").equals("0") && !resultJson.getString("rechargeStatus").equals("2") && !resultJson.getString("rechargeStatus").equals("3")) {
					rechargeWebManager.updateDrawback(re.getOutTradeNo());
				}
				response.getWriter().write("success");
			}

		} catch (Exception e) {
			log.error("callbackUrl error {}", e, e.getMessage());
		}
		return null;
	}

	/**
	 * 查询充值记录信息
	 *
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/getRechargeRecord")
	public ModelAndView getRechargeRecord(HttpServletRequest request) throws Exception {
		Model                     model         = new ExtendedModelMap();
		String                    openId        = request.getParameter("openId");
		String                    developId     = request.getParameter("developId");
		String                    operationType = request.getParameter("operationType");
		String                    channelCode   = request.getParameter("channelCode");
		List<Map<String, Object>> recordList    = rechargeManager.getRechargeRecode(openId);
		model.addAttribute("payWay", "wxpay");//
		model.addAttribute("tradeType", "JSAPI");//
		model.addAttribute("operationType", operationType);//
		model.addAttribute("openId", openId);
		model.addAttribute("developId", developId);
		model.addAttribute("recordList", recordList);
		model.addAttribute("channelCode", channelCode);
		model.addAttribute("visitPrefix", FileUploadUtils.getVisitPrefix());
		return new ModelAndView("/wechat/rechargeRecord", model.asMap());
	}

	/**
	 * 查询充值记录信息
	 *
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/getRechareRecordInfo")
	public ModelAndView getRechareRecordInfo(HttpServletRequest request) throws Exception {
		Model               model         = new ExtendedModelMap();
		String              id            = request.getParameter("id");
		String              developId     = request.getParameter("developId");
		String              operationType = request.getParameter("operationType");
		String              oepnId        = request.getParameter("openId");
		String              channelCode   = request.getParameter("channelCode");
		Map<String, Object> resultMap     = rechargeManager.getRechareRecordInfo(Integer.parseInt(id));
		model.addAttribute("payWay", "wxpay");//
		model.addAttribute("tradeType", "JSAPI");//
		model.addAttribute("operationType", operationType);//
		model.addAttribute("openId", oepnId);
		model.addAttribute("developId", developId);
		model.addAttribute("visitPrefix", FileUploadUtils.getVisitPrefix());
		model.addAttribute("resultMap", resultMap);
		model.addAttribute("channelCode", channelCode);
		return new ModelAndView("/wechat/rechargeRecordInfo", model.asMap());
	}

	@RequestMapping("/moviesvipreCharge")
	public ModelAndView moviesvipreCharge(HttpServletRequest request) throws Exception {
		Model             model             = new ExtendedModelMap();
		String            operationType     = request.getParameter("operationType");
		String            developId         = request.getParameter("developId");    //微信公众号id
		String            openId            = request.getParameter("openId");            //用户标识
		String            channelCode       = request.getParameter("channelCode");    //渠道
		List<Product>     product           = rechargeManager.findProduct("全国", "全国", operationType, "1");//查询影视会员下的产品
		ProductCategories productCategories = servicePackManager.querProductCategoriesByServiceCode(operationType);
		model.addAttribute("payWay", "wxpay");
		model.addAttribute("tradeType", "JSAPI");
		model.addAttribute("developId", developId);
		model.addAttribute("openId", openId);
		model.addAttribute("visitPrefix", FileUploadUtils.getVisitPrefix());
		model.addAttribute("channelCode", channelCode);
		model.addAttribute("productList", product);
		model.addAttribute("operationType", operationType);
		model.addAttribute("productCategories", productCategories);
		model.addAttribute("webUrl", webUrl);
		return new ModelAndView("/wechat/moviesviprecharge", model.asMap());
	}

	/**
	 * 影视会员或加油卡订单生成
	 *
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "createOrder", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json;charset=UTF-8")
	public @ResponseBody
	String createOrder(HttpServletRequest request) throws Exception {
		Map<String, String> reqParams = null;
		try {
			reqParams = RequestInfoUtil.requestUtil(request);//获取request转成Map
			Map<String, String> map               = rechargeManager.findProductById(Integer.valueOf(reqParams.get("productId")));//获取到产品详情
			ProductCategories   productCategories = servicePackManager.querProductCategoriesByServiceCode(map.get("type"));
			String              orderId           = StringUtil.getOrderId("CG");
			reqParams.put("outTradeNo", orderId);//订单号
			BigDecimal realPrice = new BigDecimal(String.valueOf(map.get("realPrice")));
			BigDecimal totalFee  = new BigDecimal(reqParams.get("number")).multiply(realPrice);
			reqParams.put("totalFee", totalFee.doubleValue() + "");//总价
			reqParams.put("notifyUrl", notifyUrl);//回调URL
			reqParams.put("body", productCategories.getName() + "-" + map.get("productName") + "-" + reqParams.get("mobile"));//商品描述
			reqParams.put("tradeType", "JSAPI");//支付方式
			reqParams.put("appkey", appkey);//平台密钥
			String timeStamp = DateUtils.getTime("");
			reqParams.put("timeStamp", timeStamp);
			//附加数据
			String attach = "{'sbpillCreateIp':'" + StringUtil.getIpAddr(request) + "','openId':'" + reqParams.get("openId") + "','type':'" + reqParams.get("type") + "'}";
			reqParams.put("timeStamp", timeStamp);
			reqParams.put("attach", attach);
			reqParams = rechargeManager.createOrder(reqParams);
			if (reqParams == null) {
				reqParams = new HashMap<String, String>();
				reqParams.put("code", "-1");
				reqParams.put("msg", "网络异常，请稍后再试");
			}
		} catch (Exception e) {
			log.error("生成影视会员或加油卡订单失败 错误信息{}", LogExceptionStackUtil.LogExceptionStack(e));
			reqParams = new HashMap<String, String>();
			reqParams.put("code", "-1");
			reqParams.put("msg", "网络异常，请稍后再试");
		}
		return net.sf.json.JSONObject.fromObject(reqParams).toString();
	}

	/**
	 * 影视会员||油卡回调
	 *
	 * @return
	 */
	@RequestMapping(value = "callbackVideoUrl")
	public String callbackVideoUrl(HttpServletRequest request, HttpServletResponse response) {
		try {
			ServletInputStream in     = request.getInputStream();
			String             xmlMsg = Tools.inputStream2String(in);
			log.info("callbackVideoUrl xmlMsg========" + xmlMsg);
			if (StringUtils.isNotBlank(xmlMsg)) {
				JSONObject          jsonObject   = JSON.parseObject(xmlMsg);
				String              ORDER_NO     = jsonObject.getString("ORDER_NO");
				String              ORDER_STATUS = jsonObject.getString("ORDER_STATUS");
				Recharge            recharge     = rechargeManager.findRechargeByOrdId(ORDER_NO);
				Map<String, String> map          = rechargeManager.findProductById(recharge.getProductId());
				log.info("蜂助手" + map.get("productName") + "回调开始====订单号：" + ORDER_NO + "状态为：" + ORDER_STATUS);
				if (ORDER_STATUS.equals("RECHAGE_OK")) {
					//查询支付状态
					Recharge re        = rechargeManager.findRechargeByOrdId(ORDER_NO);
					String   openId    = re.getOpenId();
					String   price     = re.getPrice() + "元";
					String   developId = re.getDevelopId();
					String   mobile    = re.getMobile();
					if (re.getStatus().equals("0") && re.getPayStatus().equals("0")) {
						re.setRecharTime(DateUtils.formatDate(new Date()));
						re.setRechargeDesc(ORDER_STATUS);
						re.setStatus("1");
						//更新充值状态
						int result = rechargeManager.updateRecharge(re);
						if (result > 0) {
							ProductCategories productCategories = servicePackManager.querProductCategoriesByServiceCode(map.get("type"));
							String            title             = "您成功充值" + productCategories.getName() + "-" + map.get("productName") + "，请留意到账短信通知\\n";
							title += "手机号码:" + mobile + "\\n";
							String remark = "如有问题请微信留言，小超将第一时间为您服务！";
							// 调用支付成功微信通知
							Map<String, String> paramMap = new HashMap<String, String>();
							List<Map<String, Object>> templateList = replayContentDao
									.getWxTemplate("7", 0);
							if (templateList != null) {
								String templateId = (String) templateList.get(0)
										.get("templateId");
								String webUrl = PropertiesKit.readPropertiesValue("callbackWebUrl", "wechat.properties");
								String url    = webUrl + "/wechat/recharge/getRechareRecordInfo?id=" + re.getId() + "&developId=" + re.getDevelopId() + "&operationType=" + map.get("type") + "&oepnId=" + re.getOpenId() + "&channelCode=" + re.getChannelCode();
								paramMap.put("developId", developId);
								paramMap.put("templateId", templateId);
								paramMap.put("mobile", mobile);
								paramMap.put("openId", openId);
								paramMap.put("title", title);
								paramMap.put("statusName", productCategories.getName());
								paramMap.put("price", price);
								paramMap.put("remark", remark);
								paramMap.put("url", url);
								paramMap.put("orderNo", ORDER_NO);
								paramMap.put("createTime", re.getRecharTime());
								weChatApiManager.sendTemplateMsg07(paramMap);
							}
							JSONObject jsonObject2 = new JSONObject();
							jsonObject2.put("result", "SUCCESS");
							jsonObject2.put("result_desc", "收到结果");
							response.getWriter().write(jsonObject2.toJSONString());
							return null;
						}
					}
				} else {
					//查询支付状态
					Recharge re = rechargeManager.findRechargeByOrdId(ORDER_NO);
					//已经退款
					if (null != re && re.getStatus().equals("2")) {
						JSONObject jsonObject2 = new JSONObject();
						jsonObject2.put("result", "SUCCESS");
						jsonObject2.put("result_desc", "收到结果");
						response.getWriter().write(jsonObject2.toJSONString());
						return null;
					}
					re.setRecharTime(DateUtils.formatDate(new Date()));
					re.setRechargeDesc(ORDER_STATUS);
					re.setStatus("2");
					rechargeManager.updateRecharge(re);
					rechargeWebManager.updateDrawback(re.getOutTradeNo());
					JSONObject jsonObject2 = new JSONObject();
					jsonObject2.put("result", "SUCCESS");
					jsonObject2.put("result_desc", "收到结果");
					response.getWriter().write(jsonObject2.toJSONString());
				}
			}

		} catch (Exception e) {
			log.error("callbackVideoUrl error {}", e, e.getMessage());
		}
		return null;
	}

	/**
	 * H5充值
	 *
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "wechatH5_", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json;charset=UTF-8")
	public @ResponseBody
	String wechatH5_(HttpServletRequest request) throws Exception {
		Map<String, String> reqParams = null;
		try {
			reqParams = RequestInfoUtil.requestUtil(request);//获取request转成Map
			WXConfig config = new WXConfig();
			WXPay    wxPay  = new WXPay(config);

			//金额
			Long money = 1L;


			Date   nowDate      = new Date();
			String out_trade_no = String.valueOf(nowDate.getTime());

			Map<String, String> data = new HashMap<String, String>();
			data.put("body", "短信包充值测试");
			data.put("out_trade_no", out_trade_no);
			data.put("device_info", "");
			data.put("fee_type", "CNY");
			data.put("total_fee", String.valueOf(money));
			data.put("spbill_create_ip", "120.24.83.59");
			data.put("notify_url", "http://120.24.83.59:8080/message-web/message/wxpayNotify");//异步接收微信支付结果通知的回调地址，通知url必须为外网可访问的url，不能携带参数。
			data.put("trade_type", "MWEB");  // 此处指定为app支付
			data.put("product_id", "12");
			Map<String, String> resp = wxPay.unifiedOrder(data);
			if (resp.get("return_code").equals("SUCCESS")) {

			}

		} catch (Exception e) {
			log.error("下单失败！{}", LogExceptionStackUtil.LogExceptionStack(e));
			reqParams = new HashMap<String, String>();
			reqParams.put("code", "-1");
			reqParams.put("msg", "网络异常，请稍后再试");
		}
		return net.sf.json.JSONObject.fromObject(reqParams).toString();
	}

	public static void main(String[] args) {
		System.out.println(StringUtil.getOrderId("CG"));
	}
}