package org.dromara.settlement.common.bank.zhifubao;

import com.alibaba.fastjson.JSONObject;
import org.dromara.settlement.api.domain.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alipay.api.AlipayRequest;
import com.alipay.api.AlipayResponse;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;

public class ZhiFuBaoUtil {
	private static final Logger log = LoggerFactory.getLogger(ZhiFuBaoUtil.class);

	private static class SingletonHolder {
		private static final ZhiFuBaoUtil INSTANCE = new ZhiFuBaoUtil();
	}

	private ZhiFuBaoUtil() {
	}

	public static final ZhiFuBaoUtil getInstance() {
		return SingletonHolder.INSTANCE;
	}

    public Result<ZhiFuBaoResponse> request(ZhiFuBaoConfig config, AlipayRequest request, boolean isPage) {
    	Result<ZhiFuBaoResponse> rtn = new Result<ZhiFuBaoResponse>();
		try {
			CertAlipayRequest certAlipayRequest = new CertAlipayRequest ();
		    certAlipayRequest.setServerUrl(config.URL);
		    certAlipayRequest.setAppId(config.APPID);
		    certAlipayRequest.setPrivateKey(config.prikeyStr);
		    certAlipayRequest.setFormat("JSON");
		    certAlipayRequest.setCharset("UTF-8");
		    certAlipayRequest.setSignType("RSA2");
		    certAlipayRequest.setCertPath(config.appCertPublicKey);
		    certAlipayRequest.setAlipayPublicCertPath(config.alipayCertPublicKey);
		    certAlipayRequest.setRootCertPath(config.alipayRootCert );
		    DefaultAlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
			String reqStr = JSONObject.toJSONString(request);
			log.info("req:  " + reqStr);
			rtn.setResult(reqStr);
			AlipayResponse response = null;
			if (isPage) {
				response = alipayClient.pageExecute(request,"get");
			}else {
				response = alipayClient.certificateExecute(request);
			}
			log.info("res:  " + JSONObject.toJSONString(response));
			ZhiFuBaoResponse res = new ZhiFuBaoResponse();
			res.setData(response);
			res.setResultcode(response.getCode());
			res.setResultmsg(response.getMsg());
			rtn.setRtnData(res);
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			log.error("支付宝api调用出错（"+JSONObject.toJSONString(config)+","+JSONObject.toJSONString(request)+"）：",e);
		}
        return rtn;
    }
}
