package com.malk.lianan.utils;

import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.malk.lianan.utils.AesUtil;
import com.malk.lianan.utils.RSASignatureUtil;
import com.malk.lianan.utils.RsaUtil;
import com.malk.utils.UtilDateTime;
import com.malk.utils.UtilMap;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.*;

@Slf4j
public class TestUtil {


    // 测试环境数据
    private final static String GYPAY_API_URL="http://sk-uat.tech.dccnet.com.cn:8343/api/dtxg"; // 财资云服务的地址
    private final static String GYPAY_API_SYS_ID="NBLASY"; // 接入系统编号
    private final static String GYPAY_API_SYS_NAME="宁波联安商业"; // 接入系统名称
    private final static String GYPAY_API_TENANT_ID="TN100123"; // 商户号
    private final static String GYPAY_API_TENANT_NAME="org_01"; // 付款单位名称
    private final static String GYPAY_API_ACCOUNT_NO="123456"; // 付款单位账号
    private final static String GYPAY_API_TYPE_NO="YW21081817205273002001"; // 业务类型编号
    private final static String GYPAY_API_TYPE_NAME="bt_sett"; // 业务类型名称

    private final static String GYPAY_API_PUB_KEY="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCns/4GnEfTQtKhOBxZz57F8IZvKalhvX7iOZz2M7amfsO4jsiPNNbgHqKjX4hzyIeAmCmFqLDZMDIM2a4y/oNC/ikZl2yHcYexRT/xTgbR+EM2dDQqfUjDGDD3XsXRbmVbSvvKg8OhLwd4jRTHOGooetg8IP4SC66dPreJlNBVywIDAQAB";
    private final static String GYPAY_API_PRI_KEY="MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKez/gacR9NC0qE4HFnPnsXwhm8pqWG9fuI5nPYztqZ+w7iOyI801uAeoqNfiHPIh4CYKYWosNkwMgzZrjL+g0L+KRmXbIdxh7FFP/FOBtH4QzZ0NCp9SMMYMPdexdFuZVtK+8qDw6EvB3iNFMc4aih62Dwg/hILrp0+t4mU0FXLAgMBAAECgYBcRYmgY36Ve6/eqrvWoojOig+9vCOJNrVIjcCSKlP1+cuAkXdCbCVKPTDpSRgP9Kaxl4dJFk7vwTfYoDDbt/PKFX277V6bdkjMwNclwniilSU+QMEpmu71HeaXBAiRm5TLEflhcxV2Wy5D0VyBLnPWodH1rGjtfiO6V9SbQf8bGQJBANF5RJ+Ie/+dgAYm/L4Mb3f+Pb/yipUuHcqSZlfd/eMJDtEcp7xcvNFRivbl6IcXvncvL1uInkGdriOe3nmqti0CQQDM86LS8PsseuaVdpt7HCKivub0mI/wcvZ8mUVZZ4jFibPNsSKl1+QreGk/e2QrkyOySC5e2lf5HOEGC/lREm7XAkAL5K/BwxUPQVkIgGQvQjN+A6Br6pB1weWNH9zRtlf48QW3V8IqTrWlyNR0Cj+2k+GLkNFGiC48GYDOovGMxOWNAkEAqCDNV4H8ana/pajQz2M7PoqgZ9Kncba9YWVSsI7wciwOZhSDucyrDsYOgNc2S1C/Hcd80q8HMAJyzkUQV2NprQJACwsH8IEEE/kwSesQlb8fa+ugr+tNnFVPj1xqM4kPD5Dj3XP7B8KWUwL4a4/Y1S6BtoqCL4CAfuEHTw7MlUA2NA==";
    private final static String GYPAY_API_AES_KEY="d2a1b3173e494c38";
    private final static String GYPAY_API_SIGN_PUB_KEY="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCmudhlkVXrFP1DB0r11LvVpy8nYVO9sR2tYLXCkQxXE4HR2VlihCO43B2v/Ep3tlny4l/OX++AQX4sJpO8vAnCRmNIAgXKXAfvre1HTSkJf9vb8G9sf4UsZX2bLEOtH4wOO7Osv8Za98WzBHBRrqESI91Z4GSE0/8ucMp6V7EZ5wIDAQAB";

    public static void main(String[] args) throws Exception {
//        query();

//        query2();

        pay();;

//        pay2();;

//        payQuery();

        /*String sign1="Ra/WLUYZUeHHyaOhyvTDm1tczq8b25mTn2tfW4VQesbQHdY6E88bjXkuuJt0YVn6jgelH56Kl7z9zgv8L3QVCfy5WLgMwpsxjUeRGrL03Gd2KIz4R9ithmGNNziSJz0JR1yYHkUU2eHv+KmKGOxEjI+7NQ/oHOxe+mVI1HpioAo=";
        String data="{    \"ResultCode\": \"82000007\",    \"ResultMsg\": \"签名验证失败\",    \"NextTag\": \"0\",    \"ResultSet\": [    ]}";

        String resultData=AesUtil.decrypt(data,GYPAY_API_AES_KEY);

//        RSASignatureUtil.verifySafe("AeWTi5jUG8l1h6JJG9uuvGH63r6sSpnJW2VhOA52XGW5QdH6TESqQ4iKV46TuAB53juaW6DyBrQcuoXOXZK6lzIkird1cQksS8ve/IxVBwc1sa8BJRrO9cqCHoURjbKdJz66+FBE5L4pCZy5DESP/Q=="
//                ,"GRJCRklJVIy8vUFUg4gDo+iv+MIp+MHmitPrnUJLO0mcg+6EiJklYhoXtHhgmTgx2Rw7AgTsAsNNbM02ehgMLim0zeX76Ghq1oD/xbDyydi6/CLSEf1QS9fQvUsnOIwgZKarSc/UM2wdlgHf9M7OmNpf3Mv+YuEHwyMF6dXlljc="
//                ,GYPAY_API_SIGN_PUB_KEY);
//        byte[] derData = Base64.decode(PRIVATE_KEY);
//        X509Certificate x= parseDERCertificate(derData);
//        PublicKey publicKey = x.getPublicKey();
//        System.out.println(Base64.encode(publicKey.getEncoded()));
        try {
            // 加载证书文件
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            FileInputStream fis = null;
            fis = new FileInputStream("D:\\project\\cont\\mjava-lianan\\src\\main\\resources\\cer\\ICBC_CZY__SIGN_TEST.cer");
//            InputStream inputStream = UtilFile.readPackageResource("cer/" + "ICBC_CZY__SIGN_TEST.cer");

            X509Certificate cert = (X509Certificate) cf.generateCertificate(fis);
//            X509Certificate cert = (X509Certificate) cf.generateCertificate(inputStream);
            // 从证书中提取公钥
            PublicKey publicKey = cert.getPublicKey();
            System.out.println(new String(Base64.encode(publicKey.getEncoded()).getBytes(), StandardCharsets.UTF_8));

            // 验证签名
            Signature signature = Signature.getInstance("SHA256withRSA");
            signature.initVerify(publicKey);
            signature.update(resultData.getBytes(StandardCharsets.UTF_8));
            boolean verify = signature.verify(Base64.decode(sign1));
            System.out.println(verify);
        }catch (Exception e){
            e.printStackTrace();
        }*/
    }

    /**
     * 解析 DER 格式证书
     */
    private static X509Certificate parseDERCertificate(byte[] derData) throws Exception {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        ByteArrayInputStream bis = new ByteArrayInputStream(derData);
        return (X509Certificate) cf.generateCertificate(bis);
    }

    public static void query(){
        Map<String,Object> head = new HashMap<>();
        head.put("MesgNo","T0001");
        head.put("TenantId",GYPAY_API_TENANT_ID);
        head.put("Timestamp", UtilDateTime.getLocalDateTimeTimeStamp());
        head.put("SystemNo",GYPAY_API_SYS_ID);
        head.put("SystemName",GYPAY_API_SYS_NAME);
        head.put("RequestNo", IdUtil.nanoId(6));
        Map<String,Object> body = new HashMap<>();
        Map<String,Object> item = new HashMap<>();
        item.put("AcctNo",GYPAY_API_ACCOUNT_NO);
        item.put("CurrencyCode","CNY");
        item.put("StartTransDate","2026-01-01");
        item.put("EndTransDate","2026-01-12");
        item.put("NextTag","1");
        Map<String,Object> data = UtilMap.map("ParamSet", Arrays.asList(item));
        System.out.println(JSON.toJSONString(data));
        String encrypt = AesUtil.encrypt(JSON.toJSONString(data),GYPAY_API_AES_KEY);
        log.info("encrypt:{},{}","",encrypt);
        //解密
        body.put("Data", encrypt);
        String signed= RsaUtil.sign(JSONObject.toJSONString(data).getBytes(),GYPAY_API_PRI_KEY);
        body.put("Sign", signed);

        Map<String,Object> Cmscloud = new HashMap<>();
        Cmscloud.put("Head",head);
        Cmscloud.put("Body",body);
        String indata=JSONObject.toJSONString(UtilMap.map("Cmscloud",Cmscloud));
        System.out.println(indata);
        String result=HttpUtil.createPost(GYPAY_API_URL).body(indata).execute().body();
        System.out.println(result);
        JSONObject resultjson=JSONObject.parseObject(result);
        JSONObject resultBody = resultjson.getJSONObject("Cmscloud").getJSONObject("Body");
        String resultData=AesUtil.decrypt(resultBody.getString("Data"),GYPAY_API_AES_KEY);
        System.out.println(resultData);

        Boolean flag= RSASignatureUtil.verifySafe(resultData,resultBody.getString("Sign"),GYPAY_API_SIGN_PUB_KEY);
        System.out.println(flag);

    }

    //账户信息查询接口
    public static void query2(){
        Map<String,Object> head = new HashMap<>();
        head.put("MesgNo","T0005");
        head.put("TenantId",GYPAY_API_TENANT_ID);
        head.put("Timestamp", UtilDateTime.getLocalDateTimeTimeStamp());
        head.put("SystemNo",GYPAY_API_SYS_ID);
        head.put("SystemName",GYPAY_API_SYS_NAME);
        head.put("RequestNo",IdUtil.nanoId(6));


        Map<String,Object> body = new HashMap<>();
        Map<String,Object> item = new HashMap<>();
        item.put("CurrencyCodeList",Arrays.asList("CNY"));
        item.put("CategoryCodeList",Arrays.asList("01"));
        item.put("AcctStatus","1");
        item.put("AcctNoOrName",Arrays.asList("123456"));
        item.put("CooperativeInstitutionTypeList",Arrays.asList("1"));
        item.put("NextTag",1);

        Map<String,Object> data = UtilMap.map("ParamSet", Arrays.asList(item));
        String dataStr = JSON.toJSONString(data);
        System.out.println(dataStr);
        String encrypt = AesUtil.encrypt(dataStr,GYPAY_API_AES_KEY);
        log.info("encrypt:{},{}","",encrypt);
        body.put("Data", encrypt);
        String signed=RsaUtil.sign(dataStr.getBytes(),GYPAY_API_PRI_KEY);
        body.put("Sign", signed);

        Map<String,Object> Cmscloud = new HashMap<>();
        Cmscloud.put("Head",head);
        Cmscloud.put("Body",body);
        String indata=JSONObject.toJSONString(UtilMap.map("Cmscloud",Cmscloud));
        System.out.println(indata);
        String result=HttpUtil.createPost(GYPAY_API_URL).body(indata).execute().body();
        System.out.println(result);
        JSONObject resultjson=JSONObject.parseObject(result);
        JSONObject resultBody = resultjson.getJSONObject("Cmscloud").getJSONObject("Body");
        String resultData=AesUtil.decrypt(resultBody.getString("Data"),GYPAY_API_AES_KEY);
        System.out.println(resultData);

        Boolean flag=RSASignatureUtil.verifySafe(resultData,resultBody.getString("Sign"),GYPAY_API_SIGN_PUB_KEY);
        System.out.println(flag);

    }


    //单笔付款
    public static void pay(){
        Map<String,Object> head = new HashMap<>();
        head.put("MesgNo","T0002");
        head.put("TenantId",GYPAY_API_TENANT_ID);
        head.put("Timestamp", UtilDateTime.getLocalDateTimeTimeStamp());
        head.put("SystemNo",GYPAY_API_SYS_ID);
        head.put("SystemName",GYPAY_API_SYS_NAME);
        head.put("RequestNo", IdUtil.nanoId(6));


        Map<String,Object> body = new HashMap<>();
        Map<String,Object> item = new HashMap<>();
        item.put("BillsPayOrderNo","CS20260115001");
        item.put("PayType","1");
        item.put("PaymentDate","2026-01-15");
        item.put("BusinessTypeCode",GYPAY_API_TYPE_NO);
        item.put("BusinessTypeName",GYPAY_API_TYPE_NAME);
        item.put("PayOrgName",GYPAY_API_TENANT_NAME);
        item.put("PayAccountNo",GYPAY_API_ACCOUNT_NO);
        item.put("PayChannel","1");
        item.put("PayAmount","9.99");
        item.put("PayCurrencyType","CNY");
        item.put("PayCurrencyName","人民币");
        item.put("WhetherUrgent","2");
        item.put("Remark","测试单笔付款");
        item.put("PayUse","111111111");
        item.put("Purpose","报销");

        Map paymentRec = new HashMap();
        paymentRec.put("ReceiveAccountNo","0200000319201967739");
        paymentRec.put("ReceiveAccountName","111");
        paymentRec.put("ReceiveCurrencyCode","CNY");
        paymentRec.put("ReceiveCurrencyName","人民币");

        item.put("PaymentRec",paymentRec);



        Map<String,Object> data = UtilMap.map("ParamSet", Arrays.asList(item));
        System.out.println(JSON.toJSONString(data));
        String encrypt = AesUtil.encrypt(JSON.toJSONString(data),GYPAY_API_AES_KEY);
        log.info("encrypt:{},{}","",encrypt);
        //解密
        body.put("Data", encrypt);
        String signed=RsaUtil.sign(JSONObject.toJSONString(data).getBytes(),GYPAY_API_PRI_KEY);
        body.put("Sign", signed);

        Map<String,Object> Cmscloud = new HashMap<>();
        Cmscloud.put("Head",head);
        Cmscloud.put("Body",body);
        String indata=JSONObject.toJSONString(UtilMap.map("Cmscloud",Cmscloud));
        System.out.println(indata);
        String result=HttpUtil.createPost(GYPAY_API_URL).body(indata).execute().body();
        System.out.println(result);
        JSONObject resultjson=JSONObject.parseObject(result);
        JSONObject resultBody = resultjson.getJSONObject("Cmscloud").getJSONObject("Body");
        String resultData=AesUtil.decrypt(resultBody.getString("Data"),GYPAY_API_AES_KEY);
        System.out.println(resultData);

        Boolean flag=RSASignatureUtil.verifySafe(resultData,resultBody.getString("Sign"),GYPAY_API_SIGN_PUB_KEY);
        System.out.println(flag);

    }

    //工资代发（批量对私）
    public static void pay2(){
        Map<String,Object> head = new HashMap<>();
        head.put("MesgNo","T0003");
        head.put("TenantId",GYPAY_API_TENANT_ID);
        head.put("Timestamp", UtilDateTime.getLocalDateTimeTimeStamp());
        head.put("SystemNo",GYPAY_API_SYS_ID);
        head.put("SystemName",GYPAY_API_SYS_NAME);
        head.put("RequestNo", IdUtil.nanoId(6));


        Map<String,Object> body = new HashMap<>();
        Map<String,Object> item = new HashMap<>();
        item.put("BillsPayOrderNo","GZDF20260113001");
        item.put("PayType","2");
        item.put("PaymentDate","2026-01-13");
        item.put("BusinessTypeCode",GYPAY_API_TYPE_NO);
        item.put("BusinessTypeName",GYPAY_API_TYPE_NAME);
        item.put("PayOrgName",GYPAY_API_TENANT_NAME);
        item.put("PayAccountNo",GYPAY_API_ACCOUNT_NO);
        item.put("PayChannel","1");
        item.put("PayAmount","1.11");
        item.put("PayCurrencyType","CNY");
        item.put("PayCurrencyName","人民币");
        item.put("WhetherUrgent","2");
        item.put("Remark","测试工资代发");
        item.put("PayUse","111111111");
        item.put("Purpose","工资");

        //对私收款账户
        List<Map> batchPrivateRecList = new ArrayList<>();
        Map paymentRec = new HashMap();
        paymentRec.put("BillsPayOrderNo","GZDF20260113001-1");
        paymentRec.put("PrivateAmount","1");
        paymentRec.put("ReceiveAccountNo","0200000319201967739");
        paymentRec.put("ReceiveAccountName","111");
        paymentRec.put("ReceiveBranchCode","收款方开户行行号");
        paymentRec.put("ReceiveBranchName","收款方开户行名称");
        paymentRec.put("ReceiveCurrencyCode","CNY");
        paymentRec.put("ReceiveCurrencyName","人民币");
        batchPrivateRecList.add(paymentRec);

        Map paymentRec2 = new HashMap();
        paymentRec2.put("BillsPayOrderNo","GZDF20260113001-2");
        paymentRec2.put("PrivateAmount","0.11");
        paymentRec2.put("ReceiveAccountNo","0200000319201967739");
        paymentRec2.put("ReceiveAccountName","111");
        paymentRec2.put("ReceiveBranchCode","收款方开户行行号");
        paymentRec2.put("ReceiveBranchName","收款方开户行名称");
        paymentRec2.put("ReceiveCurrencyCode","CNY");
        paymentRec2.put("ReceiveCurrencyName","人民币");
        batchPrivateRecList.add(paymentRec2);

        item.put("BatchPrivateRecList",batchPrivateRecList);

        Map<String,Object> data = UtilMap.map("ParamSet", Arrays.asList(item));
        System.out.println(JSON.toJSONString(data));
        String encrypt = AesUtil.encrypt(JSON.toJSONString(data),GYPAY_API_AES_KEY);
        log.info("encrypt:{},{}","",encrypt);
        //解密
        body.put("Data", encrypt);
        String signed=RsaUtil.sign(JSONObject.toJSONString(data).getBytes(),GYPAY_API_PRI_KEY);
        body.put("Sign", signed);

        Map<String,Object> Cmscloud = new HashMap<>();
        Cmscloud.put("Head",head);
        Cmscloud.put("Body",body);
        String indata=JSONObject.toJSONString(UtilMap.map("Cmscloud",Cmscloud));
        System.out.println(indata);
        String result=HttpUtil.createPost(GYPAY_API_URL).body(indata).execute().body();
        System.out.println(result);
        JSONObject resultjson=JSONObject.parseObject(result);
        JSONObject resultBody = resultjson.getJSONObject("Cmscloud").getJSONObject("Body");
        String resultData=AesUtil.decrypt(resultBody.getString("Data"),GYPAY_API_AES_KEY);
        System.out.println(resultData);

        Boolean flag=RSASignatureUtil.verifySafe(resultData,resultBody.getString("Sign"),GYPAY_API_SIGN_PUB_KEY);
        System.out.println(flag);

    }

    //应付单业务状态查询
    public static void payQuery(){
        Map<String,Object> head = new HashMap<>();
        head.put("MesgNo","T0004");
        head.put("TenantId",GYPAY_API_TENANT_ID);
        head.put("Timestamp", UtilDateTime.getLocalDateTimeTimeStamp());
        head.put("SystemNo",GYPAY_API_SYS_ID);
        head.put("SystemName",GYPAY_API_SYS_NAME);
        head.put("RequestNo", IdUtil.nanoId(6));


        Map<String,Object> body = new HashMap<>();
        Map<String,Object> item = new HashMap<>();
        item.put("BillsPayOrderNo","CS20260112001");

        Map<String,Object> data = UtilMap.map("ParamSet", Arrays.asList(item));
        System.out.println(JSON.toJSONString(data));
        String encrypt = AesUtil.encrypt(JSON.toJSONString(data),GYPAY_API_AES_KEY);
        log.info("encrypt:{},{}","",encrypt);
        //解密
        body.put("Data", encrypt);
        String signed=RsaUtil.sign(JSONObject.toJSONString(data).getBytes(),GYPAY_API_PRI_KEY);
        body.put("Sign", signed);

        Map<String,Object> Cmscloud = new HashMap<>();
        Cmscloud.put("Head",head);
        Cmscloud.put("Body",body);
        String indata=JSONObject.toJSONString(UtilMap.map("Cmscloud",Cmscloud));
        System.out.println(indata);
        String result=HttpUtil.createPost(GYPAY_API_URL).body(indata).execute().body();
        System.out.println(result);
        JSONObject resultjson=JSONObject.parseObject(result);
        JSONObject resultBody = resultjson.getJSONObject("Cmscloud").getJSONObject("Body");
        String resultData=AesUtil.decrypt(resultBody.getString("Data"),GYPAY_API_AES_KEY);
        System.out.println(resultData);

        Boolean flag=RSASignatureUtil.verifySafe(resultData,resultBody.getString("Sign"),GYPAY_API_SIGN_PUB_KEY);
        System.out.println(flag);

    }


}

