package com.upay.sdk.onlinepay;

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.onlinepay.executer.OnlinePayOrderExecuter;
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;

public class RefundNotifyServlet extends HttpServlet {
	static final Logger LOGGER = LoggerFactory.getLogger(RefundNotifyServlet.class);

    private static final String ENCRYPT_KEY = "encryptKey";
    private static final String MERCHANT_ID = "merchantId";


    @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 {

	    try{
            OnlinePayOrderExecuter executer = new OnlinePayOrderExecuter();
            JSONObject json = FastJsonUtils.convert(req.getInputStream());
            String encryptKey = req.getHeader(ENCRYPT_KEY);
            String merchantId = req.getHeader(MERCHANT_ID);
            json.put(ENCRYPT_KEY,encryptKey);
            json.put(MERCHANT_ID,merchantId);

            LOGGER.info("encryptKey : {},merchantId : {}",encryptKey,merchantId);
		    executer.bothCipherCallback(json, new ResultListenerAdpater() {

				@Override
                public void success(JSONObject jsonObject) {
                    LOGGER.info("退款成功！");
                    LOGGER.info(jsonObject.toJSONString());
                }

				@Override
                public void failure(JSONObject jsonObject) {
                    LOGGER.info("退款失败！");
                    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());
		}
	}
}
