

package com.upay.sdk.onlinepay;

import com.alibaba.fastjson.JSONObject;
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.RefundBuilder;
import com.upay.sdk.onlinepay.executer.OnlinePayOrderExecuter;

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


public class RefundServlet extends HttpServlet {

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

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String merchantId = req.getParameter("merchantId");
		String requestId = req.getParameter("requestId");
		String amount = req.getParameter("amount");
		String orderId = req.getParameter("orderId");
		String remark = req.getParameter("remark");
		String notifyUrl = req.getParameter("notifyUrl");

		RefundBuilder builder = new RefundBuilder(merchantId);
		builder.setRequestId(requestId).setAmount(amount).setOrderId(orderId).setRemark(remark).setNotifyUrl(notifyUrl);;

		final PrintWriter out = resp.getWriter();
		OnlinePayOrderExecuter executer = new OnlinePayOrderExecuter();
		
		try{
			executer.bothRefund(builder, new ResultListenerAdpater() {
				@Override
				public void success(JSONObject jsonObject) {
				    out.println("处理成功！<br/>");
					String result = jsonObject.toJSONString();
					out.print(result);
				}

				@Override
				public void failure(JSONObject jsonObject) {
				    out.println("处理失败！<br/>");
					String result = jsonObject.toJSONString();
					out.print(result);
				}

				@Override
		        public void pending(JSONObject jsonObject) {
		            out.println("待处理！<br/>");
		            String result = jsonObject.toJSONString();
		            out.print(result);
		        }
			});
		}
		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());
		}
	}
}
