package com.bohuikeji.delivery.backstage.pay;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.*;
import com.alipay.api.domain.*;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.*;
import com.alipay.api.response.*;
import com.bohuikeji.delivery.backstage.entity.AliPayConfig;
import com.bohuikeji.delivery.backstage.entity.AliPayV2Config;
import com.bohuikeji.delivery.backstage.entity.TPay;
import com.bohuikeji.frame.module.admin.component.StaticComponent;
import com.bohuikeji.frame.module.admin.entity.vo.AlipayVo;
import com.bohuikeji.frame.module.admin.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 支付宝支付请求类
 */
@Slf4j
public class AliPayV2 {

    /**
     * 支付宝： 同城急送平台小程序公钥证书加签方式
     */
    public static class aliClientPlatform {
        public static AlipayClient alipayBycodeClient;
        static {
            CertAlipayRequest certAlipayRequest = new CertAlipayRequest ();
            certAlipayRequest.setServerUrl("https://openapi.alipay.com/gateway.do");
            certAlipayRequest.setAppId(AliPayV2Config.AliClientID);
            certAlipayRequest.setPrivateKey(AliPayV2Config.APP_PRIVATE_KEY);
            certAlipayRequest.setFormat("json");
            certAlipayRequest.setCharset("GBK");
            certAlipayRequest.setSignType("RSA2");
            certAlipayRequest.setCertPath(AliPayV2Config.appclientCertPath);
            certAlipayRequest.setAlipayPublicCertPath(AliPayV2Config.alipayclientCertPath);
            certAlipayRequest.setRootCertPath(AliPayV2Config.alipayclientRootCertPath);
            try {
                alipayBycodeClient = new DefaultAlipayClient(certAlipayRequest);
            } catch (AlipayApiException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 支付宝: 同城急送官方小程序公钥证书加签方式
     */
    public static class aliClientOfficial {
        public static AlipayClient alipayBycodeClient;
        static {
            CertAlipayRequest certAlipayRequest = new CertAlipayRequest ();
            certAlipayRequest.setServerUrl("https://openapi.alipay.com/gateway.do");
            certAlipayRequest.setAppId(AliPayV2Config.appID);
            certAlipayRequest.setPrivateKey(AliPayV2Config.privateKey);
            certAlipayRequest.setFormat("json");
            certAlipayRequest.setCharset("GBK");
            certAlipayRequest.setSignType("RSA2");
            certAlipayRequest.setCertPath(AliPayV2Config.appCertPath);
            certAlipayRequest.setAlipayPublicCertPath(AliPayV2Config.alipayCertPath);
            certAlipayRequest.setRootCertPath(AliPayV2Config.alipayRootCertPath);
            try {
                alipayBycodeClient = new DefaultAlipayClient(certAlipayRequest);
            } catch (AlipayApiException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 支付宝: 同城急送小程序公钥证书加签方式
     */
    public static class aliClientTcjsicial {
        public static AlipayClient alipayBycodeClient;
        static {
            CertAlipayRequest certAlipayRequest = new CertAlipayRequest ();
            certAlipayRequest.setServerUrl("https://openapi.alipay.com/gateway.do");
            certAlipayRequest.setAppId(AliPayV2Config.AliID);
            certAlipayRequest.setPrivateKey(AliPayV2Config.ALI_PRIVATE_KEY);
            certAlipayRequest.setFormat("json");
            certAlipayRequest.setCharset("GBK");
            certAlipayRequest.setSignType("RSA2");
            certAlipayRequest.setCertPath(AliPayV2Config.aliClientCertPath);
            certAlipayRequest.setAlipayPublicCertPath(AliPayV2Config.aliPayClientCertPath);
            certAlipayRequest.setRootCertPath(AliPayV2Config.aliClientRootCertPath);
            try {
                alipayBycodeClient = new DefaultAlipayClient(certAlipayRequest);
            } catch (AlipayApiException e) {
                e.printStackTrace();
            }
        }
    }



    /**
     * 支付宝小程序支付
     * @param payNum
     * @param orderFactPrice
     * @param userId
     * @return
     */
    public static JSONObject alipayClient (String payNum,String channelType,String orderFactPrice,String userId) {
        AlipayTradeCreateRequest request = new AlipayTradeCreateRequest();
        request.setNotifyUrl(StaticComponent.ALIPAY_NOTIFY_URL);
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", payNum);
        bizContent.put("total_amount",orderFactPrice);
        bizContent.put("subject", "同城急送");
        bizContent.put("buyer_id", userId);
        bizContent.put("timeout_express", "90m");
        request.setBizContent(bizContent.toString());
        JSONObject orderStr = null;
        AlipayTradeCreateResponse response = null;
        try {
            if("官方平台".equals(channelType)){
                response = aliClientPlatform.alipayBycodeClient.certificateExecute(request);
            }
            if("急送平台".equals(channelType)){
                response = aliClientOfficial.alipayBycodeClient.certificateExecute(request);
            }
            if("同城急送".equals(channelType)){
                log.info("过来了吗");
                response = aliClientTcjsicial.alipayBycodeClient.certificateExecute(request);
            }
            orderStr = JSONObject.parseObject(response.getBody()).getJSONObject("alipay_trade_create_response");
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return orderStr;
    }

    /**
     * 支付宝小程序退款
     * @param orderNum
     * @param orderFactPrice
     * @param trade_no
     * @param refundReason
     * @param out_request_no
     * @return
     */
    public static JSONObject clientRefundV2(String orderNum,String channelType,String orderFactPrice,String trade_no, String refundReason,String out_request_no) {
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderNum);
        bizContent.put("trade_no", trade_no);
        bizContent.put("refund_amount", orderFactPrice);
        bizContent.put("refund_reason", refundReason);
        bizContent.put("out_request_no", out_request_no);
        request.setBizContent(bizContent.toString());
        AlipayTradeRefundResponse response = null;
        try {
            if("官方平台".equals(channelType)){
                response = aliClientOfficial.alipayBycodeClient.certificateExecute(request);
            }
            if("急送平台".equals(channelType)){
                response = aliClientPlatform.alipayBycodeClient.certificateExecute(request);
            }
            if("同城急送".equals(channelType)){
                response = aliClientTcjsicial.alipayBycodeClient.certificateExecute(request);
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if(response.isSuccess()){
            return JSONObject.parseObject(response.getBody()).getJSONObject("alipay_trade_refund_response");
        }
        return null;
    }


    /**
     * 支付宝小程序获取UserId信息
     * @param code
     * @return
     * @throws AlipayApiException
     */
    public static JSONObject getUserId(String code,String channelType) throws AlipayApiException {
        log.error("渠道类型3：{}",channelType);
        AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
        request.setGrantType("authorization_code");
        request.setCode(code);
        AlipaySystemOauthTokenResponse response = null;
        if("官方平台".equals(channelType)){
            response = aliClientOfficial.alipayBycodeClient.certificateExecute(request);
        }
        if("急送平台".equals(channelType)){
            response = aliClientPlatform.alipayBycodeClient.certificateExecute(request);
        }
        if("同城急送".equals(channelType)){
            response = aliClientTcjsicial.alipayBycodeClient.certificateExecute(request);
        }
        if("客户端小程序（支付宝）".equals(channelType)){
            response = AliPay.aliClient.alipayBycodeClient.certificateExecute(request);
        }
        if(response.isSuccess()){
            String body = response.getBody();
            if(!StringUtils.isEmpty(body)){
                JSONObject jsonObject = JSONObject.parseObject(body);
                JSONObject object = jsonObject.getJSONObject(AliPayConfig.ALIPAY_SYSTEM_OAUTH_TOKEN_RESPONSE);
                return object;
            }
        } else {
        }
        return null;
    }



}
