package cn.com.ty.lift.common.aliservice.alipay;

import com.alipay.api.AlipayApiException;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayFundTransUniTransferRequest;
import com.alipay.api.request.AlipayTradeCancelRequest;
import com.alipay.api.request.AlipayTradeCreateRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayFundTransUniTransferResponse;
import com.alipay.api.response.AlipayTradeCancelResponse;
import com.alipay.api.response.AlipayTradeCreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

public class AlipayUtil {
    private static String appId = "2016101500691469";
    //应用私匙
    private static String privateKey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCuUJBSbA240jwqaqrv0xptBJqEzLmCyA0DRzBx6y2dzADq93wTd1xTD2YYwQmQQetJPl9D5czbP7ziwaqXXoDdtDjz3dFQvqaKuiEFw6E2mo8Q2WLM2rn7gmBUw1llo0blJhiLWKhceXtxNTi0oeYH1ZH/xAIinI5BqMvAWcHDr19BA4t6Kvcrw3ZmwkyWaNt8jMQsxRImr5JrF+5OBbUnzzpckx6quGlosVetmMZGQS/TCPybmY7X8qYXvtnMEteBkCLGd3o9ngHwOMUQFw1ARd1NFD49i1r4OMhhoWjVfqGh1dV7RGE9r7EAp1yjsMpz8g+6eZGLbS6VB7qCL7xlAgMBAAECggEAXxyIUuCwcAsOVxqSoH7wKVHcud82zZw4NXSvg0kOP85jJdHZuoljL9L0I0eY30SIjBNjSZnmuC7D8no3iZY//Dhs5us+Xa9ZEdLTV+DRYwjcTRZAKYSi/A+8XiOk8KcxdLDfrZC3dJW4fCHNCgpYiCfJHOQnQhloKX1fh1myNwHb19bvXqNxmeHQi2LNzMA9V9z4DP9k4BMYpzRe65KsVZAwq93zWNeVRO9R0rfI+Dx6S0mil7gQcrAxW+SfyprbImZy8I+66TwXyhzhmhRqTLFp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fnYLLpV/yxMUZcoWNdUsL/dZOyigYk+gemHArMCvpT7w3ajJkbKy4MUi4hePkRi1/8NKCkqQ0q3+qpdtiES0crQ7nq4IxKQzEz0c9TSWLkwbMq/gCw1eEmmkL+1Vvf93RMDYD5MrBrx9bVM8QL9lnHXq+5NSWa6sxUrgEwUUj/OlIGCyoUClYr6fFHeeI/NiSy7TmVSOtfHllRwms1TAS/KWE2d+A2/ua8Yznb63I6yTSbNKl1pEqjRRSgoDZSF8Ee8ugC/wR9a1Dtnzzbr+ktzzgs75neGNIlbhiwIDAQAB";
    //接口地址
    private static String gateway = "https://openapi.alipaydev.com/gateway.do";
    //参数编码格式
    private static String charSet = "utf-8";
    //加密算法方式
    private static String signType = "RSA2";
    //买家id
    private static String buyerId = "2088102180079574";
    //买家账号
    private static String buyerLogonId = "bdlcph6736@sandbox.com";
    //卖家id
    private static String sellerId = "2088102179670843";

    private static DefaultAlipayClient client;

    /*** @param 买家id，自定义订单号，商品名，商品说明，商品总价
     * @return 支付宝的订单编号
     * @description
     * @date 2019/12/25 9:14
     */
    static {
        CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
        certAlipayRequest.setServerUrl(gateway);
        certAlipayRequest.setAppId(appId);
        certAlipayRequest.setPrivateKey(privateKey);
        certAlipayRequest.setFormat("json");
        certAlipayRequest.setCharset("utf-8");
        certAlipayRequest.setSignType("RSA2");
        String path = "D:/Documents/支付宝开放平台开发助手/CSR/";
//        String path = "C:/Users/admin/Desktop/temp/";
        certAlipayRequest.setCertPath(path + "appCertPublicKey_2016101500691469.crt");
        certAlipayRequest.setAlipayPublicCertPath(path + "alipayCertPublicKey_RSA2.crt");
        certAlipayRequest.setRootCertPath(path + "alipayRootCert.crt");
        try {
            client = new DefaultAlipayClient(certAlipayRequest);
        } catch (AlipayApiException e) {
            System.out.println("支付宝连接失败");
            e.printStackTrace();
        }
    }

    public static String create(String buyerLogonId, String outTradeNo, String subject, String body, BigDecimal totalAmount) throws AlipayApiException {
        AlipayTradeCreateRequest request = new AlipayTradeCreateRequest();
        request.setBizContent("{" +
                "\"method\":\"alipay.trade.app.pay\"," +
                "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
                "\"out_trade_no\":\"" + outTradeNo + "\"," +
                "\"seller_id\":\"" + sellerId + "\"," +
                "\"total_amount\":\"" + totalAmount.toString() + "\"," +
                "\"buyer_logon_id\":\"" + buyerLogonId + "\"," +
                "\"subject\":\"" + subject + "\"," +
                "\"body\":\"" + body + "\"" +
                "  }");
        //"\"buyer_id\":\"" + buyerId + "\"," +
        client.certificateExecute(request);
        AlipayTradeCreateResponse response = client.certificateExecute(request);
        if (response.isSuccess()) {
            return response.getTradeNo();
        } else {
            return null;
        }
    }

    public static boolean cancel(String tradeNo) throws AlipayApiException {
        AlipayTradeCancelRequest request = new AlipayTradeCancelRequest();
        request.setBizContent("{" +
                "\"trade_no\":\"" + tradeNo + "\"" +
                "}");
        AlipayTradeCancelResponse response = client.certificateExecute(request);
        return "close".equals(response.getAction());
    }

    /**
     * @return 提现成功返回单号 提现失败返回null
     * @description
     * @date 2019/12/26 14:51
     * // @param收款人id，自定义提现单号，提现标题，提现总金额,备注
     */
    public static String withdraw(String identity, String outTradeNo, String orderTitle, BigDecimal transAmount) throws AlipayApiException {
        AlipayFundTransUniTransferRequest request = new AlipayFundTransUniTransferRequest();
        request.setBizContent("{" +
                "\"out_biz_no\":\"" + outTradeNo + "\"," +
                "\"trans_amount\":" + transAmount.toString() + "," +
                "\"product_code\":\"TRANS_ACCOUNT_NO_PWD\"," +
                "\"biz_scene\":\"DIRECT_TRANSFER\"," +
                "\"order_title\":\"" + orderTitle + "\"," +
                "\"payee_info\":{" +
                "\"identity\":\"" + identity + "\"," +
                "\"identity_type\":\"ALIPAY_USER_ID\"" +
                "    }," +
                "\"business_params\":\"{\\\"payer_show_name\\\":\\\"天域梯业\\\"}\"," +
                "  }");
        AlipayFundTransUniTransferResponse response = client.certificateExecute(request);
        if (response.isSuccess()) {
            return response.getOrderId();
        } else {
            return null;
        }
    }

    /**
     * //* @param 商家自定义的订单编号，创建订单时支付宝的订单编号
     *
     * @return 已支付返回true，其它返回false
     * @description
     * @date 2019/12/25 11:00
     */
    public static Map<String, Object> order(String tradeNo) throws AlipayApiException {
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        request.setBizContent("{" +
                "\"trade_no\":\"" + tradeNo + "\"" +
                "}");
        AlipayTradeQueryResponse response = client.certificateExecute(request);
        HashMap<String, Object> result = new HashMap<>();
        if (response.getTradeStatus() == null) {
            result.put("status", false);
            return result;
        }
        result.put("status", response.getTradeStatus().equals("TRADE_SUCCESS"));
        result.put("alipayId", response.getBuyerUserId());
        return result;
    }

    public static void main(String[] args) throws AlipayApiException {
//        if ((Boolean) AlipayUtil.order("2019123022001479571000092593").get("status")) {
//            System.out.println("已支付");
//        } else {
//            System.out.println("未支付");
//        }
//        System.out.println(AlipayUtil.cancel("2019123022001479571000093711"));
//        System.out.println(AlipayUtil.create(buyerLogonId, IdWorker.getIdStr(), "2019123016001", "电梯性能说明", new BigDecimal("100.00")));
        //        AlipayUtil.withdraw(buyerId, IdWorker.getIdStr(), "电梯5号", new BigDecimal("100.00"), "电梯提现");
//        AlipayUtil.getUserId();
    }

//    public static String getUserId() throws AlipayApiException {
//        AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
//        request.setBizModel(new AlipayObject() {
//        String method = "alipay.user.info.share";
//        });
//
//        AlipaySystemOauthTokenResponse response = client.certificateExecute(request);
//        response.getUserId();
//        return "123";
//    }
}