package com.letousky.lottery.action;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

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

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.anylotto.client.MD5Util;
import com.letousky.exception.LotteryException;
import com.letousky.lottery.alipayUtil.CheckURL;
import com.letousky.lottery.alipayUtil.Payment;
import com.letousky.lottery.alipayUtil.SignatureHelper;
import com.letousky.lottery.delegate.QueryLotDelegate;
import com.letousky.lottery.delegate.TradeDelegate;
import com.letousky.lottery.util.HelpRandom;
import com.letousky.lottery.util.StandFormat;
import com.letousky.lottery.util.TimeUtil;

/**
 * 交易清单
 * 
 * @author xuliang
 * 
 */
public class TradeAction extends BaseAction {

	TradeDelegate del = new TradeDelegate();
	private static final String EX="EX";

	/**
	 * 查询充值记录
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward findPrePaid(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		try {
			__logger.debug("开始!");
			// System.out.println("-----------------充值记录查询1-------------");
			String[] params = super.initParamtersUP(new String[] { "st1",
					"st2", "type", "page", "pageCount" }, request, "xuliang");
			params[2] = params[2] + " 00:00:01";
			params[3] = params[3] + " 23:59:59";
			params[2] = TimeUtil.getStringToDate(params[2]) + "";
			params[3] = TimeUtil.getStringToDate(params[3]) + "";
			params[params.length - 1] = "5";// pagecount
			params[4] = "2";// 充值写死类型1
			// System.out.println("-----------------充值记录查询2-------------");
			String s = "st1=" + request.getParameter("st1") + "&st2="
					+ request.getParameter("st2");
			for (int i = 0; i < params.length; i++) {
				// System.out.println("充值记录查询参数="+i+"="+params[i]);
			}
			int total = new QueryLotDelegate().getNoteNum(params, "N0019");
			// System.out.println("total="+total);
			setReqAtt(s, Integer.valueOf(request.getParameter("page")), 5,
					total, request);
			List list = new QueryLotDelegate().queryPre(params, "N0018");
			Object obj[] = list.toArray();
			String str[] = null;
			String results[][] = new String[obj.length][];
			for (int i = 0; i < obj.length; i++) {
				str = (String[]) obj[i];
				results[i] = new String[] { str[0], str[1],
						StandFormat.prePaidType.get(str[2]),
						TimeUtil.formatStr(str[3]),
						StandFormat.applyType.get(str[4]) };
			}
			request.setAttribute("rel", results);
			__logger.debug("结束!");
			if (request.getParameter("split") != null) {
				return mapping.findForward("prePaidTem");
			} else {
				return mapping.findForward("prePaid");
			}
		} catch (LotteryException le) {
			System.out.println(le.getErrNo() + " " + le.getErrMsg());
			return mapping.findForward(null);
		} catch (Exception e) {
			e.printStackTrace();
			return mapping.findForward(null);
		}
	}

	/**
	 * 充值申请
	 * 
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward prePaidApply(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		try {
			__logger.debug("开始!");
			String[] params = this.initParamtersUP(new String[] {"prePaidmoney", "patType" }, request, "xuliang");
			// for (int i = 0; i < params.length; i++) {
			// System.out.println("账户充值参数网站="+i+"="+params[i]);
			// }
			String[] st = new QueryLotDelegate().handleDelegateAry(params,
					"C0003");
			request.setAttribute("rel", st);
			__logger.debug("结束!");
			super.setReqAttForward(null, mapping.findForward("prePaidApply")
					.getPath(), new String[] {
					"realName," + st[0],
					"accountMoney," + st[2],
					"tradeNum," + st[1],
					"applyMoney,"
							+ HelpRandom.formatNumByBigDecimal(request
									.getParameter("prePaidmoney")),
					"patType," + request.getParameter("patType") }, request);
			return mapping.findForward("alertForward1");
		} catch (LotteryException le) {
			System.out.println(le.getErrNo() + " " + le.getErrMsg());
			request.setAttribute("msg", le.getErrMsg());
			return mapping.findForward("LotteryEx");
		} catch (Exception e) {
			e.printStackTrace();
			return mapping.findForward("Ex");
		}
	}


	
	/**
	 * 充值申请(新购彩大厅跳转)
	 * 
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward prePaidApplyNew(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		try {
			__logger.debug("开始!");
			String paytype=request.getParameter("payType");
			if(paytype==null){
				
				paytype="patType";
				
			}else{
				
				paytype="payType";
			}
			
			String params[] = new String[]{super.getUserName(request),super.getPassword(request),request.getParameter("czMoney"),paytype};
			
			String[] st = new QueryLotDelegate().handleDelegateAry(params,"C0003");
			
			request.setAttribute("rel", st);
			__logger.debug("结束!");
			super.setReqAttForward(null, mapping.findForward("prePaidApplynew")
					.getPath(), new String[] {
					"realName," + st[0],
					"accountMoney," + st[2],
					"tradeNum," + st[1],
					"applyMoney,"
							+ HelpRandom.formatNumByBigDecimal(request
									.getParameter("czMoney")),
					paytype+"," + request.getParameter(paytype) }, request);
			return mapping.findForward("alertForward1");
		} catch (LotteryException le) {
			System.out.println(le.getErrNo() + " " + le.getErrMsg());
			request.setAttribute("msg", le.getErrMsg());
			return mapping.findForward("LotteryEx");
		} catch (Exception e) {
			e.printStackTrace();
			return mapping.findForward("Ex");
		}
	}
	
	/**
	 * 梁 合作
	 * 
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward  RechargePrePaidApplyNew(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		try {
			__logger.debug("开始!");
			String paytype=request.getParameter("payType");
			if(paytype==null){
				paytype="patType";
				
			}else{
				paytype="payType";
			}
			String params[] = new String[]{super.getUserName(request),super.getPassword(request),request.getParameter("czMoney"),paytype};
			
			String[] st = new QueryLotDelegate().handleDelegateAry(params,"C0003");
			
			request.setAttribute("rel", st);
			__logger.debug("结束!");
			super.setReqAttForward(null, mapping.findForward("prePaidApplynew1")
					.getPath(), new String[] {
					"realName," + st[0],
					"accountMoney," + st[2],
					"tradeNum," + st[1],
					"applyMoney,"
							+ HelpRandom.formatNumByBigDecimal(request
									.getParameter("czMoney")),
					paytype+"," + request.getParameter(paytype) }, request);
			return mapping.findForward("alertForward2");
		} catch (LotteryException le) {
			System.out.println(le.getErrNo() + " " + le.getErrMsg());
			request.setAttribute("msg", le.getErrMsg());
			return mapping.findForward("LotteryEx");
		} catch (Exception e) {
			e.printStackTrace();
			return mapping.findForward("Ex");
		}
	}
	
	/**
	 * 充值申请提交到支付宝
	 * 
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward alipayCom(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		try {
			__logger.debug("开始!");
			String whichAlipayWay = request.getParameter("patType");
			String paytype = request.getParameter("payType");
			String[] params = null;
			if (!paytype.equals("") || paytype!=null){
				
				String paygateway = getResources(request).getMessage(
						"Letousky.Alipay.paygateway");// '支付接口
				String service = getResources(request).getMessage(
						"Letousky.Alipay.service");// 快速付款交易服务
				String partner = getResources(request).getMessage(
						"Letousky.Alipay.partner"); // 支付宝合作伙伴id (账户内提取)
				
				String out_trade_no = request.getParameter("tradeId"); // 商户网站订单
				String sign_type = getResources(request).getMessage(
						"Letousky.Alipay.sign_type");// 加密类型
				String subject = "彩票充值"; // 商品名称
				String total_fee = request.getParameter("tradeMoney"); // 订单总价
				String body = subject + "(" + "订单编号: " + out_trade_no
						+ ",充值金额: " + total_fee + ")"; // 商品描述，推荐格式：商品名称（订单编号：订单编号）
				String input_charset = "UTF-8";
				String payment_type = getResources(request).getMessage(
						"Letousky.Alipay.payment_type");// 支付宝类型.1代表商品购买
				String seller_email = getResources(request).getMessage(
						"Letousky.Alipay.seller_email");// 卖家支付宝帐户
			
				String defaultbank = paytype;// 默认选择工商银行
				if("zhifubao".equals(defaultbank)){
					defaultbank="";
				}
				String key = getResources(request).getMessage(
						"Letousky.Alipay.key"); // 支付宝安全校验码(账户内提取)
				String show_url = getResources(request).getMessage(
						"Letousky.Alipay.show_url");
				// 测试用我本机发布外网url，上线用服务器路径request.getContextPath()
				String notify_url = /* "http://letousky.vicp.net:8080/mw" */getResources(
						request).getMessage("Letousky.Alipay.notify_url")
						+ request.getContextPath()
						+ "/TradeAction.do?action=alipayNotify";// 通知接收URL(本地测试时，服务器返回无法测试)
				
				String paymethod="bankPay";
				
				
				String itemUrl = Payment.CreateUrl(paygateway, service,
						sign_type, out_trade_no, input_charset, partner, key,
						show_url, body, total_fee, payment_type, seller_email,
						subject, notify_url, paymethod,defaultbank);
				
		
				params = new String[] { body, notify_url, out_trade_no,
						partner, payment_type, seller_email, service, itemUrl,
						sign_type, subject, total_fee, show_url, paymethod,defaultbank};
			
				
			} else if (whichAlipayWay.equals("kuaiqian")) {

				String merchantAcctId = getResources(request).getMessage(
						"Letousky.kuaiqian.merchantAcctId");// 人民币网关账户号
				String key = getResources(request).getMessage(
						"Letousky.kuaiqian.key");// 人民币网关密钥
				String inputCharset = getResources(request).getMessage(
						"Letousky.kuaiqian.inputCharset"); // 字符集.固定选择值。可为空。代表UTF-8;
				// 2代表GBK; 3代表gb2312
				// 默认值为1只能选择1、2、3.
				String bgUrl = getResources(request).getMessage(
						"Letousky.kuaiqian.buUrl"); // 服务器接受支付结果的后台地址.与[pageUrl]不能同时为空。必须是绝对地址。
				// ,
				// 快钱通过服务器连接的方式将交易结果发送到[bgUrl]对应的页面地址，在商户处理完成后输出的<result>如果为1，页面会转向到<redirecturl>对应的地址。
				// ,
				// 如果快钱未接收到<redirecturl>对应的地址，快钱将把支付结果GET到[pageUrl]对应的页面
				String version = getResources(request).getMessage(
						"Letousky.kuaiqian.version"); // 网关版本.固定值
				String language = getResources(request).getMessage(
						"Letousky.kuaiqian.language");// 语言种类.固定选择值。,
				// 只能选择1、2、3 1代表中文；2代表英文
				String signType = getResources(request).getMessage(
						"Letousky.kuaiqian.signType");// 签名类型.固定值,
				// 1代表MD5签名,当前版本固定为1
				String payerName = "payerName"; // //支付人姓名

				String payerContactType = getResources(request).getMessage(
						"Letousky.kuaiqian.payerContactType");// 支付人联系方式类型.固定选择值
				// 只能选择1
				// 1代表Email

				String payerContact = getResources(request).getMessage(
						"Letousky.kuaiqian.payerContact"); // 支付人联系方式
				// //只能选择Email或手机号

				String orderId = request.getParameter("tradeId");// 商户订单号
				// ///由字母、数字、或[-][_]组成

				String orderAmount = request.getParameter("tradeMoney");// 订单金额,以分为单位，必须是整型数字,比方2，代表0.02元
				orderAmount = "" + Double.parseDouble(orderAmount) * 100;
				orderAmount = orderAmount
						.substring(0, orderAmount.indexOf("."));

				String orderTime = new java.text.SimpleDateFormat(
						"yyyyMMddHHmmss").format(new java.util.Date()); // 订单提交时间
				// 如；20080101010101

				String productName = getResources(request).getMessage(
						"Letousky.kuaiqian.productName"); // 商品名称,可为中文或英文字符

				String productNum = getResources(request).getMessage(
						"Letousky.kuaiqian.productNum");// 商品数量

				String productId = getResources(request).getMessage(
						"Letousky.kuaiqian.productId");// 商品代码 可为字符或者数字

				String productDesc = getResources(request).getMessage(
						"Letousky.kuaiqian.productDesc"); // 商品描述

				String ext1 = getResources(request).getMessage(
						"Letousky.kuaiqian.ext1");// 扩展字段1 在支付结束后原样返回给商户
				String ext2 = getResources(request).getMessage(
						"Letousky.kuaiqian.ext2");// 扩展字段2 在支付结束后原样返回给商户
				String payType = getResources(request).getMessage(
						"Letousky.kuaiqian.payType");// 支付方式.固定选择值,只能选择00、10、11、12、13、14,00：组合支付（网关支付页面显示快钱支持的各种支付方式，推荐使用）10：银行卡支付（网关支付页面只显示银行卡支付）.11：电话银行支付（网关支付页面只显示电话支付）.12：快钱账户支付（网关支付页面只显示快钱账户支付）.13：线下支付（网关支付页面只显示线下支付方式）
				String redoFlag = getResources(request).getMessage(
						"Letousky.kuaiqian.redoFlag");// 同一订单禁止重复提交标志,固定选择值：
				// 1、0
				String pid = getResources(request).getMessage(
						"Letousky.kuaiqian.pid");// 快钱的合作伙伴的账户号

				// 生成加密签名串
				// /请务必按照如下顺序和规则组成加密串！
				String signMsgVal = "";
				signMsgVal = appendParam(signMsgVal, "inputCharset",
						inputCharset);
				signMsgVal = appendParam(signMsgVal, "bgUrl", bgUrl);
				signMsgVal = appendParam(signMsgVal, "version", version);
				signMsgVal = appendParam(signMsgVal, "language", language);
				signMsgVal = appendParam(signMsgVal, "signType", signType);
				signMsgVal = appendParam(signMsgVal, "merchantAcctId",
						merchantAcctId);
				signMsgVal = appendParam(signMsgVal, "payerName", payerName);
				signMsgVal = appendParam(signMsgVal, "payerContactType",
						payerContactType);
				signMsgVal = appendParam(signMsgVal, "payerContact",
						payerContact);
				signMsgVal = appendParam(signMsgVal, "orderId", orderId);
				signMsgVal = appendParam(signMsgVal, "orderAmount", orderAmount);
				signMsgVal = appendParam(signMsgVal, "orderTime", orderTime);
				signMsgVal = appendParam(signMsgVal, "productName", productName);
				signMsgVal = appendParam(signMsgVal, "productNum", productNum);
				signMsgVal = appendParam(signMsgVal, "productId", productId);
				signMsgVal = appendParam(signMsgVal, "productDesc", productDesc);
				signMsgVal = appendParam(signMsgVal, "ext1", ext1);
				signMsgVal = appendParam(signMsgVal, "ext2", ext2);
				signMsgVal = appendParam(signMsgVal, "payType", payType);
				signMsgVal = appendParam(signMsgVal, "redoFlag", redoFlag);
				signMsgVal = appendParam(signMsgVal, "pid", pid);
				signMsgVal = appendParam(signMsgVal, "key", key);

				String signMsg = MD5Util.md5Hex(signMsgVal.getBytes("gb2312"))
						.toUpperCase();

				params = new String[] { merchantAcctId, key, inputCharset,
						bgUrl, version, language, signType, payerName,
						payerContactType, payerContact, orderId, orderAmount,
						orderTime, productName, productNum, productId,
						productDesc, ext1, ext2, payType, redoFlag, pid,
						signMsg };
				if (false) {// 打印参数值
					System.out.println("merchantAcctId=" + merchantAcctId);
					System.out.println("key=" + key);
					System.out.println("inputCharset=" + inputCharset);
					System.out.println("bgUrl=" + bgUrl);
					System.out.println("version=" + version);
					System.out.println("language=" + language);
					System.out.println("signType=" + signType);
					System.out.println("payerName=" + payerName);
					System.out.println("payerContactType=" + payerContactType);
					System.out.println("payerContact=" + payerContact);
					System.out.println("orderId=" + orderId);
					System.out.println("orderAmount=" + orderAmount);
					System.out.println("orderTime=" + orderTime);
					System.out.println("productName=" + productName);
					System.out.println("productNum=" + productNum);
					System.out.println("productId=" + productId);
					System.out.println("productDesc=" + productDesc);
					System.out.println("ext1=" + ext1);
					System.out.println("ext2=" + ext2);
					System.out.println("payType=" + payType);
					System.out.println("redoFlag=" + redoFlag);
					System.out.println("pid=" + pid);
					System.out.println("signMsg=" + signMsg);
				}

			} else {
				String merchantAcctId = getResources(request).getMessage(
						"Letousky.kuaiqian.merchantAcctId");// 人民币网关账户号
				String key = getResources(request).getMessage(
						"Letousky.kuaiqian.key");// 人民币网关密钥
				String inputCharset = getResources(request).getMessage(
						"Letousky.kuaiqian.inputCharset"); // 字符集.固定选择值。可为空。代表UTF-8;
				// 2代表GBK; 3代表gb2312
				// 默认值为1只能选择1、2、3.
				
				String pageUrl=getResources(request).getMessage("Letousky.kuaiqian.pageUrl");
				String bgUrl = getResources(request).getMessage("Letousky.kuaiqian.buUrl"); // 服务器接受支付结果的后台地址.与[pageUrl]不能同时为空。必须是绝对地址。
				// ,
				// 快钱通过服务器连接的方式将交易结果发送到[bgUrl]对应的页面地址，在商户处理完成后输出的<result>如果为1，页面会转向到<redirecturl>对应的地址。
				// ,
				// 如果快钱未接收到<redirecturl>对应的地址，快钱将把支付结果GET到[pageUrl]对应的页面
				String version = getResources(request).getMessage("Letousky.kuaiqian.version"); // 网关版本.固定值
				String language = getResources(request).getMessage("Letousky.kuaiqian.language");// 语言种类.固定选择值。,
				// 只能选择1、2、3 1代表中文；2代表英文
				String signType = getResources(request).getMessage("Letousky.kuaiqian.signType");// 签名类型.固定值,
				// 1代表MD5签名,当前版本固定为1
				String payerName = "payerName"; // //支付人姓名

				String payerContactType = getResources(request).getMessage("Letousky.kuaiqian.payerContactType");// 支付人联系方式类型.固定选择值
				// 只能选择1
				// 1代表Email

				String payerContact = getResources(request).getMessage("Letousky.kuaiqian.payerContact"); // 支付人联系方式
				// //只能选择Email或手机号

				String orderId = request.getParameter("tradeId");// 商户订单号
				// ///由字母、数字、或[-][_]组成

				String orderAmount = request.getParameter("tradeMoney");// 订单金额,以分为单位，必须是整型数字,比方2，代表0.02元
				orderAmount = "" + Double.parseDouble(orderAmount) * 100;
				orderAmount = orderAmount
						.substring(0, orderAmount.indexOf("."));

				String orderTime = new java.text.SimpleDateFormat("yyyyMMddHHmmss").format(new java.util.Date()); // 订单提交时间
				// 如；20080101010101

				String productName = getResources(request).getMessage(
						"Letousky.kuaiqian.productName"); // 商品名称,可为中文或英文字符

				String productNum = getResources(request).getMessage(
						"Letousky.kuaiqian.productNum");// 商品数量

				String productId = getResources(request).getMessage(
						"Letousky.kuaiqian.productId");// 商品代码 可为字符或者数字

				String productDesc = getResources(request).getMessage(
						"Letousky.kuaiqian.productDesc"); // 商品描述

				String ext1 = getResources(request).getMessage(
						"Letousky.kuaiqian.ext1");// 扩展字段1 在支付结束后原样返回给商户
				String ext2 = getResources(request).getMessage(
						"Letousky.kuaiqian.ext2");// 扩展字段2 在支付结束后原样返回给商户
				String payType ="10";// 支付方式.固定选择值,只能选择00、10、11、12、13、14,00：组合支付（网关支付页面显示快钱支持的各种支付方式，推荐使用）10：银行卡支付（网关支付页面只显示银行卡支付）.11：电话银行支付（网关支付页面只显示电话支付）.12：快钱账户支付（网关支付页面只显示快钱账户支付）.13：线下支付（网关支付页面只显示线下支付方式）
				
				String bankId=whichAlipayWay;
				String redoFlag = getResources(request).getMessage(
						"Letousky.kuaiqian.redoFlag");// 同一订单禁止重复提交标志,固定选择值：
				// 1、0
				String pid = getResources(request).getMessage(
						"Letousky.kuaiqian.pid");// 快钱的合作伙伴的账户号

				//生成加密签名串
				///请务必按照如下顺序和规则组成加密串！
				String signMsgVal="";
				signMsgVal=appendParam(signMsgVal,"inputCharset",inputCharset);
				signMsgVal=appendParam(signMsgVal,"pageUrl",pageUrl);
				signMsgVal=appendParam(signMsgVal,"bgUrl",bgUrl);
				signMsgVal=appendParam(signMsgVal,"version",version);
				signMsgVal=appendParam(signMsgVal,"language",language);
				signMsgVal=appendParam(signMsgVal,"signType",signType);
				signMsgVal=appendParam(signMsgVal,"merchantAcctId",merchantAcctId);
				signMsgVal=appendParam(signMsgVal,"payerName",payerName);
				signMsgVal=appendParam(signMsgVal,"payerContactType",payerContactType);
				signMsgVal=appendParam(signMsgVal,"payerContact",payerContact);
				signMsgVal=appendParam(signMsgVal,"orderId",orderId);
				signMsgVal=appendParam(signMsgVal,"orderAmount",orderAmount);
				signMsgVal=appendParam(signMsgVal,"orderTime",orderTime);
				signMsgVal=appendParam(signMsgVal,"productName",productName);
				signMsgVal=appendParam(signMsgVal,"productNum",productNum);
				signMsgVal=appendParam(signMsgVal,"productId",productId);
				signMsgVal=appendParam(signMsgVal,"productDesc",productDesc);
				signMsgVal=appendParam(signMsgVal,"ext1",ext1);
				signMsgVal=appendParam(signMsgVal,"ext2",ext2);
				signMsgVal=appendParam(signMsgVal,"payType",payType);
				signMsgVal=appendParam(signMsgVal,"bankId",bankId);
				signMsgVal=appendParam(signMsgVal,"redoFlag",redoFlag);
				signMsgVal=appendParam(signMsgVal,"pid",pid);
				signMsgVal=appendParam(signMsgVal,"key",key);

		     	String signMsg=MD5Util.md5Hex(signMsgVal.getBytes("gb2312")).toUpperCase();

				params = new String[] { merchantAcctId, key, inputCharset,pageUrl,
						bgUrl, version, language, signType, payerName,
						payerContactType, payerContact, orderId, orderAmount,
						orderTime, productName, productNum, productId,
						productDesc, ext1, ext2, payType, bankId,redoFlag, pid,
						signMsg };
				if (false) {// 打印参数值
					System.out.println("merchantAcctId=" + merchantAcctId);
					System.out.println("key=" + key);
					System.out.println("inputCharset=" + inputCharset);
					System.out.println("bgUrl=" + bgUrl);
					System.out.println("version=" + version);
					System.out.println("language=" + language);
					System.out.println("signType=" + signType);
					System.out.println("payerName=" + payerName);
					System.out.println("payerContactType=" + payerContactType);
					System.out.println("payerContact=" + payerContact);
					System.out.println("orderId=" + orderId);
					System.out.println("orderAmount=" + orderAmount);
					System.out.println("orderTime=" + orderTime);
					System.out.println("productName=" + productName);
					System.out.println("productNum=" + productNum);
					System.out.println("productId=" + productId);
					System.out.println("productDesc=" + productDesc);
					System.out.println("ext1=" + ext1);
					System.out.println("ext2=" + ext2);
					System.out.println("bankId=" + bankId);
					System.out.println("payType=" + payType);
					System.out.println("redoFlag=" + redoFlag);
					System.out.println("pid=" + pid);
					System.out.println("signMsg=" + signMsg);
				}
			}

			request.setAttribute("whichAlipayWay", whichAlipayWay);
			request.setAttribute("payType", paytype);
			request.setAttribute("rel", params);
			__logger.debug("结束!");
			return mapping.findForward("alipayCom");
		} catch (LotteryException le) {
			// System.out.println(le.getErrNo()+" "+le.getErrMsg());
			request.setAttribute("msg", le.getErrMsg());
			return mapping.findForward("LotteryEx");
		} catch (Exception e) {
			// e.printStackTrace();
			return mapping.findForward("Ex");
		}
	}

	// 功能函数。将变量值不为空的参数组成字符串
	public String appendParam(String returnStr, String paramId,
			String paramValue) {
		if (!returnStr.equals("")) {
			if (!paramValue.equals("")) {
				returnStr = returnStr + "&" + paramId + "=" + paramValue;
			}
		} else {
			if (!paramValue.equals("")) {
				returnStr = paramId + "=" + paramValue;
			}
		}
		return returnStr;
	}

	// 功能函数。将变量值不为空的参数组成字符串。结束

	/**
	 * 充值申请提交支付宝完成以后,支付宝异步通知回复
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward alipayNotify1(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		System.out.println("alipayNotify1________________ok");
		System.out.println("alipayNotify1________________ok");
		System.out.println("alipayNotify1________________ok");
		System.out.println("alipayNotify1________________ok");
		
		String merchantAcctId;// 获取人民币网关账户号
		String key;// 设置人民币网关密钥
		String version;// 获取网关版本.固定值
		String language; // 获取语言种类.固定选择值。
		String signType; // 签名类型.固定值

		String payType;// 获取支付方式

		String bankId;// 获取银行代码

		String orderId; // 获取商户订单号

		String orderTime;// 获取订单提交时间

		String orderAmount;// 获取原始订单金额
		String dealId; // 获取快钱交易号

		String bankDealId; // 获取银行交易号

		String dealTime;// 获取在快钱交易时间

		String payAmount;// 获取实际支付金额

		String fee;// 获取交易手续费

		String ext1;// 获取扩展字段1

		String ext2; // 获取扩展字段2

		String payResult; // 获取处理结果
		// /10代表 成功11代表 失败
		try {
			merchantAcctId = (String) request.getParameter("merchantAcctId").trim();
			key = "1234567897654321";
			version = (String) request.getParameter("version").trim();
			language = (String) request.getParameter("language").trim();
			signType = (String) request.getParameter("signType").trim();
			payType = (String) request.getParameter("payType").trim();
			bankId = (String) request.getParameter("bankId").trim();
			orderId = (String) request.getParameter("orderId").trim();
			orderTime = (String) request.getParameter("orderTime").trim();
			orderAmount = (String) request.getParameter("orderAmount").trim();
			orderAmount = "" + Double.parseDouble(orderAmount) / 100;
			dealId = (String) request.getParameter("dealId").trim();
			bankDealId = (String) request.getParameter("bankDealId").trim();
			dealTime = (String) request.getParameter("dealTime").trim();
			payAmount = (String) request.getParameter("payAmount").trim();
			fee = (String) request.getParameter("fee").trim();
			ext1 = (String) request.getParameter("ext1").trim();
			ext2 = (String) request.getParameter("ext2").trim();
			payResult = (String) request.getParameter("payResult").trim();
		
		// 获取错误代码
		// /详细见文档错误代码列表
		String errCode = (String) request.getParameter("errCode").trim();

		// 获取加密签名串
		String signMsg = (String) request.getParameter("signMsg").trim();

	//	System.out.print("merchantAcctId=" + merchantAcctId);
		//System.out.print("key=" + key);
		//System.out.print("version=" + version);
	//	System.out.print("language=" + language);
	//	System.out.print("signType=" + signType);
	//	System.out.print("payType=" + payType);
	//	System.out.print("bankId=" + bankId);
	//	System.out.print("orderId=" + orderId);
	//	System.out.print("orderTime=" + orderTime);
		//System.out.print("orderAmount=" + orderAmount);
	//	System.out.print("dealId=" + dealId);
	//	System.out.print("bankDealId=" + bankDealId);
		//System.out.print("dealTime=" + dealTime);
		//System.out.print("payAmount=" + payAmount);

		// 生成加密串。必须保持如下顺序。
		String merchantSignMsgVal = "";
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "merchantAcctId",
				merchantAcctId);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "version", version);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "language",
				language);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "signType",
				signType);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "payType", payType);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "bankId", bankId);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "orderId", orderId);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "orderTime",
				orderTime);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "orderAmount",
				orderAmount);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "dealId", dealId);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "bankDealId",
				bankDealId);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "dealTime",
				dealTime);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "payAmount",
				payAmount);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "fee", fee);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "ext1", ext1);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "ext2", ext2);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "payResult",
				payResult);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "errCode", errCode);
		merchantSignMsgVal = appendParam(merchantSignMsgVal, "key", key);

		String merchantSignMsg = MD5Util.md5Hex(
				merchantSignMsgVal.getBytes("gb2312")).toUpperCase();

		// 初始化结果及地址
		int rtnOk = 0;

		// 商家进行数据处理，并跳转会商家显示支付结果的页面
		// /首先进行签名字符串验证
		if (signMsg.toUpperCase().equals(merchantSignMsg.toUpperCase())) {
			
			// /接着进行支付结果判断
			switch (Integer.parseInt(payResult)) {

			case 10:

				// *
				// 商户网站逻辑处理，比方更新订单支付状态为成功
				// 特别注意：只有signMsg.toUpperCase().equals(merchantSignMsg.toUpperCase())，且payResult=10，才表示支付成功！同时将订单金额与提交订单前的订单金额进行对比校验。
				// *

				// 报告给快钱处理结果，并提供将要重定向的地址。
				del.handleDelegateAry(new String[] { orderId, payAmount },
						"C0084");
				// System.out.println("success----------------------");

				break;

			default:
				break;

			}

		} else {
			System.out.println("==============================Error");
		}
		
		} catch (Exception ex) {
		    ex.getStackTrace();
			System.out.print(ex.getMessage()+"==================================== Message Error");
		}
		return mapping.findForward(null);
	}

	/**
	 * ajax分页，非常方便带参数
	 * 
	 * @param params
	 *            查询要带的参数除了分页的
	 * @param page
	 *            当前第几页
	 * 
	 * @param showLen
	 *            一页显示多少条记录
	 * @param total
	 *            总记录数
	 * @param request
	 */
	protected void setReqAtt(String params, Integer page, Integer showLen,
			Integer total, HttpServletRequest request) {
		request.setAttribute("params", params);//查询要带的参数除了分页的
		request.setAttribute("page", page);//当前第几页

		request.setAttribute("showLen", showLen);//一页显示多少条记录
		request.setAttribute("total", total);//总记录数
	}
	
	
	/**
	 * 充值申请提交支付宝完成以后,支付宝异步通知回复
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward alipayNotify(ActionMapping mapping,ActionForm form,
			HttpServletRequest request,HttpServletResponse response)throws Exception{
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");  
		PrintWriter out = response.getWriter();	
		
		/*System.out.println("notify_type: "+request.getParameter("notify_type"));
		System.out.println("notify_id: "+request.getParameter("notify_id"));
		System.out.println("notify_time: "+request.getParameter("notify_time"));
		System.out.println("sign: "+request.getParameter("sign"));
		System.out.println("sign_type: "+request.getParameter("sign_type"));
		System.out.println("trade_no: "+request.getParameter("trade_no"));
		System.out.println("out_trade_no: "+request.getParameter("out_trade_no"));
		System.out.println("payment_type: "+request.getParameter("payment_type"));
		System.out.println("subject: "+request.getParameter("subject"));
		System.out.println("body: "+request.getParameter("body"));
		System.out.println("total_fee: "+request.getParameter("total_fee"));
		System.out.println("trade_status: "+request.getParameter("trade_status"));
		System.out.println("seller_email: "+request.getParameter("seller_email"));
		System.out.println("seller_id: "+request.getParameter("seller_id"));
		System.out.println("buyer_id: "+request.getParameter("buyer_id"));
		System.out.println("buyer_email: "+request.getParameter("buyer_email"));	*/
		
		try{
			__logger.debug("开始!");  
			String partner = getResources(request).getMessage("Letousky.Alipay.partner"); //支付宝合作伙伴id (账户内提取)
			String privateKey = getResources(request).getMessage("Letousky.Alipay.key"); //支付宝安全校验码(账户内提取)
			String alipayNotifyURL = "http://notify.alipay.com/trade/notify_query.do?" + "&partner="+ partner+ "&notify_id="+ request.getParameter("notify_id");
			//获取支付宝ATN返回结果，true是正确的订单信息，false 是无效的
			String responseTxt = CheckURL.check(alipayNotifyURL);
			System.out.println("responseTxt: "+responseTxt);
			Map params = new HashMap();
			//获得POST 过来参数设置到新的params中

			Map requestParams = request.getParameterMap();
			for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
				String name = (String) iter.next();
				if(name.equals("action"))
					continue;
				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] + ",";
				}
				//返回如果已经是UTF-8了就不要下面再转了，不然正确转错误

				//valueStr=new String (valueStr.getBytes("ISO-8859-1"),"UTF-8"); 
				params.put(name, valueStr);
				//System.out.println("name: "+name+"  value: "+valueStr);
			}
		
			String mysign = SignatureHelper.sign(params,privateKey);
			
			//System.out.println("mysign: "+mysign);
			if (mysign.equals(request.getParameter("sign"))&& responseTxt.equals("true")) {
				
				/*if (request.getParameter("trade_status").equals("TRADE_FINISHED")) { 
					out.println("fail超过限额");
				}*/
				if (request.getParameter("trade_status").equals("TRADE_SUCCESS") || request.getParameter("trade_status").equals("TRADE_FINISHED")) { 
				//在这里可以写入数据处理,
					//System.out.println("success1=====================");
					//del.handleDelegateAry(new String[]{request.getParameter("out_trade_no"),request.getParameter("total_fee")}, "N0038");
					del.handleDelegateAry(new String[] { request.getParameter("out_trade_no"),request.getParameter("total_fee")},"C0084");
					out.println("success");
				}
			} else {
				out.println("fail");
			}
			System.out.println("****************************通知结束");
			__logger.debug("结束!");
			return mapping.findForward(null);
		}catch(LotteryException le){ 
		System.out.println(le.getErrNo()+" "+le.getErrMsg()+"===============notify");
			out.print("success");//success状态,支付宝将不再一直notify我这个方法

			return mapping.findForward(null);
		}catch(Exception e){
			//e.printStackTrace();
			System.out.println("ex=====================================");
			return mapping.findForward(EX);
		} 
	}
}


