/*
 * Project Name:upay-sdk-web
 * File Name:BindcardNotifyServlet.java
 * Package Name:com.upay.sdk.ert.v_3.BindcardNotifyServlet
 * Date:2019-04-10 18:19:07
 * Copyright (c) 2019, upay All Rights Reserved.
 */

package com.upay.sdk.wallet;

import com.alibaba.fastjson.JSONObject;

import com.upay.sdk.FastJsonUtils;
import com.upay.sdk.exception.HmacVerifyException;
import com.upay.sdk.exception.ResponseException;
import com.upay.sdk.exception.UnknownException;
import com.upay.sdk.executer.ResultListenerAdpater;
import com.upay.sdk.wallet.executer.WithdrawExecuter;
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 java.io.IOException;
import java.io.PrintWriter;

/**
 * 提现完成,通知商户
 */
public class WithdrawNotifyServlet extends HttpServlet {
	static final Logger LOGGER = LoggerFactory.getLogger(WithdrawNotifyServlet.class);

    private static final String ENCRYPT_KEY = "encryptKey";
    private static final String MERCHANT_ID = "merchantId";
    private static final String PARTNER_ID = "partnerId";
	private static final String WITHDRAW_STATUS="withdrawStatus";


	@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 {
		WithdrawExecuter executer = new WithdrawExecuter();
	    try{
            JSONObject json = FastJsonUtils.convert(req.getInputStream());
            json.put(ENCRYPT_KEY,req.getHeader(ENCRYPT_KEY));
            json.put(MERCHANT_ID,req.getHeader(MERCHANT_ID));
		    executer.bothCipherCallback(json, new ResultListenerAdpater() {
		        @Override
	            public void success(JSONObject jsonObject) {
					if (jsonObject.get("withdrawStatus") != null) {
						String status = jsonObject.getString("withdrawStatus");
						LOGGER.info("提现成功！");
						LOGGER.info(jsonObject.toJSONString());
					}
				}
		        @Override
	            public void failure(JSONObject jsonObject) {
	                LOGGER.info("提现失败！",jsonObject);
	                LOGGER.info(jsonObject.toJSONString());
	            }
	        });
	    }
		catch(ResponseException e){
			LOGGER.info("响应异常");
			LOGGER.info(e.toString());
		}
		catch(HmacVerifyException e){
			LOGGER.info("签名验证异常");
			LOGGER.info(e.toString());
		}
		catch(UnknownException e){
			LOGGER.info("未知异常");
			LOGGER.info(e.toString());
		}
	    
	    LOGGER.info("withdraw notify success...");
		PrintWriter out = resp.getWriter();
		out.print("SUCCESS");
	}
}
