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.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;

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

public class AdapayTest {
    private final String appId = "app_0e8d3acb-3d95-4ebb-8445-e470c378a787";

    public AdapayTest() {
        Adapay.debug = false;
        Adapay.prodMode = true;

        MerConfig merConfig = new MerConfig();
        merConfig.setApiKey("api_live_dc298e47-c0be-4acf-a962-a2c2988e4cae");
        merConfig.setApiMockKey("api_test_26e9eee7-6695-4169-90a1-203c6d2cf196");
        merConfig.setRSAPrivateKey("MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCLeSEu8CXg4iwpRtAapIGpbuoJdyAh3E2FgIqOJSME/0+DscuIUVzfQzMWgXT98Zd8aKQLmjTWHx6Tg60DCFJzJBkISZYaqF9Oc+YdPe15TINpp5syKDk72WeUEW/jlXiLwKyeFxzCvedbpbdAUi0cP64US/LslGohHGWUrgj/WBR33vgwA2NAHR+ziGp8IhFUXHoWtXdBjwGsWuZ6Wt9mWOVeGIHP6OyUYzhkVuDyFMZ6wlA60PqxPAQrvZG3VP2mSlpWTs7xQHM9nk8Rn2pQDUmexHmKS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Ez//FiMHB+TvT3JBzxBVXGEZnJOAEizzB2kCgYEAxUFRiJMcmp5IyGcFlmGP219OcEfzt8BV8s3yoPHPpgYX/zPsH9764UMSZb+FRXFLd8HC+UqqppQ4cq2RmMu5X7H/DWoj9FqXgusjOmZUyWiJgTPC4ktFesuhJhCHuk/50/nXmc6O8rWLwXqXf1XNaoNfzDmZNQ20jRZGr8eVc4g=");
        merConfig.setRSAPublicKey("MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAi3khLvAl4OIsKUbQGqSBqW7qCXcgIdxNhYCKjiUjBP9Pg7HLiFFc30MzFoF0/fGXfGikC5o01h8ek4OtAwhScyQZCEmWGqhfTnPmHT3teUyDaaebMig5O9lnlBFv45V4i8Csnhccwr3nW6W3QFItHD+uFEvy7JRqIRxllK4I/1gUd974MANjQB0fs4hqfCIRVFx6FrV3QY8BrFrmelrfZljlXhiBz+jslGM4ZFbg8hTGesJQOtD6sTwEK72Rt1T9pkpaVk7O8UBzPZ5PEZ9qUA1JnsR5ikv8J+F2b5d0vSkbOv5fMA6pQVuUIZhGTUcIjhvJ/xaasVDCIRRY+EkqtQIDAQAB");
        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 {
        LocalDateTime start = LocalDateTime.of(2022, 1, 7, 0, 0, 0);
        LocalDateTime end = LocalDateTime.of(2022, 1, 8, 0, 0, 0);

        Map<String, Object> paymentParams = new HashMap<>();
        int page = 0;
        paymentParams.put("app_id", appId);
        paymentParams.put("page_size", "20");
        paymentParams.put("created_gte", start.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
        paymentParams.put("created_lte", end.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());

        boolean hasMore = true;
        JSONArray list = new JSONArray();
        while (hasMore) {
            paymentParams.put("page_index", ++page);
            Map<String, Object> paymentList = Payment.queryList(paymentParams);
            if (paymentList.get("payments") != null) {
                list.addAll((JSONArray) paymentList.get("payments"));
            }
            hasMore = MapUtils.getBooleanValue(paymentList, "has_more");
        }
        System.out.println(list);
    }

    @Test
    public void rrr() throws BaseAdaPayException {
        Map<String, Object> queryParams = new HashMap<>();
        queryParams.put("payment_id", "002112022011117055410326902706185465856");
        Map<String, Object> refund = Refund.query(queryParams);
        System.out.println(JSON.toJSONString(refund, SerializerFeature.PrettyFormat));
    }
}