package com.ym.mec.thirdparty.adapay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.huifu.adapay.AdaPay;
import com.huifu.adapay.demo.BaseDemo;
import com.huifu.adapay.demo.NotifyCallbackDemo;
import com.huifu.adapay.exception.BaseAdaPayException;
import com.huifu.adapay.model.DeviceInfo;
import com.huifu.adapay.model.payment.*;
import com.huifu.adapay.util.AdaPaySign;
import org.aspectj.apache.bcel.classfile.Module;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author jane.zhao
 */
public class Pay {
    private static final String appId = "app_7d87c043-aae3-4357-9b2c-269349a980d6";
    private static final String wxAppId = "wxcf8e8b33a9477845";

    /**
     * 运行支付类接口
     *
     * @return paymentId
     * @throws Exception 异常
     */
    public Pay() throws Exception {
        //apiKey，商户联调用
        String apiKey = "api_test_e640fa26-bbe6-458f-ac44-a71723ee2176";
        //apiKey，真实交易用（live）
        String apiKeyLive = "api_live_9c14f264-e390-41df-984d-df15a6952031";
        //公钥
        String pubKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCwN6xgd6Ad8v2hIIsQVnbt8a3JituR8o4Tc3B5WlcFR55bz4OMqrG/356Ur3cPbc2Fe8ArNd/0gZbC9q56Eb16JTkVNA/fye4SXznWxdyBPR7+guuJZHc/VW2fKH2lfZ2P3Tt0QkKZZoawYOGSMdIvO+WqK44updyax0ikK6JlNQIDAQAB";
        //私钥
        String privateKey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAMQhsygJ2pp4nCiDAXiqnZm6AzKSVAh+C0BgGR6QaeXzt0TdSi9VR0OQ7Qqgm92NREB3ofobXvxxT+wImrDNk6R6lnHPMTuJ/bYpm+sx397rPboRAXpV3kalQmbZ3P7oxtEWOQch0zV5B1bgQnTvxcG3REAsdaUjGs9Xvg0iDS2tAgMBAAECgYAqGFmNdF/4234Yq9V7ApOE1Qmupv1mPTdI/9ckWjaAZkilfSFY+2KqO8bEiygo6xMFCyg2t/0xDVjr/gTFgbn4KRPmYucGG+FzTRLH0nVIqnliG5Ekla6a4gwh9syHfstbOpIvJR4DfldicZ5n7MmcrdEwSmMwXrdinFbIS/P1+QJBAOr6NpFtlxVSGzr6haH5FvBWkAsF7BM0CTAUx6UNHb+RCYYQJbk8g3DLp7/vyio5uiusgCc04gehNHX4laqIdl8CQQDVrckvnYy+NLz+K/RfXEJlqayb0WblrZ1upOdoFyUhu4xqK0BswOh61xjZeS+38R8bOpnYRbLf7eoqb7vGpZ9zAkEAobhdsA99yRW+WgQrzsNxry3Ua1HDHaBVpnrWwNjbHYpDxLn+TJPCXvI7XNU7DX63i/FoLhOucNPZGExjLYBH/wJATHNZQAgGiycjV20yicvgla8XasiJIDP119h4Uu21A1Su8G15J2/9vbWn1mddg1pp3rwgvxhw312oInbHoFMxsQJBAJlyDDu6x05MeZ2nMor8gIokxq2c3+cnm4GYWZgboNgq/BknbIbOMBMoe8dJFj+ji3YNTvi1MSTDdSDqJuN/qS0=";

        //设置AdaPay全局参数，不同环境设置不同的apiKey/pubKey/privateKey
        AdaPay.apiKey = apiKeyLive;
        AdaPay.pubKey = pubKey;
        AdaPay.privateKey = privateKey;
        AdaPay.debug = true;

        //启动 mqtt 异步监听
        AdaPay.iNotifyCallback = new NotifyCallbackDemo();
        AdaPay.startNotifyListener();
    }

    public static String executePaymentTest() throws Exception {
        //test chargeId = "002112019080716223300005091372336111616";
        Pay demo = new Pay();
        //支付接口
        String orderNo = "jsdk_payment_" + System.currentTimeMillis();
        String payChannel = PayChannelEnum.ALIPAY_QR.getCode();
        BigDecimal amount = new BigDecimal("0.01");
        String orderSubject = "测试大雅订单";
        String orderBody = "测试大雅订单";
        Payment payment = demo.executePayment(amount, orderNo, payChannel, orderSubject, orderBody,null);
        //支付查询接口
        //demo.queryPayment(payment.getId());
        //关单接口
        //demo.closePayment(payment.getId());

        return payment.getId();
    }


    public Map<String, Object> getPayMap(BigDecimal amount, String orderNo, String notifyUrl, String orderSubject, String orderBody) throws Exception {

        Map<String, Object> paymentParams = new HashMap<>(10);
        paymentParams.put("appId", appId);
        paymentParams.put("amount", amount);
        paymentParams.put("orderNo", orderNo);
        paymentParams.put("notifyUrl", notifyUrl);
        paymentParams.put("orderSubject", orderSubject);
        paymentParams.put("orderBody", orderBody);
        paymentParams.put("wxAppId", wxAppId);
        String originalStr = JSONObject.toJSONString(paymentParams);

        String sign = AdaPaySign.sign(originalStr, AdaPay.privateKey);
        paymentParams.put("sign", sign);
        paymentParams.put("host", "http://192.168.3.27:8000/api-student/studentOrder/executePayment");
        paymentParams.remove(appId);
        return paymentParams;
    }

    public boolean verifySign(BigDecimal amount, String orderNo, String notifyUrl, String orderSubject, String orderBody, String sign) throws Exception {
        Map<String, Object> paymentParams = new HashMap<>(10);
        paymentParams.put("appId", appId);
        paymentParams.put("amount", amount);
        paymentParams.put("orderNo", orderNo);
        paymentParams.put("notifyUrl", notifyUrl);
        paymentParams.put("orderSubject", orderSubject);
        paymentParams.put("orderBody", orderBody);
        String originalStr = JSONObject.toJSONString(paymentParams);
        return AdaPaySign.verifySign(originalStr, sign, AdaPay.pubKey);
    }

    /**
     * 执行一个支付交易
     *
     * @return 创建的支付对象
     * @throws Exception 异常
     */
    public static Payment executePayment(BigDecimal amount, String orderNo, String payChannel, String orderSubject, String orderBody, String openid) throws Exception {
        System.out.println("=======execute payment begin=======");
        //创建支付对象的参数，全部参数请参考 https://docs.adapay.tech/api/04-trade.html#id3
        Map<String, Object> paymentParams = new HashMap<>(10);
        paymentParams.put("app_id", appId);
        paymentParams.put("order_no", orderNo);
        paymentParams.put("pay_channel", payChannel);
        paymentParams.put("pay_amt", amount);
        paymentParams.put("currency", CurrencyEnum.CNY.getCode());
        paymentParams.put("goods_title", orderSubject);
        paymentParams.put("goods_desc", orderBody);

//        DeviceInfo deviceInfo = new DeviceInfo();
//        deviceInfo.setDeviceType(DeviceTypeEnum.MOBILE.getCode());
//        deviceInfo.setDeviceIp("127.0.0.1");
//        paymentParams.put("device_info", deviceInfo);

//        List<GoodsDetail> goodsDetailList = new ArrayList<>();
//        GoodsDetail goodsDetail = new GoodsDetail();
//        goodsDetail.setGoodsId("your goods id");
//        goodsDetail.setGoodsName("your goods name");
//        goodsDetail.setQuantity("1");
//        goodsDetail.setPrice("100.00");
//        goodsDetailList.add(goodsDetail);
//
//        PromotionDetail promotionDetail = new PromotionDetail();
//        promotionDetail.setGoodsDetail(goodsDetailList);
//        promotionDetail.setCostPrice("100.00");

        if (openid != null && !openid.isEmpty()) {
            PaymentExpend expend = new PaymentExpend();
            expend.setOpenId(openid);
            paymentParams.put("expend", expend);
        }

        //调用sdk方法，创建支付，得到支付对象
        Payment payment = null;
        try {
            payment = Payment.create(paymentParams);
        } catch (BaseAdaPayException e) {
            e.printStackTrace();
        }
        System.out.println("payment result=" + JSON.toJSONString(payment));
        return payment;
    }

    /**
     * 关闭一个支付交易
     *
     * @param paymentId 要关闭的支付id
     * @return 关闭的支付对象
     * @throws Exception 异常
     */
    public Payment closePayment(String paymentId) throws Exception {
        System.out.println("=======close payment begin=======");
        //关闭支付对象的参数，全部参数请参考 https://docs.adapay.tech/api/04-trade.html#id11
        //调用sdk方法，关闭支付，得到支付对象
        Payment payment = null;
        try {
            payment = Payment.close(paymentId);
        } catch (BaseAdaPayException e) {
            e.printStackTrace();
        }
        System.out.println("close payment result=" + JSON.toJSONString(payment));
        return payment;
    }

    /**
     * 查询一个支付交易
     *
     * @param paymentId 要查询的支付id
     * @return 查询的支付对象
     * @throws Exception 异常
     */
    public Payment queryPayment(String paymentId) throws Exception {
        System.out.println("=======query payment begin=======");
        //查询支付对象的参数，全部参数请参考 https://docs.adapay.tech/api/04-trade.html#id7
        //调用sdk方法，查询支付交易，得到支付对象
        Payment payment = null;
        try {
            payment = Payment.query(paymentId);
        } catch (BaseAdaPayException e) {
            e.printStackTrace();
        }
        System.out.println("query payment result=" + JSON.toJSONString(payment));
        return payment;
    }
}
