package com.wechat.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

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

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeFastpayRefundQueryRequest;
import com.alipay.api.response.AlipayTradeCloseResponse;
import com.alipay.api.response.AlipayTradeFastpayRefundQueryResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.wechat.common.Constants;
import com.wechat.common.utils.DateUtils;
import com.wechat.common.utils.MessageUtils;
import com.wechat.common.utils.StringsUtils;
import com.wechat.dao.MdeAddressDao;
import com.wechat.dao.MdeGoodsDao;
import com.wechat.dao.MdeOrdersDao;
import com.wechat.dao.MdeTicketDetailDao;
import com.wechat.dao.RedisGoodsSaleDao;
import com.wechat.global.CustomException;
import com.wechat.global.base.BaseService;
import com.wechat.global.base.dao.RedisWithExpiryTimeDao;
import com.wechat.global.message.InfoMsg;
import com.wechat.model.dbEntity.MdeGoods;
import com.wechat.model.dbEntity.MdeInvoiceTitle;
import com.wechat.model.dbEntity.MdeOrders;
import com.wechat.model.dbEntity.MdeTicketDetail;
import com.wechat.model.dbEntity.MdeUser;
import com.wechat.model.dbEntity.MdeVipPackage;
import com.wechat.model.dbEntity.MdeVipPackagePrice;
import com.wechat.model.dto.AddressesDto;
import com.wechat.model.dto.AuzAccesTokenDto;
import com.wechat.model.dto.OrderDetailDto;
import com.wechat.model.dto.VipPackagePriceDto;
import com.wechat.model.requestDto.GoodsOrdersReq;
import com.wechat.model.requestDto.MdeOrdersReq;
import com.wechat.model.responseDto.ResultEntity;
import com.wechat.sdk.api.PaymentApi;
import com.wechat.sdk.kit.IpKit;
import com.wechat.sdk.kit.PaymentKit;

/**
 * @author jadyn.wu
 * @date: 2019-09-07 18:17
 */
@Service
public class OrderService extends BaseService{

	@Autowired
	MdeVipPackageService mdeVipPackageService;

	@Autowired
	MdeInvoiceTitleService mdeInvoiceTitleService;
	
	@Autowired
	MdeUserService mdeUserService;

	@Autowired
	MdeOrdersService ordersService;

	@Autowired
	CommonService commonService;

	@Resource
	MdeTicketDetailService tdService;
	
	@Resource
	RedisWithExpiryTimeDao redisDao;
	
	@Autowired
	MdeOrdersDao mdeOrdersDao;
	
	@Resource
	MdeTicketDetailDao ticketDetailDao;
	
	@Autowired
	MdeGoodsDao goodsDao;
	
	@Autowired
	MdeGoodsService mdeGoodsService;
	
	@Autowired
	MdeAddressDao addressDao;
	
	@Autowired
	private RedisGoodsSaleDao goodsRedisDao;
	
	@Value("#{configProperties['url.base']}")
	private String domainUrl;// 主域名 带/
	
	/******线下支付卖家信息******/
	@Value("#{configProperties['default.invoiceContent']}")
	private String invoiceContent;
	@Value("#{configProperties['default.invoiceContent_en']}")
	private String invoiceContentEn;

	@Value("#{configProperties['default.accountName']}")
	private String accountName;
	@Value("#{configProperties['default.accountName_en']}")
	private String accountNameEn;
	
	@Value("#{configProperties['default.openingBank']}")
	private String openingBank;
	@Value("#{configProperties['default.openingBank_en']}")
	private String openingBankEn;

	@Value("#{configProperties['default.account']}")
	private String account;

	/******AliPay******/
	@Value("#{configProperties['AliPay.appId']}")
	private String alipay_appId;

	@Value("#{configProperties['AliPay.gatewayUrl']}")
	private String alipay_gatewayUrl;

	@Value("#{configProperties['AliPay.merchantPrivateKey']}")
	private String alipay_merchantPrivateKey;

	@Value("#{configProperties['AliPay.charset']}")
	private String alipay_charset;

	@Value("#{configProperties['AliPay.alipayPublicKey']}")
	private String alipay_publicKey;

	@Value("#{configProperties['AliPay.signType']}")
	private String alipay_signType;

	@Value("#{configProperties['AliPay.notifyUrl']}")
	private String alipay_notifyUrl;

	@Value("#{configProperties['AliPay.returnUrl']}")
	private String alipay_returnUrl;

	/******WechatPay******/
	// 请求授权access_token路径
	
	@Value("#{configProperties['weixin.authorization.code']}")
	private String wxAuzCodeUrl;
	
	@Value("#{configProperties['weixin.authorization.token']}")
	private String wxAuzTokenUrl;
	
	@Value("#{configProperties['WXpay.appid']}")
	private String WXpay_appId;
	
	@Value("#{configProperties['WXpay.appKey']}")
	private String WXpay_appKey;
	
	@Value("#{configProperties['WXpay.appSecret']}")
	private String WXpay_appSecret;
	// 商户号
	@Value("#{configProperties['WXpay.mchId']}")
	private String WXpay_mchId;
	// 回调地址
	@Value("#{configProperties['WXpay.notifyUrl']}")
	private String WXpay_notifyUrl;
	
	// 回调地址
	@Value("#{configProperties['WXpay.codeUrl']}")
	private String WXpay_codeUrl;
	// 企业线下支付最终付款期限
	@Value("#{configProperties['deadline_payment']}")
	private String Deadline_payment;
	
	@Value("#{configProperties['default.freight']}")
	private String DefaultFreight;
	
	
	/**
	 * 初始化开票信息
	 * 
	 */
	public Map<String, Object> initInvoiceInfo(String lang, String identityFlag){
		Map<String, Object> map = new HashMap<String, Object>();
		// 开票内容
		if(lang.equals("en")) {
			map.put("invoiceContent", invoiceContentEn);
		}else {
			map.put("invoiceContent", invoiceContent);
		}

		// 企业线下支付信息
		if (StringsUtils.isEqual(identityFlag, "1")) {
			if(lang.equals("en")) {
				map.put("accountName", accountNameEn);
				map.put("openingBank", openingBankEn);
			}else {
				map.put("accountName", accountName);
				map.put("openingBank", openingBank);
			}
			map.put("account", account);
			map.put("deadlinePayment", Deadline_payment);
		}
		return map;
	}
	
	
	/**
	 * 保存订单并调用第三方支付接口
	 * 
	 * @param mdeOrders
	 * @param request
	 * @param response
	 * @return
	 * @throws AlipayApiException
	 * @throws IOException
	 */
	@Transactional
	public Map<String, String> confirmOrder(MdeOrdersReq mdeOrdersReq, HttpServletRequest request, HttpServletResponse response) throws AlipayApiException, IOException 
	{
		String userCode = commonService.getUserCode(request);
		String identityFlag = commonService.getIdentityFlag(request);
		
		MdeOrders oldOrder =  new MdeOrders();
		String oldTdCode = "";
		//更新订单的情况下
		if(!StringsUtils.isEmpty(mdeOrdersReq.getOrderId()))
		{
			oldOrder = mdeOrdersDao.getOrderInfoByCode(mdeOrdersReq.getOrderId(),userCode);
			oldTdCode = oldOrder.getTdCode();
		}
		
		// 初始化订单
		MdeOrders mdeOrders = initOrderInfo(userCode, identityFlag, mdeOrdersReq,oldOrder);

		// 抵用券处理 当原订单的优惠券详情id为空 或者 有修改时才进行数据处理
		if(StringsUtils.isEmpty(oldTdCode) || !oldTdCode.equals(mdeOrders.getTdCode()))
		{
			mdeOrders = resolveTicket(mdeOrders,commonService.getLanguage(request));
		}
		
//		// 开票
//		makeBill(mdeOrders);
		// 创建订单
		if(StringsUtils.isEmpty(mdeOrdersReq.getOrderId()))
		{
			mdeOrdersDao.insertNewOrder(mdeOrders);
		}else {
			//更新订单
			mdeOrdersDao.updateById(mdeOrders);
		}

		Map<String, String> result = new HashMap<String, String>();
		result.put("orderId", mdeOrders.getOrderId());// 返回订单信息
		// 企业--线下支付
		if(mdeOrders.getOrderId().startsWith("E") ) {
			result.put("accountName", accountName);
			result.put("openingBank", openingBank);
			result.put("account", account);
//			result.put("remittanceIdentificationCode", orderId);//汇款识别码
			result.put("deadlinePayment", Deadline_payment);
			return result;
		}
		// 个人--支付宝/微信  调用第三方支付接口
		// 支付宝支付(生成支付页面)
		if (StringsUtils.isEqual(mdeOrders.getPayType(), "2")) {
			// PC端订单
			if (StringsUtils.isEqual(mdeOrders.getOrderSource(),"1")) {
				log.error("***************" + mdeOrders.getPkgTitle());
				log.error("***************" + StringEscapeUtils.unescapeHtml(mdeOrders.getPkgTitle()));

				String resultStr= PaymentApi.aliPayPage(
						mdeOrders.getOrderId(), 
						mdeOrders.getPayableMoney().toString(), 
						StringEscapeUtils.unescapeHtml(mdeOrders.getPkgTitle()),
						StringEscapeUtils.unescapeHtml(mdeOrders.getPkgTitle()),getAliPayConfig());
				response.setContentType("text/html;charset=" + alipay_charset);
				String str1 = resultStr.substring(0,resultStr.indexOf("action")-1);
//				String str_ = " target=\"_blank\" ";// 加上之后直接就页面跳转到新页面
				String str2 = resultStr.substring(resultStr.indexOf("action"));
//				result.put("AliPay", str1+str_+str2);
				result.put("AliPay", str1+str2);
				return result;
			} else {
				return result; // 微信端订单 (微信端的订单不能用支付宝支付)
			}
		}
		// 微信支付
		else if (StringsUtils.isEqual(mdeOrders.getPayType(), "1")) 
		{
			Map<String, String> reqMap = new HashMap<String, String>();
			
			// PC端订单
			if (StringsUtils.isEqual(mdeOrders.getOrderSource(),"1")) 
			{
				reqMap.put("trade_type", "NATIVE");// JSAPI--公众号支付、NATIVE--原生扫码支付、APP--app支付
				reqMap.put("spbill_create_ip", IpKit.getIpAddr(request));// 终端IP（APP和网页支付提交用户端ip，Native支付填调用微信支付API的机器IP）
				reqMap.put("product_id", mdeOrders.getPkgId());// 商品ID
			}
			// 微信端订单
			else if (StringsUtils.isEqual(mdeOrders.getOrderSource(),"2")) 
			{
				// 微信端支付需要用户code ; 如果code不存在抛出 code异常
				if(StringsUtils.isEmpty(mdeOrdersReq.getWxCode())) throw new CustomException(InfoMsg.ERROR_CODE_NECESSARY);
				String url = MessageUtils.getText(wxAuzTokenUrl, WXpay_appId, WXpay_appSecret, mdeOrdersReq.getWxCode());
				// 通过code 获取openId
				AuzAccesTokenDto auzAccesTokenDto = AuthorizedService.getRemoteResponseAsJson(url, AuzAccesTokenDto.class);
				reqMap.put("trade_type", "JSAPI");
				reqMap.put("spbill_create_ip", IpKit.getIpAddr(request));// 必须传正确的用户端IP
				reqMap.put("openid", auzAccesTokenDto.getOpenid());// 公众号支付，此参数必传
			}
			// pc/公众号 公共参数
			reqMap.put("appid", WXpay_appId);// 公众账号ID
			reqMap.put("mch_id", WXpay_mchId);// 商户号
			reqMap.put("nonce_str", System.currentTimeMillis() + ""+StringsUtils.getRandomString(10));// 随机字符串(32位以内)
			reqMap.put("body", mdeOrders.getPkgTitle()+mdeOrders.getSkuCn());// 商品描述
			reqMap.put("out_trade_no", mdeOrders.getOrderId()+Constants.UNDER_LINE+StringsUtils.getRandomString(5));// 系统中的唯一订单号
			
			BigDecimal decimal = mdeOrders.getPayableMoney();
			int fee =  decimal.multiply(new BigDecimal(100)).intValue();
			reqMap.put("total_fee",fee + "");// 金额需要扩大100倍:1代表支付时是0.01
			reqMap.put("notify_url", MessageUtils.getText(WXpay_notifyUrl,domainUrl));// 通知地址
			reqMap.put("sign",  PaymentKit.createSign(reqMap, WXpay_appKey));// 调用生成签名的方法，用以Map集合中的相关参数生成签名
			
			// 调用微信统一下单接口 获取结果(二维码链接等参数)
			Map<String, String> respMap = PaymentKit.xmlToMap(PaymentApi.pushOrder(reqMap));
			// 判断成功与否
			if (respMap.get("return_code").equalsIgnoreCase("SUCCESS") && 
					respMap.get("result_code").equalsIgnoreCase("SUCCESS")) {
				// PC端订单
				if (StringsUtils.isEqual(mdeOrders.getOrderSource(),"1")) 
				{
					// 设置二维码
					result.put("code_url", respMap.get("code_url"));// 链接(用来生成二维码)R
				} 
				// 微信端订单
				else if (StringsUtils.isEqual(mdeOrders.getOrderSource(),"2")) 
				{
					String orderId = result.get("orderId");
					result.remove("orderId");
					// 手机端调用wxjs工具完成支付
					result.put("appId", respMap.get("appid").trim());
					result.put("timeStamp", String.valueOf(System.currentTimeMillis() / 1000));// 生成签名的时候使用的
					result.put("nonceStr",  StringsUtils.getRandomString(16));//System.currentTimeMillis() + ""
					result.put("package", "prepay_id=" + respMap.get("prepay_id").trim());// 微信生成的预支付会话标识
					result.put("signType", "MD5");//respMap.get("sign");
					result.put("paySign", PaymentKit.createSign(result, WXpay_appKey));
					result.put("timestamp", result.get("timeStamp"));
					result.remove("appId");
					result.remove("timeStamp");
					result.put("orderId", orderId);
					
				}
			} else {
				log.error("***********微信支付发起异常："+respMap);
				return new HashMap<String, String>();
			}
		}
		return result;
	}
	
	
	private MdeOrders resolveTicket(MdeOrders mdeOrders,String lang) {
		mdeOrders.setDiscountMoney(0);
		mdeOrders.setPayableMoney(mdeOrders.getPrice());
		if(StringsUtils.isNotEmpty(mdeOrders.getTcCode()) && StringsUtils.isNotEmpty(mdeOrders.getTdCode())) {
			MdeTicketDetail detail = tdService.checkTdByCode(mdeOrders.getUserCode(),mdeOrders.getTcCode(),mdeOrders.getTdCode(),lang);
			if(detail !=null) {
				mdeOrders.setDiscountMoney(Integer.valueOf(detail.getMoney()));
				mdeOrders.setTdCode(detail.getTdCode());
				mdeOrders.setTcCode(detail.getTcCode());
				BigDecimal decimal = new BigDecimal(mdeOrders.getPrice()).subtract(new BigDecimal(detail.getMoney()));
				BigDecimal zore = new BigDecimal("0");
				if(decimal.compareTo(zore)<0) {
					decimal = zore; 
				}
				mdeOrders.setPayableMoney(decimal.toPlainString());
				mdeOrders.setInvMoney(decimal.toPlainString());
				// 更新抵用券的状态
				tdService.updateUsedFlag(detail.getTdId());
			}
		}
		return mdeOrders;
	}
	
	
	/**
	 * 初始化 服务订单信息
	 * @param request
	 * @param order
	 * @return
	 */
	public MdeOrders initOrderInfo(String userCode,String identityFlag, MdeOrdersReq mdeOrdersReq,MdeOrders order) {
		
		//将请求参数复制到订单中
		BeanUtils.copyProperties(mdeOrdersReq, order);
		
		// 设置订单数据
		if(StringsUtils.isEmpty(order.getOrderId()))
		{
			//生产订单号
			order.setOrderId(generateOrderID(identityFlag, null));
		}
		order.setUserCode(userCode);
		order.setOrdStatus("1");// 待支付
		order.setOrderTime(new Date());
		order.setDelFlag(0);
		order.setCreateBy(userCode);
		order.setUpdateBy(userCode);

		if (StringsUtils.isEqual(identityFlag, "1")) {
			order.setPayType("3");
		}
		
		
		//根据套餐id和售价id获取套餐基本信息以及用户选择的sku和售价
		MdeVipPackage vipPackage = mdeVipPackageService.getPkgInfoContainPrice(mdeOrdersReq.getPkgId(),mdeOrdersReq.getPriceId());
		if(vipPackage != null) {
			order.setPkgId(vipPackage.getPkgId()+"");
			order.setPkgTitle(vipPackage.getPkgTitle());
			order.setVipFlag(vipPackage.getVipFlag());
			order.setPkgIntroduction(vipPackage.getPkgIntroduction());
			order.setPkgDetail(vipPackage.getPkgDetail());
			order.setPkgTitleEn(vipPackage.getPkgTitleEn());
			order.setPkgIntroductionEn(vipPackage.getPkgIntroductionEn());
			order.setPkgDetailEn(vipPackage.getPkgDetailEn());
			if(vipPackage.getPkgDetails() != null && vipPackage.getPkgDetails().size()>0) {
				//售价相关内容
				VipPackagePriceDto pkgDetail = vipPackage.getPkgDetails().get(0);
				order.setPrice(String.valueOf(pkgDetail.getPrice()));
				order.setValidityPeriod(String.valueOf(pkgDetail.getValidityPeriod()));
				order.setSkuCn(pkgDetail.getSkuCn());
				order.setSkuEn(pkgDetail.getSkuEn());
			}
		}
		return order;
	}
	
	
	/**
	 * 初始化 商品订单
	 * 	基本信息
	 * @param userCode
	 * @param identityFlag
	 * @param gOrdReq
	 * @param order
	 * @param lang
	 * @return
	 */
	public MdeOrders initGoodsOrderBaseInfo(String userCode,String identityFlag, GoodsOrdersReq gOrdReq,MdeOrders order,String lang) {
		
		//将请求参数复制到订单中
		BeanUtils.copyProperties(gOrdReq, order);
		
		// 设置订单数据
		if(StringsUtils.isEmpty(order.getOrderId()))
		{
			//生成订单号
			order.setOrderId(generateOrderID(identityFlag,gOrdReq.getGoodsId()));
		}
		order.setUserCode(userCode);
		order.setOrdStatus("1");// 待支付
		order.setOrderTime(new Date());
		order.setDelFlag(0);
		order.setCreateBy(userCode);
		order.setUpdateBy(userCode);

		if (StringsUtils.isEqual(identityFlag, "1")) {
			//企业订单是线下汇款
			order.setPayType("3");
		}
		return order;
	}
	
	/**
	 * 初始化 商品订单
	 * 	商品信息
	 * @param lang
	 * @param order
	 * @return
	 */
	public MdeOrders makeGoodsInfo(MdeOrders order,MdeGoods goodsDetail,String lang) {
		if(goodsDetail != null) {
			//非vip
			order.setVipFlag("0");
			order.setGoodsId(goodsDetail.getGoodsId());
			order.setImg(goodsDetail.getImg());
			order.setPkgTitle(goodsDetail.getTitleCn());
			order.setPkgTitleEn(goodsDetail.getTitleEn());
			order.setSubheadCn(goodsDetail.getSubheadCn());
			order.setSubheadEn(goodsDetail.getSubheadEn());
			order.setPkgIntroduction(goodsDetail.getResumeCn());
			order.setPkgIntroductionEn(goodsDetail.getResumeEn());
			order.setPkgDetail(goodsDetail.getContent());
			order.setPkgDetailEn(goodsDetail.getContent());
			order.setType(goodsDetail.getType());

			//商品售价（单价）
			order.setPrice(goodsDetail.getSellPrice().toString());
			//总运费金额 统一10元
			BigDecimal freight =new BigDecimal(DefaultFreight);
			order.setPayableFreight(freight);
			order.setRealFreight(freight);
			//商品总价 = 单价*数量+运费
			order.setPayableMoney((goodsDetail.getSellPrice().multiply(new BigDecimal(order.getGoodsNums()))).add(freight));
			order.setSkuCn(goodsDetail.getUnitCn());
			order.setSkuEn(goodsDetail.getUnitEn());	
		} else {
			order = null;
		}

		return order;
	}
	
	/**
	 * 初始化 商品订单
	 * 	地址信息
	 * @param lang
	 * @param order
	 * @return
	 */
	public MdeOrders makeAddressInfo(MdeOrders order,int addid, String userCode) {
		if(order != null)
		{
			// 获取配送地址详情
			AddressesDto addDetail = addressDao.selectByAddid(addid, userCode);
			if(addDetail != null) {
				order.setAddrArea(addDetail.getAddrArea());
				order.setAddrProvince(addDetail.getAddrProvince());
				order.setAddrCity(addDetail.getAddrCity());
				order.setRecipientName(addDetail.getRecipientName());
				order.setRecipientTel(addDetail.getRecipientTel());
				order.setRecipientAdd(addDetail.getRecipientAdd());
				order.setPostcode(addDetail.getRecipientZip());
			}else {
				order = null;
			}
		}
		return order;
	}
	
	
	public String generateOrderID(String identityFlag, Integer goodsID) {
		String headFlag="";
		
		//商品订单和服务订单区分
		if(goodsID != null)
		{
			//商品订单
			headFlag = "G";
		}else {
			//服务订单
			if (StringsUtils.isEqual(identityFlag, "0")) {
				// 个人
				headFlag = "P";
			}else {
				// 企业
				headFlag = "E";
			}
		}
		return headFlag + DateUtils.dateToString("yyMMdd") + (System.currentTimeMillis()+"").substring(5)+
				StringsUtils.getRandomStringUppercase(5);
	}
	
	
	@Transactional
	public void makeBill(MdeOrders order) {
		if(order.getInvType().equals("1") || order.getInvType().equals("2")) {
			// 删除该用户的所有发票记录
			mdeInvoiceTitleService.deleteAllByUserCode(order.getUserCode());
			// 将开票信息存入数据库
			MdeInvoiceTitle invoice = new MdeInvoiceTitle();
			invoice.setUserCode(order.getUserCode());
			invoice.setInvTitle(order.getInvTitle());
			invoice.setTaxationNo(order.getTaxationNo());
			invoice.setLtdAdd(order.getLtdAdd());
			invoice.setLtdTel(order.getLtdTel());
			invoice.setOpeningBank(order.getOpeningBank());
			invoice.setAccountNumber(order.getAccountNumber());
			invoice.setInvContent(order.getInvContent());
			invoice.setInvMoney(order.getPayableMoney().toString());// 实际支付的价格
			invoice.setRecipientName(order.getRecipientName());
			invoice.setRecipientAdd(order.getRecipientAdd());
			invoice.setRecipientTel(order.getRecipientTel());
			invoice.setInvType(order.getInvType());
			invoice.setDelFlag(0);
			invoice.setVersionNo(1);
			invoice.setCreateBy(order.getUserCode()+"");
			invoice.setCreateDate(new Date());
			invoice.setUpdateBy(order.getUserCode()+"");
			invoice.setUpdateDate(new Date());
			mdeInvoiceTitleService.insert(invoice);
		}
	}
	
	/**
	 * 整理ali支付配置
	 * @return
	 */
	public Map<String,String> getAliPayConfig(){
		Map<String,String> map = new HashMap<String,String>();
		map.put("appId", alipay_appId);
		map.put("gatewayUrl",alipay_gatewayUrl);
		map.put("merchantPrivateKey", alipay_merchantPrivateKey);
		map.put("charset", alipay_charset);
		map.put("alipayPublicKey", alipay_publicKey);
		map.put("signType", alipay_signType);
		map.put("notifyUrl", MessageUtils.getText(alipay_notifyUrl,domainUrl));
		map.put("returnUrl", MessageUtils.getText(alipay_returnUrl,domainUrl));
		return map;
	}
	/**
	 * AliPay支付回调 weChatNotify
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@Transactional
	public void aliPayNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 获取支付宝POST过来反馈信息
		Map<String, String> params = new HashMap<String, String>();

		Map<String, String[]> requestParams = request.getParameterMap();
		for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = (String) iter.next();
			String[] values = (String[]) requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
			}
			// 乱码解决，这段代码在出现乱码时使用。
			// valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
			params.put(name, valueStr);
		}

		response.setContentType("text/html;charset=" + alipay_charset);

		// 切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
		boolean signVerified = AlipaySignature.rsaCheckV1(params, alipay_publicKey, alipay_charset, alipay_signType);
		// 验签成功
		if (signVerified) {
			// 商户订单号
			String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
			// 支付宝交易号
			String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
			// 付款金额
			String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");
			// 卖家账号
			String seller_id = new String(request.getParameter("seller_id").getBytes("ISO-8859-1"), "UTF-8");
			// appid
			String appid = new String(request.getParameter("app_id").getBytes("ISO-8859-1"), "UTF-8");
			
//			String seller_email = new String(request.getParameter("seller_email").getBytes("ISO-8859-1"), "UTF-8");
			// 交易状态
			String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
			// 订单支付时间
			String gmt_payment = new String(request.getParameter("gmt_payment").getBytes("ISO-8859-1"), "UTF-8");

			// 验证appid 和 验证卖家账号
			if (!StringsUtils.isEqual(appid, alipay_appId) || StringsUtils.isEmpty(seller_id)) {
				response.getWriter().write("fail");
			} else {
				// 查询订单
				MdeOrders order = ordersService.findOneByTradeCode(out_trade_no);
				String resp2Front = "";
				// 订单不存在
				if (order == null) {
					response.getWriter().write("fail");
					resp2Front = "Fail";
				} else if (trade_status.equals("TRADE_SUCCESS")) {
					// 判断价格是否正确
					if ((!StringsUtils.isEqual(order.getPayableMoney().toString(), total_amount))
							// 判断当前订单是否已处理，避免重复处理
							|| (!StringsUtils.isEqual(order.getOrdStatus(), "1"))) {
						response.getWriter().write("fail");
						resp2Front = "Fail";
					} else if(order.getOrdStatus().equals("2")) {
						resp2Front = "OK";
					} else {// 订单正确，修改订单状态
						order.setThirdPartyOrd(trade_no);
						order.setPayPrice(new BigDecimal(total_amount));
						order.setPayTime(DateUtils.stringToDate(gmt_payment, DateUtils.PATTEN_HMS));
						order.setOrdStatus("2");
						Date vipFinishDate = getFinisTime(order.getUserCode(),order.getValidityPeriod());
						order.setFinishTime(vipFinishDate);
						mdeOrdersDao.updatePaidOrder(order);
						//更新用户会员标识等
						MdeUser user= mdeUserService.getFullInfo(order.getUserCode());
						user.setVipFlag(order.getVipFlag());
						// Date date = DateUtils.addMonth(order.getPayTime(), Integer.parseInt(order.getValidityPeriod()));
						user.setDueDate(vipFinishDate);
						mdeUserService.update(user);
						// 返回通知
						response.getWriter().write("success");
						resp2Front = "OK";

						//发送系统通知邮件
						sendNoticeEmail(order);
					}
				}
				redisDao.insert("wechat_notify_return_"+out_trade_no, resp2Front,3600);
			}
			// 验签不通过
		} else {
			response.getWriter().write("fail");
		}
		response.getWriter().flush();
		response.getWriter().close();
	}

	private Date getFinisTime(String userCode, String validityPeriod) {
		Date date = new Date();
		// 购买期限为空 则返回当前时间
		if(StringsUtils.isEmpty(validityPeriod)) {
			return date;
		}
		MdeOrders order = ordersService.getValidOrdersByUserCode(userCode);
		Calendar calendar = Calendar.getInstance();
		if(order==null) {
			SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
			try {
				calendar.setTime(f.parse(f.format(date)));
			} catch (ParseException e) {
				e.printStackTrace();
			};
			// calendar.add(Calendar.DAY_OF_MONTH, 1);//把日期往后增加一个月.整数往后推,负数往前移动
		    calendar.add(Calendar.MONTH,Integer.parseInt(validityPeriod));//把日期往后增加N个月
		}else {
			if(order.getFinishTime().before(date)) {
				order.setFinishTime(date);
			}
			calendar.setTime(order.getFinishTime());
			calendar.add(Calendar.MONTH,Integer.parseInt(validityPeriod));//把日期往后增加N个月
		}
		return calendar.getTime();
	}

	/**
	 * 微信支付回回调
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@Transactional
	public String weChatNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 读取参数
		InputStream inputStream;
		StringBuffer sb = new StringBuffer();
		inputStream = request.getInputStream();
		String s;
		BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
		while ((s = in.readLine()) != null) {
			sb.append(s);
		}
		in.close();
		inputStream.close();

		// 解析xml成map
		Map<String, String> map = new HashMap<String, String>();
		map = PaymentKit.xmlToMap(sb.toString());

		// 过滤空 设置 Map
		Map<String, String> packageParams = new HashMap<String, String>();
		Iterator<String> it = map.keySet().iterator();
		while (it.hasNext()) {
			String parameter = (String) it.next();
			String parameterValue = map.get(parameter);
			String value = "";
			if (null != parameterValue) {
				value = parameterValue.trim();
			}
			packageParams.put(parameter, value);
		}

		// 返回給微信通知内容
		String resXml = "";//<?xml version=\"1.0\" encoding=\"UTF-8\"?>
		String resp2Front = "";
		
		// 判断签名是否正确
		// 回调中 签名验证的key 的值要与  支付时使用的 签名使用的key要一致  都使用 WXpay_appKey   
		if (PaymentKit.verifyNotify(packageParams, WXpay_appKey)) {

			// 验签成功
			if ("SUCCESS".equals((String) packageParams.get("result_code"))) {
				// 支付成功
				// 商户订单号 按下划线切割
				String out_trade_no = (String) packageParams.get("out_trade_no").split(Constants.UNDER_LINE)[0];
				// 支付金额
				String total_fee = (String) packageParams.get("total_fee");
				// 微信订单号
				String transaction_id = (String) packageParams.get("transaction_id");
				// 支付时间
				String time_end = (String) packageParams.get("time_end");

				// 查询订单
				MdeOrders order = ordersService.findOneByTradeCode(out_trade_no);
				// 订单不存在
				if (order == null) {
					resp2Front = "Fail";
					resXml += "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[订单不存在]]></return_msg></xml> ";
				} else if(order.getOrdStatus().equals("2")) {
					resp2Front = "OK";
					resXml += "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml> ";
				} else {
					// 订单存在 判断金额是否匹配
					BigDecimal decimal = order.getPayableMoney();
					int fee =  decimal.multiply(new BigDecimal(100)).intValue();
					if (StringsUtils.isEqual(total_fee, fee+"")) {
						// 更新订单
						order.setThirdPartyOrd(transaction_id);
						order.setPayPrice(order.getPayableMoney());
						order.setPayTime(DateUtils.stringToDate(time_end, DateUtils.PATTEN_YMD_HH_MM_SS_SEPRATE));
						order.setOrdStatus("2");
						Date vipFinishDate = getFinisTime(order.getUserCode(),order.getValidityPeriod());
						order.setFinishTime(vipFinishDate);
						mdeOrdersDao.updatePaidOrder(order);
						//更新用户会员标识等
						MdeUser user= mdeUserService.getFullInfo(order.getUserCode());
						user.setVipFlag(order.getVipFlag());
						user.setDueDate(vipFinishDate);
						mdeUserService.update(user);
						// 通知微信.异步确认成功.必写.不然会一直通知后台.八次之后就认为交易失败了.
						resXml += "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml> ";
						resp2Front = "OK";
						
						//发送系统通知邮件
						sendNoticeEmail(order);
					} else {
						// 支付数据不匹配
						resXml += "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[金额不对]]></return_msg></xml> ";
						resp2Front = "Fail";
					}
				}
				redisDao.insert("wechat_notify_return_"+out_trade_no, resp2Front,3600);
			} 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> ";
		}
//		System.out.println(resXml);
//		return res;
//		return "success";
//		BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
//		out.write(xmlStr2xml(resXml).getBytes());
//		out.flush();
//		out.close();
		
		return resXml;// 直接返回字符串即可, 输入到输出流中返回微信不认
	}
	
	/**
	 * 新订单邮件通知
	 * 
	 * @param map
	 * @param req
	 * @param rep
	 * @throws AlipayApiException
	 */
	private void sendNoticeEmail(MdeOrders order) {
		//获取下单用户信息
		MdeUser userInfo = commonService.getUserInfo(order.getUserCode());
		//发送系统通知邮件
		String emailContent = "有新的订单请注意</br>";
		emailContent = emailContent + "</br>订单编号： " + order.getOrderId();
		emailContent = emailContent + "</br>用户姓名： " + userInfo.getName();
		emailContent = emailContent + "</br>联系方式： " + userInfo.getUserName();
		emailContent = emailContent + "</br>购买套餐： " + order.getPkgTitle();
		emailContent = emailContent + "</br>购买期限： " + order.getValidityPeriod();
		emailContent = emailContent + "</br>支付金额： " + order.getPayPrice();
		emailContent = emailContent + "</br>下单时间： " + DateUtils.dateToString(order.getOrderTime(),DateUtils.PATTEN_HMS);
		commonService.sendNoticeEmail(emailContent, commonService.getNoticeEmailAdds(),"新用户订单");
	}
	
	/**
	 * 退款
	 * 
	 * @param map
	 * @param req
	 * @param rep
	 * @throws AlipayApiException
	 */
//	public ResultEntity<String> refund(Map<String, Object> map, HttpServletRequest req, HttpServletResponse rep)
//			throws AlipayApiException {
//		// 商戶订单号
//		String out_trade_no = map.get("out_trade_no").toString();
//		// 查询订单
//		MdeOrders mdeOrders = ordersService.findOneByTradeCode(out_trade_no);
//		// 判断订单是否存在 /处理状态
//		if (mdeOrders == null || (!mdeOrders.getOrdStatus().equals("2"))) {
//			return new ResultEntity<>(InfoMsg.SUCCESS_REQUEST);
//		}
//		// 支付宝退款
//		if (mdeOrders.getPayType().equals("1")) {
//			// 支付宝定单号
//			String trade_no = map.get("trade_no").toString();
//			// 退款金额
//			String refund_amount = map.get("refund_amount").toString();
//			// 退款理由
//			String refund_reason = map.get("refund_reason").toString();
//			// 调用退款接口/获取结果
//			AlipayTradeRefundResponse response = PaymentApi.aliPayRefund(trade_no, refund_amount, refund_reason,getAliPayConfig());
//			// 判断状态
//			if (response.isSuccess() && response.getMsg().equals("Success") && response.getFundChange().equals("Y")) {
//				// 退款成功 更新订单状态
//				mdeOrders.setRefundNo(response.getRefundFee());
//				mdeOrders.setOrdStatus("4");
//				ordersService.update(mdeOrders);
//				return new ResultEntity<>(InfoMsg.SUCCESS_REQUEST);
//			} else {
//				// 退款失败
//				return new ResultEntity<>();
//			}
//
//			// 调用微信退款接口
//		} else if (mdeOrders.getPayType().equals("2")) {
//			// String type = map.get("type").toString();
//			Map<String, String> params = new HashMap<String, String>();
//
//			// if (StringsUtils.isEqual(type, "PC")) {
//			// // PC
//			// params.put("sub_mch_id", "");
//			// }
//			// 下面是pc/h5公共参数
//			params.put("mch_id", "");
//			params.put("transaction_id", mdeOrders.getThirdPartyOrd());
//			// 商户退款单号(商户内部唯一)
//			params.put("out_refund_no", mdeOrders.getOrderId());
//			// 支付金额
//			params.put("total_fee", (Integer.parseInt(mdeOrders.getPrice())*100)+"");
//			// 退款金额
//			params.put("refund_fee", (Integer.parseInt(mdeOrders.getPayPrice())*100)+"");
//			// 退款原因(可不填)
//			params.put("refund_desc", "");
//			// 回调地址
//			// params.put("notify_url", "");
//			// 调用退款接口获取结果
//			Map<String, String> respMap = PaymentApi.refund(params, "paternerKey", "certPath");
//			// 判断退款状态
//			if (StringsUtils.isEqual(respMap.get("return_code"), "SUCCESS")
//					&& StringsUtils.isEqual(respMap.get("result_code"), "SUCCESS")) {
//				// 更新数据
//				mdeOrders.setRefundNo(respMap.get("refund_fee"));
//				mdeOrders.setOrdStatus("4");
//				ordersService.update(mdeOrders);
//				return new ResultEntity<>(InfoMsg.ERROR_AUZ_FAILED);
//			}
//			return new ResultEntity<>(InfoMsg.ERROR_AUZ_FAILED);
//		}
//		return new ResultEntity<>(InfoMsg.ERROR_AUZ_FAILED);
//	}

	/**
	 * 订单查询
	 * 
	 * @param map
	 * @param req
	 * @param rep
	 * @throws AlipayApiException
	 */
	public ResultEntity<Map<String, String>> queryOrder(Map<String, Object> map, HttpServletRequest req,
			HttpServletResponse rep) throws AlipayApiException {

		// 商戶订单号
		String out_trade_no = map.get("out_trade_no").toString();
		// 查询订单
		MdeOrders mdeOrders = ordersService.findOneByTradeCode(out_trade_no);
		// 判断订单是否存在 /处理状态
		if (mdeOrders == null) {
			return new ResultEntity<>(InfoMsg.SUCCESS_REQUEST);
		}
		// 支付宝订单查询
		if (mdeOrders.getPayType().equals("1")) {

			AlipayTradeQueryResponse response = PaymentApi.aliPayQuery(mdeOrders.getThirdPartyOrd(),getAliPayConfig());

			if (response.isSuccess() && response.getMsg().equals("Success")) {
				return new ResultEntity<Map<String, String>>(InfoMsg.SUCCESS_REQUEST, response.getParams());
			}

			// 微信订单查询
		} else if (mdeOrders.getPayType().equals("2")) {
			Map<String, String> mapa = PaymentApi.queryByTransactionId("appid", "mch_id", "paternerKey",
					mdeOrders.getThirdPartyOrd());
			return new ResultEntity<Map<String, String>>(InfoMsg.SUCCESS_REQUEST, mapa);
		}
		return new ResultEntity<>(InfoMsg.SUCCESS_REQUEST);
	}

	/**
	 * 退款查询
	 * 
	 * @param map
	 * @param req
	 * @param rep
	 * @throws AlipayApiException
	 */
	public ResultEntity<Map<String, String>> queryRefund(Map<String, Object> map, HttpServletRequest req,
			HttpServletResponse rep) throws AlipayApiException {
		AlipayClient alipayClient = new DefaultAlipayClient(alipay_gatewayUrl, alipay_appId, alipay_merchantPrivateKey, "json", alipay_charset,
				alipay_publicKey, alipay_signType);
		AlipayTradeFastpayRefundQueryRequest request = new AlipayTradeFastpayRefundQueryRequest();

		String out_trade_no = map.get("").toString();
		String trade_no = map.get("").toString();
		String out_request_no = map.get("").toString();
		request.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\"," + "\"trade_no\":\"" + trade_no + "\","
				+ "\"out_request_no\":\"" + out_request_no + "\"" + "}");
		AlipayTradeFastpayRefundQueryResponse response = alipayClient.execute(request);
		if (response.isSuccess() && response.getMsg().equals("Success")) {
			return new ResultEntity<Map<String, String>>(InfoMsg.SUCCESS_REQUEST, response.getParams());
		} else {
			return new ResultEntity<Map<String, String>>(InfoMsg.SUCCESS_REQUEST);
		}
	}

	/**
	 * 取消订单
	 * 
	 * @param map
	 * @param req
	 * @param rep
	 * @throws AlipayApiException
	 */
	public ResultEntity<Map<String, String>> closeOrder(Map<String, Object> map, HttpServletRequest req,
			HttpServletResponse rep) throws AlipayApiException {
		// 商戶订单号
		String out_trade_no = map.get("out_trade_no").toString();
		// 查询订单
		MdeOrders mdeOrders = ordersService.findOneByTradeCode(out_trade_no);
		// 判断订单是否存在 /处理状态
		if (mdeOrders == null || (!mdeOrders.getOrdStatus().equals("1"))) {
			return new ResultEntity<>(InfoMsg.SUCCESS_REQUEST);
		}
		// 支付宝订单查询
		if (mdeOrders.getPayType().equals("1")) {

			AlipayTradeCloseResponse response = PaymentApi.aliPayClose(out_trade_no,getAliPayConfig());
			if (response.isSuccess() && response.getMsg().equals("Success")) {
				return new ResultEntity<Map<String, String>>(InfoMsg.SUCCESS_REQUEST, response.getParams());
			}
			// 微信订单查询
		} else if (mdeOrders.getPayType().equals("2")) {
			Map<String, String> mapa = PaymentApi.closeOrder("appid", "mch_id", "paternerKey", mdeOrders.getOrderId());
			return new ResultEntity<Map<String, String>>(InfoMsg.SUCCESS_REQUEST, mapa);
		}
		return new ResultEntity<>(InfoMsg.SUCCESS_REQUEST);
	}
	
	/**
	 * 用户删除订单
	 * @param OrderId
	 */
	@Transactional
	public int deleteOrderByUser(String OrderId, String userCode) {
		MdeOrders order = mdeOrdersDao.getOrderInfoByCode(OrderId,userCode);
		int num = 0;
		//是当前用户自有订单，并且是待支付状态
		if("1".equals(order.getOrdStatus()))
		{
			// 还原抵用券的状态为可用
			if(!StringsUtils.isEmpty(order.getTdCode()))
			{
				ticketDetailDao.restartTicket(order.getTdCode());
			}
			//删除订单
			num = mdeOrdersDao.deleteOrderByUser(OrderId,userCode);
			
			//删除成功并且是商品订单（才有库存）的情况下
			if(num > 0 && order.getGoodsId() != null)
    		{
				//释放库存
    			String saleStr = goodsRedisDao.selectSaleNum(order.getGoodsId());
    			if(!StringsUtils.isEmpty(saleStr))
    			{
    				//缓存不为空的情况下 重新设置销量
    				int saleNum = Integer.valueOf(saleStr) - order.getGoodsNums();
    				goodsRedisDao.insertSaleNum(order.getGoodsId(),saleNum);
    			}
    		}
		} 
		return num;
	}
	
	/**
	 * 检查支付状态
	 * @param request
	 * @return
	 */
	public String checkPayStatus(String orderId, String userCode) {
		String orderResult = redisDao.select("wechat_notify_return_"+orderId);
		if(StringsUtils.isEmpty(orderResult)){
			MdeOrders order = mdeOrdersDao.getOrderInfoByCode(orderId,userCode);
			if(order  != null && order.getOrdStatus().equals("2")) {
				orderResult =  "ok";
			}
		}
		return orderResult;
	}
	
	/**
	 * 获取服务订单详情
	 * @param request
	 * @param lang 
	 * @return
	 */
	public Map<String, Object> getOrderDetail(String orderId, String lang, String userCode, String identityFlag, String type) {
		Map<String, Object> map = new HashMap<String, Object>();
		//获取订单信息
		MdeOrders orderInfo = mdeOrdersDao.getOrderInfoByCode(orderId, userCode);
		OrderDetailDto ordDetail = new OrderDetailDto();
		//将订单信息复制到返回集中
		BeanUtils.copyProperties(orderInfo, ordDetail);
		// 订单信息
		map.put("orderInfo", ordDetail);
		
		if(StringsUtils.isEqual(type, Constants.ORDER_TYPE_VIP))
		{
			// 套餐订单的情况下 获取套餐内容
			map.put("vipPackage", mdeVipPackageService.getPkgInfoById(Integer.valueOf(orderInfo.getPkgId()), lang));
		}

		// 开票信息
		map.putAll(initInvoiceInfo(lang, identityFlag));
		
		map.put("ticketDetail", ticketDetailDao.getValidTicketByUser(userCode,identityFlag,lang));
		
		return map;
	}

	
	/**
	 * 保存商品订单并调用第三方支付接口
	 * 
	 * @param mdeOrders
	 * @param request
	 * @param response
	 * @return
	 * @throws AlipayApiException
	 * @throws IOException
	 */
	@Transactional
	public MdeOrders confirmGoodsOrder(GoodsOrdersReq gOrdReq, MdeGoods goodsDetail, String userCode, String identityFlag, String lang) 
	{
		MdeOrders mdeOrders = new MdeOrders();
		String oldTdCode = "";

		if(!StringsUtils.isEmpty(gOrdReq.getOrderId()))
		{	//更新订单的情况下(仅能更新配送信息和发票信息,买家留言)
			mdeOrders = mdeOrdersDao.getNoPayOrder(gOrdReq.getOrderId(),userCode);
			//发票内容
			mdeOrders.setInvType(gOrdReq.getInvType());
			mdeOrders.setInvTitle(gOrdReq.getInvTitle());
			mdeOrders.setTaxationNo(gOrdReq.getTaxationNo());
			mdeOrders.setLtdAdd(gOrdReq.getLtdAdd());
			mdeOrders.setLtdTel(gOrdReq.getLtdTel());
			mdeOrders.setOpeningBank(gOrdReq.getOpeningBank());
			mdeOrders.setAccountNumber(gOrdReq.getAccountNumber());
			//抵用券
			oldTdCode = mdeOrders.getTdCode();
			//买家留言
			mdeOrders.setPostscript(gOrdReq.getPostscript());
		} else {
			// 初始化订单基本信息
			mdeOrders = initGoodsOrderBaseInfo(userCode, identityFlag, gOrdReq,mdeOrders,lang);
			// 订单商品信息
			mdeOrders = makeGoodsInfo(mdeOrders,goodsDetail,lang);
		}
		
		// 订单地址信息
		if(Constants.ORDER_TYPE_GOODS.equals(goodsDetail.getType())) 
		{
			//实物商品购买时才需要填写地址信息
			mdeOrders = makeAddressInfo(mdeOrders,gOrdReq.getAddId(),userCode);
		}
		
		if(mdeOrders != null)
		{
			// 抵用券处理 当原订单的优惠券详情id为空 或者 有修改时才进行数据处理
			if(StringsUtils.isEmpty(oldTdCode) || !oldTdCode.equals(mdeOrders.getTdCode()))
			{
				mdeOrders = resolveTicket(mdeOrders,lang);
			}
			
			// 创建订单
			int count = 0;
			if(StringsUtils.isEmpty(gOrdReq.getOrderId()))
			{
				count = mdeOrdersDao.insertNewOrder(mdeOrders);
			}else {
				//更新订单
				count = mdeOrdersDao.updateById(mdeOrders);
			}
			
			if(count <1)
			{
				mdeOrders =  null;
			}
		}

		return mdeOrders;

	}
	
	
	/**
	 * 保存商品订单并调用第三方支付接口
	 * 
	 * @param mdeOrders
	 * @param request
	 * @param response
	 * @return
	 * @throws AlipayApiException
	 * @throws IOException
	 */
	@Transactional
	public Map<String, String> confirmOrderPay(MdeOrders mdeOrders, String wxCode, HttpServletRequest request, HttpServletResponse response) throws AlipayApiException, IOException 
	{
		Map<String, String> result = new HashMap<String, String>();
		// 线下支付
		if(StringsUtils.isEqual(mdeOrders.getPayType(), "3")) {
			result.put("accountName", accountName);
			result.put("openingBank", openingBank);
			result.put("account", account);
			result.put("deadlinePayment", Deadline_payment);
		} 
		// 个人--支付宝/微信  调用第三方支付接口
		// 支付宝支付(生成支付页面)
		else if (StringsUtils.isEqual(mdeOrders.getPayType(), "2")) 
		{
			// PC端订单
			if (StringsUtils.isEqual(mdeOrders.getOrderSource(),"1")) {
				String resultStr= PaymentApi.aliPayPage(
						mdeOrders.getOrderId(), 
						(mdeOrders.getPayableMoney().add(mdeOrders.getRealFreight())).toString(), 
						StringEscapeUtils.unescapeHtml(mdeOrders.getPkgTitle()),
						StringEscapeUtils.unescapeHtml(mdeOrders.getPkgTitle()),getAliPayConfig());
				response.setContentType("text/html;charset=" + alipay_charset);

				String str1 = resultStr.substring(0,resultStr.indexOf("action")-1);
//				String str_ = " target=\"_blank\" ";// 加上之后直接就页面跳转到新页面
				String str2 = resultStr.substring(resultStr.indexOf("action"));
//				result.put("AliPay", str1+str_+str2);
				result.put("AliPay", str1+str2);
			}
		}
		// 微信支付
		else if (StringsUtils.isEqual(mdeOrders.getPayType(), "1")) 
		{
			Map<String, String> reqMap = new HashMap<String, String>();
			
			// PC端订单
			if (StringsUtils.isEqual(mdeOrders.getOrderSource(),"1")) 
			{
				reqMap.put("trade_type", "NATIVE");// JSAPI--公众号支付、NATIVE--原生扫码支付、APP--app支付
				reqMap.put("spbill_create_ip", IpKit.getIpAddr(request));// 终端IP（APP和网页支付提交用户端ip，Native支付填调用微信支付API的机器IP）
				reqMap.put("product_id", mdeOrders.getOrderId());// 商品ID
			}
			// 微信端订单
			else if (StringsUtils.isEqual(mdeOrders.getOrderSource(),"2")) 
			{
				// 微信端支付需要用户code ; 如果code不存在抛出 code异常
				if(StringsUtils.isEmpty(wxCode)) throw new CustomException(InfoMsg.ERROR_CODE_NECESSARY);
				String url = MessageUtils.getText(wxAuzTokenUrl, WXpay_appId, WXpay_appSecret, wxCode);
				// 通过code 获取openId
				AuzAccesTokenDto auzAccesTokenDto = AuthorizedService.getRemoteResponseAsJson(url, AuzAccesTokenDto.class);
				reqMap.put("trade_type", "JSAPI");
				reqMap.put("spbill_create_ip", IpKit.getIpAddr(request));// 必须传正确的用户端IP
				reqMap.put("openid", auzAccesTokenDto.getOpenid());// 公众号支付，此参数必传
			}
			// pc/公众号 公共参数
			reqMap.put("appid", WXpay_appId);// 公众账号ID
			reqMap.put("mch_id", WXpay_mchId);// 商户号
			reqMap.put("nonce_str", System.currentTimeMillis() + ""+StringsUtils.getRandomString(10));// 随机字符串(32位以内)
			reqMap.put("body", mdeOrders.getPkgTitle()+mdeOrders.getSkuCn());// 商品描述
			reqMap.put("out_trade_no", mdeOrders.getOrderId()+Constants.UNDER_LINE+StringsUtils.getRandomString(5));// 系统中的唯一订单号
			
			BigDecimal decimal = mdeOrders.getPayableMoney().add(mdeOrders.getRealFreight());
			int fee =  decimal.multiply(new BigDecimal(100)).intValue();
			reqMap.put("total_fee",fee + "");// 金额需要扩大100倍:1代表支付时是0.01
			reqMap.put("notify_url", MessageUtils.getText(WXpay_notifyUrl,domainUrl));// 通知地址
			reqMap.put("sign",  PaymentKit.createSign(reqMap, WXpay_appKey));// 调用生成签名的方法，用以Map集合中的相关参数生成签名
			
			// 调用微信统一下单接口 获取结果(二维码链接等参数)
			Map<String, String> respMap = PaymentKit.xmlToMap(PaymentApi.pushOrder(reqMap));
			// 判断成功与否
			if (respMap.get("return_code").equalsIgnoreCase("SUCCESS") && 
					respMap.get("result_code").equalsIgnoreCase("SUCCESS")) {
				// PC端订单
				if (StringsUtils.isEqual(mdeOrders.getOrderSource(),"1")) 
				{
					// 设置二维码
					result.put("code_url", respMap.get("code_url"));// 链接(用来生成二维码)R
				} 
				// 微信端订单
				else if (StringsUtils.isEqual(mdeOrders.getOrderSource(),"2")) 
				{
					String orderId = result.get("orderId");
					result.remove("orderId");
					// 手机端调用wxjs工具完成支付
					result.put("appId", respMap.get("appid").trim());
					result.put("timeStamp", String.valueOf(System.currentTimeMillis() / 1000));// 生成签名的时候使用的
					result.put("nonceStr",  StringsUtils.getRandomString(16));//System.currentTimeMillis() + ""
					result.put("package", "prepay_id=" + respMap.get("prepay_id").trim());// 微信生成的预支付会话标识
					result.put("signType", "MD5");//respMap.get("sign");
					result.put("paySign", PaymentKit.createSign(result, WXpay_appKey));
					result.put("timestamp", result.get("timeStamp"));
					result.remove("appId");
					result.remove("timeStamp");
					result.put("orderId", orderId);
					
				}
			} else {
				log.error("***********微信支付发起异常："+respMap);
				result = new HashMap<String, String>();
			}
		}
		return result;
	}
	
	/**
	 * 购买商品资格认证
	 * @param goodsDetail
	 * @param userCode
	 * @param userCreatDate 注册时间
	 * @param gNums  购买数量
	 * @return
	 */
	public ResultEntity<Boolean> checkQualification(MdeGoods goodsDetail, String userCode, Date userCreatDate, GoodsOrdersReq ordReq) {
		ResultEntity<Boolean> rest = new ResultEntity<Boolean>();
		boolean checkRseult = true;
		InfoMsg msg = InfoMsg.SUCCESS_REQUEST;

		if(DateUtils.dateCompare(new Date(), goodsDetail.getUpTime()))
		{
			//当前时间 < 商品上架时间
			checkRseult = false;
			msg=InfoMsg.ERROR_GOODS_UP;
		}
		if(checkRseult && "9".equals(goodsDetail.getOnSale()))
		{
			//商品下架了
			checkRseult = false;
			msg=InfoMsg.ERROR_GOODS_DOWN;
		}else {
			//限制条件 注册日期(此日期之前注册 包含此日期)
		    Date conditionDate = goodsDetail.getConditionDate(); 
		    //限制条件 购买次数（0-不限 0以上为限制次数）
		    Integer conditionTime = goodsDetail.getConditionTime();
		    
		    //获取商品的销量
		    Integer goodsSale = mdeGoodsService.getGoodsSale(goodsDetail.getGoodsId());
		    
		    //新下订单才进行check
		    if(StringsUtils.isEmpty(ordReq.getOrderId()))
		    {
		    	//剩余库存足够的情况下（总库存 - 销量 < 用户的购买量）
				if((goodsDetail.getStoreNums()-goodsSale)< ordReq.getGoodsNums())
				{
					//库存不足
					checkRseult = false;
					msg=InfoMsg.ERROR_NOT_ENOUGH;
				}
				//注册日期check
			    if(checkRseult && conditionDate != null)
			    {
					if(DateUtils.dateCompare(conditionDate, userCreatDate))
					{
						//限制条件 注册日期 < 用户实际注册时间
						checkRseult = false;
						msg=InfoMsg.ERROR_CONDITION_DATE;
						msg.setMsg(MessageUtils.getText(msg.getMsg(), DateUtils.dateToString(conditionDate, DateUtils.PATTEN_YMD)));
					}
			    }
				
			    //购买次数check
				if(checkRseult && conditionTime > 0)
				{
					//获取用户购买该商品次数
					int count = mdeOrdersDao.getBuyTimesOfGoods(goodsDetail.getGoodsId(), userCode);
					if(count >= conditionTime)
					{
						//用户实际购买次数 >= 限制条件(购买次数)
						checkRseult = false;
						msg=InfoMsg.ERROR_CONDITION_TIME;
						msg.setMsg(MessageUtils.getText(msg.getMsg(), conditionTime.toString()));
					}
				}	
		    }
		}

		rest.setMsg(msg);
		rest.setResult(checkRseult);
		return rest;
	}

	
}