
package com.upay.sdk.onlinepay;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.upay.sdk.entity.*;
import com.upay.sdk.exception.HmacVerifyException;
import com.upay.sdk.exception.RequestException;
import com.upay.sdk.exception.ResponseException;
import com.upay.sdk.exception.UnknownException;
import com.upay.sdk.executer.ResultListenerAdpater;
import com.upay.sdk.onlinepay.builder.OrderBuilder;
import com.upay.sdk.onlinepay.builder.OrderResponse;
import com.upay.sdk.onlinepay.executer.OnlinePayOrderExecuter;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

public class OrderServlet extends HttpServlet {

	private static final long serialVersionUID = -1450599121936722735L;
	
	static final Logger LOGGER = LoggerFactory.getLogger(OrderServlet.class);

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
		
        final String agent = req.getHeader("User-agent");//判断客户端
        LOGGER.info("agent:"+agent);
        //商户编号
		String merchantId = req.getParameter("merchantId");
		//订单号
		String requestId = req.getParameter("requestId");
		//订单金额
		String orderAmount = req.getParameter("orderAmount");
		//订单币种
		String orderCurrency = req.getParameter("orderCurrency");
		//	通知地址
		String notifyUrl = req.getParameter("notifyUrl");
		//回调地址
		String callbackUrl = req.getParameter("callbackUrl");
		//	备注
		String remark = req.getParameter("remark");
		//payer
		String email = req.getParameter("email");
		//支付方式编码(BANK_CARD-AGREEMENT-P2P 协议支付)
		String paymentModeCode = req.getParameter("paymentModeCode");
		//支付场景
		String authCode = req.getParameter("authCode");
		
		//收银台版本
		String cashierVersion = req.getParameter("cashierVersion");
		//付款人姓名
		String payerName = req.getParameter("payerName");
		//手机号码
		String phoneNum = req.getParameter("phoneNum");
		//证件号
		String idNum = req.getParameter("idNum");
		//证件类型
		String idType = req.getParameter("idType");
		//银行卡号
		String bankCardNum = req.getParameter("bankCardNum");
		//业务背景
		String forUse = req.getParameter("forUse");
		//商户会员Id
		String merchantUserId = req.getParameter("merchantUserId");
		//绑卡Id
		String bindCardId = req.getParameter("bindCardId");
		//ip
		String clientIp = req.getParameter("clientIp");
		//超时时间
		String timeout = req.getParameter("timeout");
        
		OrderBuilder builder = new OrderBuilder(merchantId);
		builder.setRequestId(requestId).setOrderAmount(orderAmount).setOrderCurrency(orderCurrency)
				.setNotifyUrl(notifyUrl).setCallbackUrl(callbackUrl).setRemark(remark)
				.setPaymentModeCode(paymentModeCode).setNotifyUrl(notifyUrl).setAuthCode(authCode)
				.setCashierVersion(cashierVersion).setForUse(forUse).setMerchantUserId(merchantUserId)
				.setBindCardId(bindCardId).setClientIp(clientIp);
		builder.setTimeout(timeout);
	
		
		ProductDetail productDetail = new ProductDetail();
		String jsonPDStr = req.getParameter("hiddenPD").trim();
		
		LOGGER.info("productDetail++++++++++++++"+jsonPDStr);
		
		JSONArray productDetailArray = JSONObject.parseArray(jsonPDStr);
		for(Object o:productDetailArray) {
			productDetail = JSONObject.parseObject(o.toString(), ProductDetail.class);
			builder.addProductDetail(productDetail);
		}
		
		
		Payer payer = new Payer();
		payer.setName(payerName);
		payer.setPhoneNum(phoneNum);
		payer.setBankCardNum(bankCardNum);
		payer.setIdNum(idNum);
		payer.setIdType(idType);
		payer.setEmail(email);

		builder.setPayer(payer);
		
 
        final PrintWriter out = resp.getWriter();
		try{
            OnlinePayOrderExecuter executer = new OnlinePayOrderExecuter();
			executer.bothOrder(builder, new ResultListenerAdpater() {
                /**
                 * 提交成功，不代表支付成功
                 */
				@Override
                public void success(JSONObject jsonObject) {
                    LOGGER.debug("success jsonObject:[" + jsonObject + "]");
                    if (jsonObject.get("scanCode") != null) {
                        try {
                            HttpSession session = req.getSession();
                            OrderResponse orderResponse = new OrderResponse();
                            orderResponse.setHmac(jsonObject.getString("hmac"));
                            orderResponse.setMerchantId(jsonObject.getString("merchantId"));
                            orderResponse.setRequestId(jsonObject.getString("requestId"));
                            orderResponse.setStatus(jsonObject.getString("status"));
                            String scanCodeStr = jsonObject.getString("scanCode");
                            orderResponse.setScanCode(Base64.decodeBase64(scanCodeStr));

                            session.setAttribute("orderResponse", orderResponse);
                            resp.sendRedirect("scancode.jsp");
                        } catch (Exception e) {
                            out.println("响应异常</br>");
                            out.println(e.toString());
                        }
                    }else if(jsonObject.get("jsString") != null && agent.contains("MicroMessenger")){
                        //微信公众号支付
                        try {
                            HttpSession session = req.getSession();
                            session.setAttribute("jsString", jsonObject.get("jsString"));
                            resp.sendRedirect("wechatjsapi.jsp");
                        } catch (Exception e) {
                            out.println("响应异常</br>");
                            out.println(e.toString());
                        }
                    }
                    out.println("提交成功</br>");
                    out.println(jsonObject);
                    String hmac = jsonObject.getString("hmac");
                    
                    
                }

				@Override
                public void redirect(JSONObject jsonObject, String redirectUrl) throws IOException {
                    resp.sendRedirect(redirectUrl);
                    LOGGER.debug("redirectUrl:[" + redirectUrl + "]");
                }
            });
		}
		catch(ResponseException e){
				out.println("响应异常</br>");
				out.println(e.toString());
			}
		catch(HmacVerifyException e){
				out.println("签名验证异常</br>");
				out.println(e.toString());
			}
		catch(RequestException e){
				out.println("请求异常</br>");
				out.println(e.toString());
			}
		catch(UnknownException e){
				out.println("未知异常</br>");
				out.println(e.toString());
		}
	}
}
