package com.xhpc.payment.service.impl;

import cn.hutool.json.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.*;
import com.alipay.api.response.*;
import com.xhpc.common.core.web.domain.AjaxResult;
import com.xhpc.payment.service.AlipayInterface;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.Map;

@Service
public class AlipayService implements AlipayInterface {

    //@Autowired
    //private Environment environment;


    //String appid =environment.getProperty("ALIPAYAPPID");
    String appid = "2021002156615717";
    // 私钥
    //String private_key = environment.getProperty("ALIPAYPRIVATEKEY");
    String private_key = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCGHX1s315EKjoIBkNiF3IxCAmvtVg+TdCDL/XmJZWdcZ23tEWmmIMsLRCLUKsaPfTEhnqD6EFJnmpJu4teDImo3aDbOoO31YFEXjMXUnTTS/dtDVEo1OecsRL+Re43KSohOkIL1TMyTuNfeIglQTuhCSZ3LOEOx4OHpYwcrLp8p1ORvAS7x35nsmjLp3oQTJo9RWfzfEaKbm6cxsWLKyr5/5eGDXrUHNC5hIDLjoJbe6iqNKyIiPJHtPZfJ36PcWa7PFvx4X+Ded32KZb2AA3p9w/HX7gn1MnRfT5NGH0k3ggxLNarDU8g6JjQYgNtmE/R8gbp99BudZNfDoSF1llNAgMBAAECggEAaTa9bSoXM/bErALt3ghyx1B8+OGVpts5F5IKoVEe/PNjPfkpIzdGwONhtUnF0cKFQaAWgWE1xuGGlO2Sumevn1Cvnw1axF+1F8Om5UcE67cPFvh5kUTlpyGrutt1tMSQjpy7r7jEf1UwP3e5pzBz7TPWf2wv635OC56uOtivPJZ+8vg7VYon/mNXQuL4AavoxfSDtvo0ad30X2fK1WKeeBtgiT4UzV6ZGZh5igKQHM4lVvmbo/jOeQD0KAod7pRe/h4FBFmCVIWwgW+I+Hnzp8A/nJezoowJ3jiTt0FodC9uBCT64ZCz5dVCryD62LDVjKBxB7cfIoQA+PxCiXr9QQKBgQD+2v38J/MlfK/XCYldclzumizwIw6T0Mv6XvYwXQHYgYDKYNF6k1LhMEUo7fP3EsPdV8h/nXmdU4qadOVm6QSJ/rGEl22yGlO7woUzTY/Ls9eknoqfMYuyI1+ICMnNxmesQbWyc0cOHh44cEF+icfJxEDAmrHGLmBVsKuLUJUuVQKBgQCGt663TF7mixghiUOcT11zC1fqG+dIcvAwHpCHfdxsniYRqnv+SLf6eC5PCkQ5aNAAl/ywOLQAWS0XgYti3LyZ4iuGIYcUE0IDDmhWl68V27iXcLIK+rBRqBGxSdk8xR+zSE8fpO4mXpxn8SH0Butex8PJ+oHTbmdXIUAXdn6HGQKBgQCvAB1rqtsRoL72ADxtCHy78u5srwXxhmyqrc6LgzIjQzn2vejaLJO6wfSbmFnwDNimAwNQbgf2ekkwqphjxBozz8qB66GNrPpWccoZYmcdT48CIUO68MCmQBf3R2GbhWPnKu/ja7kc/p1tz9eJVn70E2kLWK4+EdZgwQHqlhj6SQKBgF4AmbdpYOb5s9Li1vyhHJIEHkpLQi15lkPdb/g7SK26BNJa5b5fu5DYf2fDwCtXCZ0AcN/+EQwVLbOzPzGy2R9/g+NKTdkiPvOnAAM8QH2+HaX+ix3CI3o3DnFpGF6hJieRkzR/f3Ximryks451rZMrTWEIncKMzSstFm3Izy0xAoGBAJQaMqlzpM+QaJiytJNeqRpPWRsi0Dkf4XqJXPWLOrApSISsafZF5vk2ZOeIqRsVCBH3LdfVIJxEBAF4l/Sd2q7xC9JHawJDqa4ea7VwL68ANH2w3jcJ3j6DQqf7NIe/lSGxYF6Jt+74oRFHxN3GDSf+z91DYfZz8hQnyphKDNEJ";
    // 公钥
    String alipay_public_key = "";
    // 应用公钥证书路径（app_cert_path 文件绝对路径）
    //String app_cert_path = environment.getProperty("CERTPATH");
    String app_cert_path = "E:\\dingxiang\\顶想\\充电桩\\支付宝\\12-9\\appCertPublicKey.crt";
    // 支付宝公钥证书文件路径（alipay_cert_path 文件绝对路径），支付宝CA根证书文件路径（alipay_root_cert_path文件绝对路径）
    //String alipay_cert_path = environment.getProperty("PUBLICCERTPATH");
    String alipay_cert_path = "E:\\dingxiang\\顶想\\充电桩\\支付宝\\12-9\\alipayCertPublicKey_RSA2.crt";
    // 支付宝CA根证书文件路径（alipay_root_cert_path 文件绝对路径）
    //String alipay_root_cert_path = environment.getProperty("ROOTCRETPATH");
    String alipay_root_cert_path = "E:\\dingxiang\\顶想\\充电桩\\支付宝\\12-9\\alipayRootCert.crt";
    CertAlipayRequest certAlipayRequest = new CertAlipayRequest();


    public AlipayService() {
        certAlipayRequest.setServerUrl("https://openapi.alipay.com/gateway.do");
        certAlipayRequest.setAppId(appid);
        certAlipayRequest.setPrivateKey(private_key);
        certAlipayRequest.setFormat("json");
        certAlipayRequest.setCharset("utf-8");
        certAlipayRequest.setSignType("RSA2");
        certAlipayRequest.setCertPath(app_cert_path);
        certAlipayRequest.setAlipayPublicCertPath(alipay_cert_path);
        certAlipayRequest.setRootCertPath(alipay_root_cert_path);

    }

    /**
     * @param subject        交易标题
     * @param timeoutExpress 有效时间
     * @param notifyUrl      回调路径
     * @param orderId        订单编号
     * @param actualPay      支付金额
     * @throws AlipayApiException
     */
    @Override
    public String getSign(String subject, String timeoutExpress, String notifyUrl, String orderId, String actualPay)
            throws AlipayApiException {
        DefaultAlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
        // 实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        // SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setSubject(subject);
        model.setOutTradeNo(orderId);
        model.setTimeoutExpress(timeoutExpress);
        model.setTotalAmount(actualPay + "");
        model.setProductCode("QUICK_MSECURITY_PAY");
        request.setBizModel(model);
        request.setNotifyUrl(notifyUrl);
        try {
            // 这里和普通的接口调用不同，使用的是sdkExecute
            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
            return response.getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * APP 充值 支付宝回调验签 公共方法
     */
    @Override
    public boolean reaCert(Map<String, String> params) throws AlipayApiException {
        return AlipaySignature.rsaCertCheckV1(params, alipay_cert_path, "utf-8", "RSA2");
    }

    /**
     * APP 充值 验证公共参数部分是否正确 公共方法
     */
//    @Override
//    public boolean verific(AlipayLog log, Integer type) {
//        String seller_email = Configuration.getConfig().getValue("seller_email");
//        // 判断 回调里卖家支付宝账号 是否为系统卖家支付宝ID
//        if (!seller_email.equals(log.getSellerEmail())) {
//            return false;
//        }
//        // 判断APPID 是否为系统的APPID
//        String alipau_appKey = Configuration.getConfig().getValue("alipau_appKey");
//        if (!alipau_appKey.equals(log.getAuthAppId())) {
//            return false;
//        }
//        return true;
//    }

    /**
     * 支付宝分账关系绑定接口
     *
     * @param account      分账方账号 （登陆账号 或 用户号）
     * @param type         分账类型 （分账方类型。userId：表示是支付宝账号对应的支付宝唯一用户号；loginName：表示是支付宝登录号 ）
     * @param name         分账方全称
     * @param outRequestNo 外部请求号。32个字符以内，可包含字母、数字、下划线。需保证在商户端不重复。
     * @throws AlipayApiException
     */
    @Override
    public AjaxResult bindPaypal(String account, String type, String name, String outRequestNo) throws AlipayApiException {
        DefaultAlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
        AlipayTradeRoyaltyRelationBindRequest request = new AlipayTradeRoyaltyRelationBindRequest();
        request.setBizContent("{" +
                "\"receiver_list\":[{" +
                "\"type\":\""+type+"\"," +
                "\"account\":\""+account+"\"," +
                "\"name\":\""+name+"\"," +
                "\"memo\":\"分账给测试商户\"" +
                "}]," +
                "\"out_request_no\":\""+outRequestNo+"\"" +
                "}");
        System.out.println(request.getBizContent());
        AlipayTradeRoyaltyRelationBindResponse response = alipayClient.certificateExecute(request);
        System.out.println(response.getBody());
        if (response.isSuccess()) {
            return AjaxResult.success(response);
        } else {
            return AjaxResult.success(response);
        }
    }

    /**
     * 支付宝分账关系解绑接口
     *
     * @param account      分账方账号 （登陆账号 或 用户号）
     * @param type         分账类型 （分账方类型。userId：表示是支付宝账号对应的支付宝唯一用户号；loginName：表示是支付宝登录号 ）
     * @param name         分账方全称
     * @param outRequestNo 外部请求号。32个字符以内，可包含字母、数字、下划线。需保证在商户端不重复。
     * @throws AlipayApiException
     */

    @Override
    public AjaxResult unBindPaypal(String account, String type, String name, String outRequestNo)
            throws AlipayApiException {
        DefaultAlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
        AlipayTradeRoyaltyRelationUnbindRequest request = new AlipayTradeRoyaltyRelationUnbindRequest();
        request.setBizContent("{" +
                "\"receiver_list\":[{" +
                "      \"type\":\""+type+"\"," +
                "      \"account\":\""+account+"\"," +
                "\"memo\":\"分账给测试商户\"" +
                "        }]," +
                "\"out_request_no\":\""+outRequestNo+"\"" +
                "  }");
        AlipayTradeRoyaltyRelationUnbindResponse response = alipayClient.certificateExecute(request);
        if (response.isSuccess()) {
            return AjaxResult.success(response);
        } else {
            return AjaxResult.success(response);
        }
    }

    @Override
    public AjaxResult batchquery(Integer pageNum, Integer pageSize, String outRequestNo) throws AlipayApiException {
        DefaultAlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
        AlipayTradeRoyaltyRelationBatchqueryRequest  request = new AlipayTradeRoyaltyRelationBatchqueryRequest ();
        request.setBizContent("{" +
                "\"out_request_no\":\""+outRequestNo+"\"" +
                "}");
        System.out.println(request.getBizContent());
        AlipayTradeRoyaltyRelationBatchqueryResponse  response = alipayClient.certificateExecute(request);
        System.out.println(response);
        System.out.println(response.getBody());
        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        return AjaxResult.success(response);
    }

    /**
     * 支付宝分账接口
     *
     * @param outRequestNo 外部请求号。32个字符以内，可包含字母、数字、下划线。需保证在商户端不重复。
     * @param tradeNo      支付宝订单号
     * @param transIn      收入方账户。如果收入方账户类型为userId，本参数为收入方的支付宝账号对应的支付宝唯一用户号，
     *                     以2088开头的纯16位数字；如果收入方类型为cardAliasNo，本参数为收入方在支付宝绑定的卡编号；
     *                     如果收入方类型为loginName，本参数为收入方的支付宝登录号；
     * @param amount       分账金额
     * @throws AlipayApiException
     */
    @Override
    public boolean settlePaypal(String outRequestNo, String tradeNo, String transIn, BigDecimal amount)
            throws AlipayApiException {
        DefaultAlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
        AlipayTradeOrderSettleRequest request = new AlipayTradeOrderSettleRequest();
        request.setBizContent("{\"out_request_no\":\"" + outRequestNo + "\",\"trade_no\":\"" + tradeNo + "\",\"royalty_parameters\":[{\"trans_in\":\"" + transIn + "\",\"amount\":" + amount + ",\"trans_in_type\":\"userId\"}]}");
        AlipayTradeOrderSettleResponse response = alipayClient.certificateExecute(request);

        if (response.isSuccess()) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public AjaxResult query(String outTradeNo, String tradeNo) throws AlipayApiException {
      try{
          DefaultAlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
          AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
          JSONObject bizContent = new JSONObject();
          //商户订单号
          //bizContent.put("out_trade_no", "20150320010101001");
          //支付宝交易号
          bizContent.put("trade_no", tradeNo);
          request.setBizContent(bizContent.toString());
          AlipayTradeQueryResponse response = alipayClient.certificateExecute(request);
          if(response.isSuccess()){
              System.out.println("调用成功");
              return AjaxResult.success(response.getBody());
          } else {
              System.out.println("调用失败");
              return AjaxResult.success();
          }
      }catch (Exception e){
          e.printStackTrace();
      }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult refund(String outTradeNo, String tradeNo, BigDecimal refundAmount, String transInType, String transIn, String desc) throws AlipayApiException {
        DefaultAlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("trade_no", tradeNo);
        bizContent.put("refund_amount", refundAmount);
        //bizContent.put("out_request_no", "HZ01RF001");

        //// 返回参数选项，按需传入
        //JSONArray queryOptions = new JSONArray();
        //queryOptions.add("refund_detail_item_list");
        //bizContent.put("query_options", queryOptions);

        request.setBizContent(bizContent.toString());
        AlipayTradeRefundResponse response = alipayClient.certificateExecute(request);
        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }


        return null;
    }

    @Override
    public AjaxResult refundQuery(String outTradeNo, String tradeNo, BigDecimal refundAmount, String transInType, String transIn, String desc) throws AlipayApiException {
        DefaultAlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
        AlipayTradeFastpayRefundQueryRequest request = new AlipayTradeFastpayRefundQueryRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("trade_no", tradeNo);
        bizContent.put("out_request_no", "HZ01RF001");
        request.setBizContent(bizContent.toString());
        AlipayTradeFastpayRefundQueryResponse response = alipayClient.certificateExecute(request);
        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        return null;
    }

    /**
     * 支付宝转账接口
     *
     * @param outBizNo    商户端的唯一订单号，对于同一笔转账请求，商户需保证该订单号唯一。
     * @param transAmount 订单总金额，单位为元，精确到小数点后两位，
     * @param orderTitle  转账业务的标题，用于在支付宝用户的账单里显示
     * @param identity    参与方的唯一标识
     * @param name        参与方真实姓名，如果非空，将校验收款支付宝账号姓名一致性。当identity_type=ALIPAY_LOGON_ID时，本字段必填。
     * @throws AlipayApiException
     */
    @Override
    public boolean transfer(String outBizNo, BigDecimal transAmount, String orderTitle, String identity, String name) throws AlipayApiException {
        DefaultAlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
        AlipayFundTransUniTransferRequest request = new AlipayFundTransUniTransferRequest();
        request.setBizContent("{\"out_biz_no\":\"" + outBizNo + "\",\"trans_amount\":" + transAmount + ",\"product_code\":\"TRANS_ACCOUNT_NO_PWD\",\"order_title\":\"" + orderTitle + "\",\"biz_scene\":\"DIRECT_TRANSFER\",\"payee_info\":{\"identity\":\"" + identity + "\",\"identity_type\":\"ALIPAY_LOGON_ID\",\"name\":\"" + name + "\"}}");
        AlipayFundTransUniTransferResponse response = alipayClient.certificateExecute(request);
        if (response.isSuccess()) {
            return true;
        } else {
            return false;
        }

    }

    @Override
    public String Precreate(String outTradeNo, BigDecimal totalAmount, String subject, String sellerId) throws AlipayApiException, IOException {
        DefaultAlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();//创建API对应的request
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + outTradeNo + "\",\"total_amount\":" + totalAmount + ",\"subject\":\"" + subject + "\",\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        alipayRequest.setReturnUrl("这里是跳转页面");
        alipayRequest.setNotifyUrl("这里是返回通知路径");
        String form = "";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return form;
    }
}

