package com.tzy.framework.pay.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tzy.base.dto.DictBaseDto;
import com.tzy.base.service.SysBaseService;
import com.tzy.common.utils.Base64Util;
import com.tzy.common.utils.DateUtils;
import com.tzy.common.utils.LogSyncUtil;
import com.tzy.common.utils.StringUtils;
import com.tzy.framework.pay.config.BaoFooPayConfig;
import com.tzy.framework.pay.dto.PaymentInfoResponseDto;
import com.tzy.framework.pay.dto.PaymentRequestDto;
import com.tzy.framework.pay.dto.RefundRequestDto;
import com.tzy.framework.pay.dto.ResultMap;
import com.tzy.framework.pay.service.BaoFooBankPayService;
import com.tzy.framework.pay.util.bofoo.bank.HttpUtil;
import com.tzy.framework.pay.util.bofoo.bank.RsaCodingUtil;
import com.tzy.framework.pay.util.bofoo.bank.SecurityUtil;
import com.tzy.framework.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

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

/**
 * 宝付银行卡支付
 */
@Slf4j
@Service
public class BaoFooBankPayServiceImpl implements BaoFooBankPayService {

    public static final String URL = "https://mch-juhe.baofoo.com/api";
    @Value("${tzy.app-version:dev}")
    private String appversion ;
    @Autowired
    private BaoFooPayConfig baoFooPayConfig ;
    @Autowired
    private SysBaseService sysBaseService;

    public static void main(String[] args) throws Exception{
        BaoFooBankPayServiceImpl service = new BaoFooBankPayServiceImpl();
        service.baoFooPayConfig = new BaoFooPayConfig();
        PaymentRequestDto payRequestBody = new PaymentRequestDto();
        payRequestBody.setBody("测试支付");
        payRequestBody.setTotalAmount(new BigDecimal("1000"));
        payRequestBody.setOrderNo(RandomUtil.getRandomNew(RandomUtil.GROUP_USER_ORDER));
//        ResultMap bankType = service.getBankType(payRequestBody);
//        log.info("获取银行卡列表>>>>"+bankType);
//        ResultMap order = service.createOrder(payRequestBody);
//        payRequestBody.setUacBank("4020039");
//        payRequestBody.setMerOrderId(String.valueOf(order.get("trade_no")));
//        log.info("下单结果>>>>"+service.unifiedOrder(payRequestBody));
        //查询
        PaymentRequestDto paymentRequestDto = new PaymentRequestDto();
        paymentRequestDto.setMerOrderId("GU202304201247511431");//GU202304141528385870
        log.info("查询结果>>>>"+service.queryOrder(paymentRequestDto));
        //退款
//        RefundRequestDto refundRequestDto = new RefundRequestDto();
//        refundRequestDto.setTradeNo("GU202304141637244105");
//        refundRequestDto.setRefundAmount(new BigDecimal(1000));
//        refundRequestDto.setRefundMsg("退款测试！");//RN202304141640122746
//        log.info("退款申请>>>>"+service.refund(refundRequestDto));
        //退款查询
//        RefundRequestDto refundRequestDto = new RefundRequestDto();
//        refundRequestDto.setRefundNo("RN202304141640122746");//RN202304141601525321
//        log.info("退款查询>>>>"+service.refundQuery(refundRequestDto));
    }

    @Override
    public ResultMap getBankList(PaymentRequestDto payRequestBody){
        ResultMap resultMap = createOrder(payRequestBody);
        if(null != resultMap && 0 == (int)resultMap.get("code")){
            try {
                //获取银行列表
                baoFooPayConfig = initPayConfig(payRequestBody);
                String memberId = baoFooPayConfig.getMid();
                String terminalId = baoFooPayConfig.getTid();
                String trade_no = String.valueOf(resultMap.get("trade_no"));//（下单接口中的商户订单号）
//                String ServerUrl = "https://vgw.baofoo.com/union-gw/api/T-1001-024-02/transReq.do";//test
                String ServerUrl = "https://public.baofu.com/union-gw/api/T-1001-024-02/transReq.do";
                String pfxpath = baoFooPayConfig.getPrivateKey();//商户私钥
                String cerpath = baoFooPayConfig.getPublicKey();//宝付公钥
                String pfx_pwd = baoFooPayConfig.getPrivateKeyPwd();
                Map<String, String> HeaderPost = new HashMap<String, String>();
                HeaderPost.put("memberId", memberId);// 宝付提供给商户的唯一编号
                HeaderPost.put("terminalId", terminalId);
                HeaderPost.put("serviceTp", "T-1001-024-02");//
                HeaderPost.put("verifyType", "1");// 加密方式目前只有1种，请填：1
                Map<String, String> BodyData = new TreeMap<String, String>();
                BodyData.put("memberTransId", trade_no);// 商户订单号
                BodyData.put("memberId", memberId);//商户号
                BodyData.put("cardType", "1");//类型  1 借记卡
                Map<String, Object> contentData = new TreeMap<String, Object>();
                contentData.put("header", HeaderPost);
                contentData.put("body", BodyData);
                String jsonString = JSONObject.toJSONString(contentData);
                log.info("序列化：" + jsonString);
                String base64str = SecurityUtil.Base64Encode(jsonString);
                String data_content = RsaCodingUtil.encryptByPriPfxFile(base64str, pfxpath, pfx_pwd);
                HeaderPost.put("content", data_content);
                LogSyncUtil.logSync("宝付手机银行支付 获取银行卡列表,交易编号:{},请求参数:{}",trade_no,HeaderPost);
                String retStr = HttpUtil.RequestForm(ServerUrl, HeaderPost);
                log.info("请求返回：" + retStr);
                LogSyncUtil.logSync("宝付手机银行支付 获取银行卡列表,交易编号:{},返回结果:{}",trade_no,retStr);
                String retStrDe = SecurityUtil.Base64Decode(RsaCodingUtil.decryptByPubCerFile(retStr, cerpath));
                JSONObject jsonObject = JSONObject.parseObject(retStrDe);
                log.info("下单返回结果 >>> " + jsonObject);
                JSONObject retBody = jsonObject.getJSONObject("body");
                if("0000".equals(retBody.getString("errorCode"))){
                    JSONArray bankList = retBody.getJSONArray("bankList");
                    Map<String , JSONObject> bankMap = new HashMap<>();
                    bankList.forEach(item->{
                        JSONObject jsonItem = (JSONObject) item;
                        String bankName = jsonItem.getString("functionId");
                        bankMap.put(bankName,jsonItem);
                    });
                    List<DictBaseDto> bankListDicts = sysBaseService.selectDictDataByDictType("bank_list");
                    JSONArray bankitems = new JSONArray();
                    if(null != bankListDicts && bankListDicts.size() > 0){
                        bankListDicts.forEach(item->{
                            JSONObject bankValue = bankMap.get(item.getKey());
                            bankValue.put("url",item.getRemark());
                            bankitems.add(bankValue);
                        });
                    }
                    return ResultMap.ok()
                            .put("bankList",bankitems)
                            .put("trade_no",trade_no)
                            ;
                } else {
                    return ResultMap.error(retBody.getString("errorMsg"));
                }
            }catch (Exception e){
                e.printStackTrace();
                log.error("getBankList  下单失败  {}",e);
            }
            return ResultMap.error("下单失败");
        }
        return resultMap;
    }

    private ResultMap createOrder(PaymentRequestDto payRequestBody){
        try {
            String body = String.valueOf(payRequestBody.getBody());
            if(StringUtils.isNotEmpty(body) ){
                body = Base64Util.subStringByBytes(body,80)+"...";
            }
            baoFooPayConfig = initPayConfig(payRequestBody);
            String memberId = baoFooPayConfig.getMid();
            String terminalId = baoFooPayConfig.getTid();
            String orderAmt = String.valueOf(payRequestBody.getTotalAmount().multiply(new BigDecimal(100)).intValue());
            String pfxpath = baoFooPayConfig.getPrivateKey();//商户私钥
            String cerpath = baoFooPayConfig.getPublicKey();//宝付公钥
            String pfx_pwd = baoFooPayConfig.getPrivateKeyPwd();
            String trade_no = payRequestBody.getMerOrderId();
            String ServerUrl = "https://public.baofu.com/union-gw/api/T-1001-024-01/transReq.do";
            Map<String, String> HeaderPost = new HashMap<String, String>();
            HeaderPost.put("memberId", memberId);// 宝付提供给商户的唯一编号
            HeaderPost.put("terminalId", terminalId);
            HeaderPost.put("serviceTp", "T-1001-024-01");//
            HeaderPost.put("verifyType", "1");// 加密方式目前只有1种，请填：1
            String tradeDate = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
            Map<String, String> BodyData = new TreeMap<String, String>();
            BodyData.put("memberTransId", trade_no);// 商户订单号
//            BodyData.put("memberTransId", payRequestBody.getOrderNo());// 商户订单号
            BodyData.put("memberId", memberId);//商户号
            BodyData.put("terminalId", terminalId);//终端号
            BodyData.put("tradeDate", tradeDate);//交易日期 格式：yyyyMMddHHmms
            BodyData.put("orderAmt", orderAmt);//单位：分
            BodyData.put("notifyUrl", baoFooPayConfig.getPayNotifyUrl());//交易异步通知地址。
            BodyData.put("reqAddtion", body);//请求附加信息
            BodyData.put("tradeCode", "0");//0⼿机银⾏	1⼿机银
//            BodyData.put("shareInfo", "");//分账信息
//            BodyData.put("shareNotifyUrl", "");//分账通知地址
            Map<String, Object> contentData = new TreeMap<String, Object>();
            contentData.put("header", HeaderPost);
            contentData.put("body", BodyData);
            String Jsonstr = JSONObject.toJSONString(contentData);
            log.info("序列化：" + Jsonstr);
            String base64str = SecurityUtil.Base64Encode(Jsonstr);
            String data_content = RsaCodingUtil.encryptByPriPfxFile(base64str, pfxpath, pfx_pwd);
            log.info("加密参数data_content》》》" + data_content);
//            String s = RsaCodingUtil.decryptByPubCerFile(data_content, "C:\\poyi\\project\\admin\\poyee-pay\\src\\main\\resources\\lib\\bofooPublic.cer");
//            String s = RsaCodingUtil.decryptByPubCerFile(data_content, "/app/configs/bofooPublic.cer");
//            String inStrDe = SecurityUtil.Base64Decode(s);
//            log.info("解密请求参数返回：" + inStrDe);
            HeaderPost.put("content", data_content);
            LogSyncUtil.logSync("宝付手机银行支付 创建订单,交易编号:{},请求参数:{}",trade_no,HeaderPost);
            String retString = HttpUtil.RequestForm(ServerUrl, HeaderPost);
            LogSyncUtil.logSync("宝付手机银行支付 创建订单,交易编号:{},返回结果:{}",trade_no,retString);
            log.info("请求返回：" + retString);
            retString = RsaCodingUtil.decryptByPubCerFile(retString, cerpath);
            String retStrDe = SecurityUtil.Base64Decode(retString);
            log.info("请求返回(明)：" + retStrDe);
            JSONObject jsonObject = JSONObject.parseObject(retStrDe);
            log.info("下单返回结果 >>> " + jsonObject);
            JSONObject retBody = jsonObject.getJSONObject("body");
            if("0000".equals(retBody.getString("errorCode"))){
                return ResultMap.ok()
                        .put("trade_no",trade_no)
                        ;
            } else {
                return ResultMap.error(retBody.getString("errorMsg"));
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error(" createOrder  下单失败  {}",e);
        }
        return ResultMap.error("下单失败");
    }

    @Override
    public ResultMap unifiedOrder(PaymentRequestDto payRequestBody){
        try{
            baoFooPayConfig = initPayConfig(payRequestBody);
            String memberId = baoFooPayConfig.getMid();
            String terminalId = baoFooPayConfig.getTid();
            String functionId = payRequestBody.getUacBank();//通过获取银行例表返回
            String pfxpath = baoFooPayConfig.getPrivateKey();//商户私钥
            String cerpath = baoFooPayConfig.getPublicKey();//宝付公钥
            String pfx_pwd = baoFooPayConfig.getPrivateKeyPwd();
            String trade_no = payRequestBody.getMerOrderId();//（下单接口中的商户订单号）
//            String ServerUrl = "https://vgw.baofoo.com/union-gw/api/T-1001-024-03/transReq.do";//test
            String ServerUrl = "https://public.baofu.com/union-gw/api/T-1001-024-03/transReq.do";
            Map<String, String> HeaderPost = new HashMap<String, String>();
            HeaderPost.put("memberId", memberId);// 宝付提供给商户的唯一编号
            HeaderPost.put("terminalId",terminalId);
            HeaderPost.put("serviceTp", "T-1001-024-03");//
            HeaderPost.put("verifyType", "1");// 加密方式目前只有1种，请填：1
            Map<String, String> BodyData = new TreeMap<String, String>();
            BodyData.put("memberTransId",trade_no);// 商户订单号
            BodyData.put("memberId", memberId);//商户号
            BodyData.put("functionId", functionId);
            BodyData.put("channelType", "H5");//受理⽅式： APP、H5, 默认H5
            BodyData.put("clientIp", "101.229.133.177");//用户IP
            Map<String, Object> contentData = new TreeMap<String, Object>();
            contentData.put("header", HeaderPost);
            contentData.put("body", BodyData);
            String Jsonstr = JSONObject.toJSONString(contentData);
            log.info("序列化：" + Jsonstr);
            String base64str = SecurityUtil.Base64Encode(Jsonstr);
            String data_content = RsaCodingUtil.encryptByPriPfxFile(base64str, pfxpath, pfx_pwd);
            log.info("序列化：" + Jsonstr);
            HeaderPost.put("content", data_content);
            LogSyncUtil.logSync("宝付手机银行支付 预下单,交易编号:{},请求参数:{}",trade_no,HeaderPost);
            String PostString = HttpUtil.RequestForm(ServerUrl, HeaderPost);
            LogSyncUtil.logSync("宝付手机银行支付 预下单,交易编号:{},返回结果:{}",trade_no,PostString);
            log.info("请求返回：" + PostString);
            String retStrDe = SecurityUtil.Base64Decode(RsaCodingUtil.decryptByPubCerFile(PostString, cerpath));
            log.info("请求返回(明)：" + retStrDe);
            JSONObject jsonObject = JSONObject.parseObject(retStrDe);
            log.info("下单返回结果 >>> " + jsonObject);
            JSONObject retBody = jsonObject.getJSONObject("body");
            if("0000".equals(retBody.getString("errorCode"))){
                //根据不同银行处理不同的请求方式
                retBody.remove("memberId");
                return ResultMap.ok()
                        .put("merOrderId",trade_no)
                        .put("orderNo",payRequestBody.getOrderNo())
                        .put("data",retBody)
                        ;
            } else {
                return ResultMap.error(retBody.getString("errorMsg"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("unifiedOrder  下单失败  {}",e);
        }
        return ResultMap.error("下单失败");
    }

    @Override
    public PaymentInfoResponseDto queryOrder(PaymentRequestDto paymentRequestDto){
        PaymentInfoResponseDto paymentInfoResponseDto = new PaymentInfoResponseDto();
        try {
//            baoFooPayConfig = initPayConfig(payRequestBody);
            String memberId = baoFooPayConfig.getMid();
            String terminalId = baoFooPayConfig.getTid();
            String pfxpath = baoFooPayConfig.getPrivateKey();//商户私钥
            String cerpath = baoFooPayConfig.getPublicKey();//宝付公钥
            String pfx_pwd = baoFooPayConfig.getPrivateKeyPwd();
            String trade_no = paymentRequestDto.getOrderNo();//（下单接口中的商户订单号）
//            String ServerUrl = "https://vgw.baofoo.com/union-gw/api/T-1001-024-04/transReq.do";//test
            String ServerUrl = "https://public.baofu.com/union-gw/api/T-1001-024-04/transReq.do";
            Map<String, String> HeaderPost = new HashMap<String, String>();
            HeaderPost.put("memberId", memberId);// 宝付提供给商户的唯一编号
            HeaderPost.put("terminalId", terminalId);
            HeaderPost.put("serviceTp", "T-1001-024-04");//
            HeaderPost.put("verifyType", "1");// 加密方式目前只有1种，请填：1
            Map<String, String> BodyData = new TreeMap<String, String>();
            BodyData.put("memberTransId", trade_no);// 商户订单号
            BodyData.put("memberId", memberId);//商户号
            Map<String, Object> contentData = new TreeMap<String, Object>();
            contentData.put("header", HeaderPost);
            contentData.put("body", BodyData);
            String Jsonstr = JSONObject.toJSONString(contentData);
            log.info("序列化：" + Jsonstr);
            String base64str = SecurityUtil.Base64Encode(Jsonstr);
            String data_content = RsaCodingUtil.encryptByPriPfxFile(base64str, pfxpath, pfx_pwd);
            HeaderPost.put("content", data_content);
            LogSyncUtil.logSync("宝付手机银行支付 订单查询,交易编号:{},请求参数:{}",trade_no,HeaderPost);
            String PostString = HttpUtil.RequestForm(ServerUrl, HeaderPost);
            LogSyncUtil.logSync("宝付手机银行支付 订单查询,交易编号:{},返回结果:{}",trade_no,PostString);
            log.info("请求返回：" + PostString);
            String retStrDe = SecurityUtil.Base64Decode(RsaCodingUtil.decryptByPubCerFile(PostString, cerpath));
            log.info("请求返回(明)：" + retStrDe);
            JSONObject jsonObject = JSONObject.parseObject(retStrDe);
            log.info("下单返回结果 >>> " + jsonObject);
            JSONObject retBody = jsonObject.getJSONObject("body");
            if("0000".equals(retBody.getString("errorCode"))){
                //根据不同银行处理不同的请求方式
                if("S".equals(retBody.getString("orderState"))){
                    //下单成功
                    paymentInfoResponseDto.setOrderNo(trade_no);
                    paymentInfoResponseDto.setPayWay(paymentRequestDto.getPayWay());
                    paymentInfoResponseDto.setPaymentNo(StringUtils.isNotEmpty(jsonObject.getString("orderId")) ? jsonObject.getString("orderId") : null);
                    Integer orderAmt = null != jsonObject.getInteger("orderAmt") ? jsonObject.getInteger("orderAmt") : 0;
                    paymentInfoResponseDto.setPaymentPrice(new BigDecimal(orderAmt).divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_FLOOR));
                    paymentInfoResponseDto.setActualPayment(new BigDecimal(orderAmt).divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_FLOOR));
                    Date finishedDate = StringUtils.isNotEmpty(jsonObject.getString("succTime")) ? DateUtils.dateTime(DateUtils.YYYYMMDDHHMMSS, jsonObject.getString("succTime")) : null;
                    paymentInfoResponseDto.setPaymentSuccessTime(finishedDate);
                    paymentInfoResponseDto.setSuccess(true);
                    return paymentInfoResponseDto
                            ;
                }else
                if("C".equals(retBody.getString("orderState"))){
                    return PaymentInfoResponseDto.error(-1,"交易关闭");
                }else
                if("P".equals(retBody.getString("orderState"))){
                    return PaymentInfoResponseDto.error(1,"处理中");
                }else
                if("F".equals(retBody.getString("orderState"))){
                    return PaymentInfoResponseDto.error(-1,"支付失败");
                }
            } else {
                return PaymentInfoResponseDto.error(-1,retBody.getString("errorMsg"));
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return PaymentInfoResponseDto.error(-1,"查询失败！");
    }

    @Override
    public ResultMap refund( RefundRequestDto refundRequestDto){
        try {
            baoFooPayConfig = initRefundConfig(refundRequestDto);
            String pfxpath = baoFooPayConfig.getPrivateKey();//商户私钥
            String cerpath = baoFooPayConfig.getPublicKey();//宝付公钥
            String pfxpwd = baoFooPayConfig.getPrivateKeyPwd();//私钥密码
            String merId = baoFooPayConfig.getMid();
            String terId = baoFooPayConfig.getTid();
            String ServerUrl = "https://public.baofoo.com/cutpayment/api/backTransRequest";
            String txnTime = getTxnTime();//报文发送日期时间
            String originOutTradeNo = refundRequestDto.getOrderNo();//原支付订单商户订单号 [与原支付订单宝付交易号二选一比传]
            String outTradeNo = RandomUtil.getRandomNew(RandomUtil.REFUND_NO);
            String refundAmt = String.valueOf(refundRequestDto.getRefundAmount().multiply(new BigDecimal(100)).intValue());//退款金额
            Map<String, String> HeaderPost = new HashMap<String, String>();
            HeaderPost.put("member_id", merId);// 宝付提供给商户的唯一编号
            HeaderPost.put("terminal_id", terId);
            HeaderPost.put("version", "4.0.0.0");//
            HeaderPost.put("txn_type", "331");
            HeaderPost.put("txn_sub_type", "09");
            HeaderPost.put("data_type", "json");
            Map<String, Object> Biz_Content = new HashMap<String, Object>();
            Biz_Content.put("member_id", merId);
            Biz_Content.put("terminal_id", terId);
            Biz_Content.put("txn_sub_type", "09");
            Biz_Content.put("refund_type", "1");
            Biz_Content.put("trans_id", originOutTradeNo);
            Biz_Content.put("refund_order_no", outTradeNo);
            Biz_Content.put("trans_serial_no", RandomUtil.getRandomNew(RandomUtil.REFUND_NO));
            Biz_Content.put("refund_reason", refundRequestDto.getRefundMsg());
            Biz_Content.put("refund_amt", refundAmt);
            Biz_Content.put("refund_time", txnTime);
            Biz_Content.put("notice_url", baoFooPayConfig.getRefundNotifyUrl());
            String Jsonstr = JSONObject.toJSONString(Biz_Content).toString();
            log.info("序列化：" + Jsonstr);
            String base64str = SecurityUtil.Base64Encode(Jsonstr);
            String data_content = RsaCodingUtil.encryptByPriPfxFile(base64str, pfxpath, pfxpwd);
            HeaderPost.put("data_content", data_content);
            LogSyncUtil.logSync("宝付手机银行支付 退款,交易编号:{},请求参数:{}",originOutTradeNo,HeaderPost);
            String PostString = HttpUtil.RequestForm(ServerUrl, HeaderPost);
            LogSyncUtil.logSync("宝付手机银行支付 退款,交易编号:{},返回结果:{}",originOutTradeNo,PostString);
            log.info("请求返回：" + PostString);
            String retStrDe = SecurityUtil.Base64Decode(RsaCodingUtil.decryptByPubCerFile(PostString, cerpath));
            log.info("请求返回(明)：" + retStrDe);
            JSONObject jsonObject = JSONObject.parseObject(retStrDe);
            log.info("下单返回结果 >>> " + jsonObject);
            if("0000".equals(jsonObject.getString("resp_code"))){
                //根据不同银行处理不同的请求方式
                log.info("[申请退款结果]交易成功，成功金额：" + refundAmt.toString() + "分。");
                //下单成功
                Map<String, String> stringStringMap = new HashMap<>();
                stringStringMap.put("out_refund_no", outTradeNo);
                stringStringMap.put("refund_id", jsonObject.getString("refund_business_no"));
                stringStringMap.put("refund_fee", String.valueOf(jsonObject.getInteger("refund_amt")));
                stringStringMap.put("fund_change", "Y");
//                                stringStringMap.put("finishedDate", result.get("finishedDate"));
                return ResultMap.ok(jsonObject.getString("resp_msg"))
                        .put("data", stringStringMap)
                        ;
            } else {
                return ResultMap.error(-1, jsonObject.getString("resp_msg"));
            }
        }catch (Exception e){
            e.printStackTrace();
            return ResultMap.error(-1,"签名生成异常！");
        }
    }

    @Override
    public ResultMap refundQuery( RefundRequestDto refundRequestDto){
        try {
            baoFooPayConfig = initRefundConfig(refundRequestDto);
            String pfxpath = baoFooPayConfig.getPrivateKey();//商户私钥
            String cerpath = baoFooPayConfig.getPublicKey();//宝付公钥
            String pfxpwd = baoFooPayConfig.getPrivateKeyPwd();//私钥密码
            String merId = baoFooPayConfig.getMid();
            String terId = baoFooPayConfig.getTid();
            String ServerUrl = "https://public.baofoo.com/cutpayment/api/backTransRequest";
            String outTradeNo = refundRequestDto.getRefundNo();//原支付订单商户订单号 [与原支付订单宝付交易号二选一比传]
            String refundAmt = String.valueOf(refundRequestDto.getRefundAmount());//退款金额
            Map<String, String> HeaderPost = new HashMap<String, String>();
            HeaderPost.put("member_id", merId);// 宝付提供给商户的唯一编号
            HeaderPost.put("terminal_id", terId);
            HeaderPost.put("version", "4.0.0.0");//
            HeaderPost.put("txn_type", "331");
            HeaderPost.put("txn_sub_type", "10");
            HeaderPost.put("data_type", "json");
            Map<String, Object> Biz_Content = new HashMap<String, Object>();
            Biz_Content.put("member_id", merId);
            Biz_Content.put("terminal_id", terId);
            Biz_Content.put("txn_sub_type", "10");
            Biz_Content.put("refund_order_no", outTradeNo);
            Biz_Content.put("trans_serial_no", RandomUtil.getRandomNew(RandomUtil.REFUND_NO));
            String Jsonstr = JSONObject.toJSONString(Biz_Content).toString();
            log.info("序列化：" + Jsonstr);
            String base64str = SecurityUtil.Base64Encode(Jsonstr);
            String data_content = RsaCodingUtil.encryptByPriPfxFile(base64str, pfxpath, pfxpwd);
            HeaderPost.put("data_content", data_content);
            LogSyncUtil.logSync("宝付手机银行支付 退款查询,交易编号:{},请求参数:{}",outTradeNo,HeaderPost);
            String PostString = HttpUtil.RequestForm(ServerUrl, HeaderPost);
            LogSyncUtil.logSync("宝付手机银行支付 退款查询,交易编号:{},返回结果:{}",outTradeNo,PostString);
            log.info("请求返回：" + PostString);
            String retStrDe = SecurityUtil.Base64Decode(RsaCodingUtil.decryptByPubCerFile(PostString, cerpath));
            log.info("请求返回(明)：" + retStrDe);
            JSONObject jsonObject = JSONObject.parseObject(retStrDe);
            log.info("下单返回结果 >>> " + jsonObject);
            if("0000".equals(jsonObject.getString("resp_code"))){
                //根据不同银行处理不同的请求方式
                log.info("[申请退款结果]交易成功，成功金额：" + refundAmt.toString() + "分。");
                //下单成功
                Map<String, String> stringStringMap = new HashMap<>();
                stringStringMap.put("out_refund_no", outTradeNo);
                stringStringMap.put("refund_id", jsonObject.getString("refund_business_no"));
                stringStringMap.put("refund_fee", String.valueOf(jsonObject.getInteger("refund_amt")));
                stringStringMap.put("fund_change", "Y");
//                                stringStringMap.put("finishedDate", result.get("finishedDate"));
                return ResultMap.ok(jsonObject.getString("resp_msg"))
                        .put("data", stringStringMap)
                        ;
            } else {
                return ResultMap.error(-1, jsonObject.getString("resp_msg"));
            }
        }catch (Exception e){
            e.printStackTrace();
            return ResultMap.error(-1,"签名生成异常！");
        }
    }


    private static String getTxnTime() {
        return DateUtils.dateTimeNow(DateUtils.YYYYMMDDHHMMSS);
    }

    private BaoFooPayConfig initPayConfig(PaymentRequestDto paymentRequestDto){
        BaoFooPayConfig config = StringUtils.isNotEmpty(appversion) && appversion.equals("prod")
                ? baoFooPayConfig = (BaoFooPayConfig) paymentRequestDto.getPayConfigByClass(BaoFooPayConfig.class) : new BaoFooPayConfig();
        log.info(" baoFooPayConfig>> "+config);
        return config;
    }
    private BaoFooPayConfig initRefundConfig(RefundRequestDto refundRequestDto){
        return StringUtils.isNotEmpty(appversion) && appversion.equals("prod")
                ? baoFooPayConfig = (BaoFooPayConfig) refundRequestDto.getPayConfigByClass(BaoFooPayConfig.class) : new BaoFooPayConfig();
    }
}
