/*
 * Project Name:upay-sdk-web
 * File Name:BindCardQueryServlet.java
 * Package Name:com.upay.sdk.cashier.bindcard.BindCardQueryServlet
 * Date:2019-01-28 15:50:10
 * Copyright (c) 2019, upay All Rights Reserved.
 */

package com.upay.sdk.onlinepay;

import com.alibaba.fastjson.JSONObject;
import com.upay.sdk.cashier.bindcard.builder.BindCardQueryBuilder;
import com.upay.sdk.cashier.bindcard.executer.BindCardExecuter;
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 org.apache.commons.lang3.StringUtils;

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 BindCardQueryServlet extends HttpServlet {

	private static final long serialVersionUID = -1164878700739474259L;

	@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 bindCardId = req.getParameter("bindCardId");
		String merchantUserId = req.getParameter("merchantUserId");



		BindCardQueryBuilder builder = new BindCardQueryBuilder(merchantId);
		builder.setBindCardId(bindCardId)
		.setMerchantUserId(merchantUserId);

		final PrintWriter out = resp.getWriter();


		if(StringUtils.isBlank(merchantId)){
			out.println("参数异常</br>");
			out.println("商户编号不能为空");
			return;
		}else{
			if (merchantId.length() != 9){
				out.println("参数异常</br>");
				out.println("商户编号长度必须为9");
				return;
			}
		}

		BindCardExecuter executer = new BindCardExecuter();
		try {
			executer.bothBindCardQuery(builder, new ResultListenerAdpater() {
				@Override
				public void success(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());
		}
	}
}
