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.JSONObject;
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.ApplicationTests;
import com.izouma.nineth.dto.adapay.DivMembersItem;
import com.izouma.nineth.dto.adapay.PaymentList;
import com.izouma.nineth.dto.adapay.PaymentItem;
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.AllArgsConstructor;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

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 AdapayTest extends ApplicationTests {
    private       String     appId    = "app_843a743d-744e-4d73-bd60-3ebbee15d383";
    private final String[][] accounts = new String[][]{
            {"mtws-a1", "app_843a743d-744e-4d73-bd60-3ebbee15d383", "api_live_c9db942a-b6d6-4cf7-b1b1-ec1e2873a7e7"},
            {"mtws-a2", "app_dcf563b9-14cf-4583-a023-b41eb7a88f22", "api_live_ed24cd9d-b188-46dd-97f7-45e1000dc72d"},
            {"mtws-a3", "app_7c2c29db-72d7-4215-ba56-99eacf28d7ee", "api_live_f77971eb-e816-4523-a41f-d4423526fb06"},
            {"mtws-a4", "app_8d662b06-27e0-46c0-b7a0-6aaffa014a9b", "api_live_b692f68b-417f-4f1c-b9ff-568e8e9de6f2"},
            {"mtws-a5", "app_f8760acc-f4d8-46f6-8f70-d80e36517075", "api_live_8818cac1-894b-40bc-ac77-803e02e9c260"},
    };

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

        appId = accounts[account - 1][1];
        MerConfig merConfig = new MerConfig();
        merConfig.setApiKey(accounts[account - 1][2]);
        merConfig.setApiMockKey("api_test_0b1b0eb9-30e1-4acd-8e03-10b529de1856");
        merConfig.setRSAPrivateKey("MIIEuwIBADANBgkqhkiG9w0BAQEFAASCBKUwggShAgEAAoIBAQCnIaIrFP598qcf/s3FqXxMTjrVAevnf1w5CAMdJqcRFv0WvdLEmNRxxqAYSLl/iQ8AyU4yqVwkwYqvn/aENBg0iQ5h5qboxb8T6xmrZLctk97TiIuCUwbd7Q5NBHJXzHlaKc1p1KBvTCJDMw8+t0Jh3sBkBvu7l0KPliEQHtPLBDkKvy3NBQD6BMy47kPersjSUH53HBvNpcjcPZGpUX/TmL3SNkS98RkoebFxuorK5UdazYN5xvarjfcYziShIjU3WIZJb52DGUxYWTk6vJKZrJhw7AhWIEQpH7qJxvml/B8RMQ4guHdtp3ojxwkHDtZdPU9rY8i6EHwba4qOYgobAgMBAAECggEAT36L5/oAYl+8ZleIAHBxEspS6WYUkvPdJbNN59uus04/60U2rxQSWFulYmeU87h5TmJxs18i2MjF8msfkhpFORfHo4FV+nm0PQEiIIezKRagcfUMhlx/c6eBmdh3mpNDVUN01NWxyb5ovZXXtnjsNikBUZKQwdVcb3d1GnnPO0xtt6/0xwiduCkA2ihS1tgnsYYDhMHgukIdZ3eczn3stRPQ+QyCt1JWS6DDd1nS3S2RyPZw8P9Z1zzJFVKH8z3bGqk3/98Lw7Hw+rKFnKhIA6/H9ZVORKw5OuGC3Ozy6cVbmUn8tuw3sC0NdR7w56dedB+fjJB8od0nahX1Cc6eQQKBgQDckcenslWqjs2PbncwW1wqlw7FdJX9rzJAg7kp9ItpHCoNi/kSgXeLphHXWJmyj7a1BkWynmTGxO48X3dPXUrDPFKJc42fSbxMgAQdtc/A2z+v7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N1iGSW+dgxlMWFk5OrySmayYcOwIViBEKR+6icb5pfwfETEOILh3bad6I8cJBw7WXT1Pa2PIuhB8G2uKjmIKGwIDAQAB");
        Adapay.publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCwN6xgd6Ad8v2hIIsQVnbt8a3JituR8o4Tc3B5WlcFR55bz4OMqrG/356Ur3cPbc2Fe8ArNd/0gZbC9q56Eb16JTkVNA/fye4SXznWxdyBPR7+guuJZHc/VW2fKH2lfZ2P3Tt0QkKZZoawYOGSMdIvO+WqK44updyax0ikK6JlNQIDAQAB";
        try {
            Adapay.initWithMerConfig(merConfig);
        } catch (Exception e) {
        }
    }

    @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("out_trans_id", "2022022522001490791443239943");

        JSONArray list = new JSONArray();
        paymentParams.put("page_index", ++page);
        Map<String, Object> paymentList = Payment.queryList(paymentParams);
        System.out.println(JSON.toJSONString(paymentList, SerializerFeature.PrettyFormat));
    }

    @Test
    public void singleRefund() throws BaseAdaPayException {
        Map<String, Object> refundParams = new HashMap<>();
        refundParams.put("refund_amt", "0.01");
        refundParams.put("refund_order_no", new SnowflakeIdWorker(0, 0).nextId() + "");
        Map<String, Object> response = Refund.create("002112022030111085110344569856421703680", refundParams);
        System.out.println(JSON.toJSONString(response, SerializerFeature.PrettyFormat));
    }

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

    @Test
    public void singleQuery() throws BaseAdaPayException {
        Map<String, Object> map = Payment.query("002112022022700094210343679201843290112");
        System.out.println(JSON.toJSONString(map, SerializerFeature.PrettyFormat));
    }

    @Test
    public void listQuery() throws BaseAdaPayException {
        Map<String, Object> paymentParams = new HashMap<>();
        paymentParams.put("app_id", appId);
        paymentParams.put("payment_id", "002112022022700094210343679201843290112");
        Map<String, Object> res = Payment.queryList(paymentParams);
        System.out.println(JSON.toJSONString(res, SerializerFeature.PrettyFormat));
        PaymentList paymentList = JSON.parseObject(JSON.toJSONString(res), PaymentList.class);
        if (paymentList.getPayments() != null) {
            PaymentItem paymentItem = paymentList.getPayments().get(0);
            if (paymentItem.getDivMembers() != null && paymentItem.getDivMembers().size() > 1) {
                DivMembersItem item = paymentItem.getDivMembers().stream().filter(d -> !d.getMemberId().equals("0"))
                        .findAny().get();
            }
        }
    }


    public void balancePay(String from, String to, String amount) throws BaseAdaPayException {
        Map<String, Object> balanceParam = new HashMap<String, Object>(4);
        balanceParam.put("app_id", appId);
        balanceParam.put("adapay_func_code", "settle_accounts.balancePay");
        balanceParam.put("order_no", new SnowflakeIdWorker(0, 0).nextId() + "");
        balanceParam.put("out_member_id", from);
        balanceParam.put("in_member_id", to);
        balanceParam.put("trans_amt", amount);
        balanceParam.put("goods_title", "一双鞋子");
        balanceParam.put("goods_desc", "一双鞋子啊");

        Map<String, Object> paymentResult = AdapayCommon.requestAdapay(balanceParam);
        System.out.println(JSON.toJSONString(paymentResult, SerializerFeature.PrettyFormat));
    }

    @Test
    public void testbalancePay() throws BaseAdaPayException {
        balancePay("8635", "3896", "0.01");
    }

    @Autowired
    private LianlianPayService lianlianPayService;

    @Test
    public void testUpload() throws Exception{
        JSONObject res = lianlianPayService.uploadFile(9398L , "https://cosmoscdn.9space.vip/image/2022-03-09-18-32-40zhXEPasT.jpg");
        System.out.print("输出：" + res);
    }


}