package com.izouma.nineth.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.huifu.adapay.Adapay;
import com.huifu.adapay.core.exception.BaseAdaPayException;
import com.huifu.adapay.model.AdapayCommon;
import com.huifu.adapay.model.MerConfig;
import com.huifu.adapay.model.Payment;
import com.huifu.adapay.model.Refund;
import com.izouma.nineth.utils.SnowflakeIdWorker;
import com.izouma.nineth.utils.excel.BigIntegerConverter;
import com.izouma.nineth.utils.excel.LocalDateConverter;
import com.izouma.nineth.utils.excel.LocalDateTimeConverter;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AdapayServiceTest {
    private final String appId = "app_f8760acc-f4d8-46f6-8f70-d80e36517075";

    public AdapayServiceTest() {
        Adapay.debug = true;
        Adapay.prodMode = true;

        MerConfig merConfig = new MerConfig();
        merConfig.setApiKey("api_live_8818cac1-894b-40bc-ac77-803e02e9c260");
        merConfig.setApiMockKey("api_test_0b1b0eb9-30e1-4acd-8e03-10b529de1856");
        merConfig.setRSAPrivateKey("MIIEuwIBADANBgkqhkiG9w0BAQEFAASCBKUwggShAgEAAoIBAQCnIaIrFP598qcf/s3FqXxMTjrVAevnf1w5CAMdJqcRFv0WvdLEmNRxxqAYSLl/iQ8AyU4yqVwkwYqvn/aENBg0iQ5h5qboxb8T6xmrZLctk97TiIuCUwbd7Q5NBHJXzHlaKc1p1KBvTCJDMw8+t0Jh3sBkBvu7l0KPliEQHtPLBDkKvy3NBQD6BMy47kPersjSUH53HBvNpcjcPZGpUX/TmL3SNkS98RkoebFxuorK5UdazYN5xvarjfcYziShIjU3WIZJb52DGUxYWTk6vJKZrJhw7AhWIEQpH7qJxvml/B8RMQ4guHdtp3ojxwkHDt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AMDwg0ebzBEZsV2cr/Er2b25LsXteDJ+V67plBNrv+A1/omA9a52sWek4bY0D+Uu6zPTDaLj9BhHC2wJmThYl0eLRKyDKYQslBR3h253Gsn3If6RH9/tSyDsQ88iAEI1f6QH27bGHL9VDrsLGEFg5E7ZEzFQuJPqoUvBOoURNwa6");
        merConfig.setRSAPublicKey("MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApyGiKxT+ffKnH/7Nxal8TE461QHr539cOQgDHSanERb9Fr3SxJjUccagGEi5f4kPAMlOMqlcJMGKr5/2hDQYNIkOYeam6MW/E+sZq2S3LZPe04iLglMG3e0OTQRyV8x5WinNadSgb0wiQzMPPrdCYd7AZAb7u5dCj5YhEB7TywQ5Cr8tzQUA+gTMuO5D3q7I0lB+dxwbzaXI3D2RqVF/05i90jZEvfEZKHmxcbqKyuVHWs2Decb2q433GM4koSI1N1iGSW+dgxlMWFk5OrySmayYcOwIViBEKR+6icb5pfwfETEOILh3bad6I8cJBw7WXT1Pa2PIuhB8G2uKjmIKGwIDAQAB");
        Adapay.publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCwN6xgd6Ad8v2hIIsQVnbt8a3JituR8o4Tc3B5WlcFR55bz4OMqrG/356Ur3cPbc2Fe8ArNd/0gZbC9q56Eb16JTkVNA/fye4SXznWxdyBPR7+guuJZHc/VW2fKH2lfZ2P3Tt0QkKZZoawYOGSMdIvO+WqK44updyax0ikK6JlNQIDAQAB";
        try {
            Adapay.initWithMerConfig(merConfig);
        } catch (Exception e) {
        }
    }

    @Test
    public void testPay() throws BaseAdaPayException {
        Map<String, Object> paymentParams = new HashMap<String, Object>(10);
        List<Map<String, Object>> divMembers = new ArrayList<>();
        divMembers.add(new HashMap<>() {{
            put("member_id", "0");
            put("amount", BigDecimal.valueOf(0.05));
            put("fee_flag", "Y");
        }});
        divMembers.add(new HashMap<>() {{
            put("member_id", "1110");
            put("amount", BigDecimal.valueOf(0.05));
        }});

        paymentParams.put("app_id", appId);
        paymentParams.put("order_no", "jsdk_payment" + System.currentTimeMillis());
        paymentParams.put("pay_channel", "wx_pub");
        paymentParams.put("pay_amt", "0.10");
        paymentParams.put("goods_title", "your goods title");
        paymentParams.put("goods_desc", "your goods desc");
        paymentParams.put("notify_url", "http://9th.frp.izouma.com/notify/adapay/order/1");
        paymentParams.put("description", "orderId=1");

        Map<String, Object> expend = new HashMap<>();
        expend.put("open_id", "oWJG55wLnwdVzXoKka1-DzQKOd_Y");
        paymentParams.put("expend", expend);

        Map<String, Object> payment = Payment.create(paymentParams);
        System.out.println("payment result=" + JSON.toJSONString(payment, SerializerFeature.PrettyFormat));
    }

    @Test
    public void testWxPay() throws BaseAdaPayException {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("order_no", "host_wx_lite_params_sdk_" + System.currentTimeMillis());
        params.put("adapay_func_code", "wxpay.createOrder");
        params.put("pay_amt", "0.02");
        params.put("app_id", appId);
        params.put("currency", "cny");
        params.put("goods_title", "Your goods_title");
        params.put("goods_desc", "Your goods_desc");
        params.put("description", "payment Discription");
        params.put("callback_url", "/9th/orders");
        Map<String, Object> response = AdapayCommon.requestAdapayUits(params);
        System.out.println("payment result=" + JSON.toJSONString(response, SerializerFeature.PrettyFormat));
    }

    @Data
    public static class RefundOrder {
        @ExcelProperty("交易时间")
        private LocalDateTime time;

        @ExcelProperty("订单号")
        private String id;

        @ExcelProperty("支付流水号")
        private String serial;

        @ExcelProperty("第三方订单号")
        private String thirdId;

        @ExcelProperty("支付宝/微信订单号")
        private String txId;

        @ExcelProperty("交易金额")
        private String amount;

        private String refundId;
    }

    @Test
    public void refund() throws BaseAdaPayException {
        List<RefundOrder> orders = EasyExcel.read("/Users/drew/Downloads/merTransDetail_0284905900625472_20211201_20211215_1639557451.xlsx")
                .head(RefundOrder.class)
                .registerConverter(new LocalDateConverter())
                .registerConverter(new LocalDateTimeConverter())
                .registerConverter(new BigIntegerConverter())
                .sheet().doReadSync();
        System.out.println(orders.size());
        for (RefundOrder order : orders) {
            String refundId = new SnowflakeIdWorker(0, 0).nextId() + "";
            Map<String, Object> refundParams = new HashMap<>();
            refundParams.put("refund_amt", order.getAmount());
            refundParams.put("refund_order_no", new SnowflakeIdWorker(0, 0).nextId() + "");
            Map<String, Object> response = Refund.create(order.getId(), refundParams);
            order.setRefundId(refundId);
        }
        EasyExcel.write("/Users/drew/Desktop/refund.xlsx", RefundOrder.class).sheet("sheet")
                .registerConverter(new LocalDateConverter())
                .registerConverter(new LocalDateTimeConverter())
                .registerConverter(new BigIntegerConverter())
                .doWrite(orders);
    }


    @Test
    public void queryrefund() throws BaseAdaPayException {
        List<RefundOrder> orders = EasyExcel.read("/Users/drew/Desktop/refund.xlsx")
                .head(RefundOrder.class)
                .registerConverter(new LocalDateConverter())
                .registerConverter(new LocalDateTimeConverter())
                .registerConverter(new BigIntegerConverter())
                .sheet().doReadSync();
        System.out.println(orders.size());
        List<String> success = new ArrayList<>();
        List<String> fail = new ArrayList<>();
        for (RefundOrder order : orders) {
            Map<String, Object> refundParams = new HashMap<>();
            refundParams.put("refund_order_no", order.getRefundId());
            Map<String, Object> refund = Refund.query(refundParams);
            System.out.println(refund.get("refunds"));
            try {
                if (((JSONArray) refund.get("refunds")).getJSONObject(0).getString("trans_status").equals("S")) {
                    success.add(order.getId());
                } else {
                    fail.add(order.getId());
                }
            } catch (Exception e) {
                fail.add(order.getId());
            }
        }
        System.out.println("success:" + success.size());
        System.out.println("fail:" + fail.size());
        System.out.println(StringUtils.join(fail, ","));
    }

    @Test
    public void queryList() throws BaseAdaPayException {
        Map<String, Object> paymentParams = new HashMap<>();
        paymentParams.put("app_id", appId);
        paymentParams.put("page_index", "1");
        paymentParams.put("page_size", "10");
        paymentParams.put("order_no", "928303191131422720");
        Map<String, Object> paymentList = Payment.queryList(paymentParams);
    }
}