package com.xhpc.payment.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.*;
import com.alipay.api.domain.AlipayFundTransUniTransferModel;
import com.alipay.api.domain.Participant;
import com.alipay.api.request.AlipayFundTransUniTransferRequest;
import com.alipay.api.request.AlipayTradeFastpayRefundQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayFundTransUniTransferResponse;
import com.alipay.api.response.AlipayTradeFastpayRefundQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.service.transferbatch.TransferBatchService;
import com.wechat.pay.java.service.transferbatch.model.InitiateBatchTransferRequest;
import com.wechat.pay.java.service.transferbatch.model.InitiateBatchTransferResponse;
import com.wechat.pay.java.service.transferbatch.model.TransferDetailInput;
import com.xhpc.common.api.SmsService;
import com.xhpc.common.core.constant.HttpStatus;
import com.xhpc.common.core.constant.StatusConstants;
import com.xhpc.common.core.domain.R;
import com.xhpc.common.core.utils.DateUtils;
import com.xhpc.common.core.utils.StringUtils;
import com.xhpc.common.core.utils.WXPayUtil;
import com.xhpc.common.domain.XhpcRechargeOrder;
import com.xhpc.common.domain.XhpcRefundOrder;
import com.xhpc.common.domain.XhpcSettingConfig;
import com.xhpc.common.util.UserTypeUtil;
import com.xhpc.payment.domain.XhpcAppInternetUser;
import com.xhpc.payment.domain.XhpcAppUser;
import com.xhpc.payment.domain.XhpcRefundOriginalOrder;
import com.xhpc.payment.mapper.XhpcRefundOriginalOrderMapper;
import com.xhpc.payment.mapper.XhpcUserAccountStatementMapper;
import com.xhpc.payment.service.*;
import com.xhpc.payment.util.TransferBatchNotifyData;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.net.ssl.SSLContext;
import java.io.*;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyStore;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author yuyang
 * @date 2023-08-23 9:35
 */
@Service
public class XhpcRefundOriginalOrderServiceImpl implements IXhpcRefundOriginalOrderService {

    @Resource
    private XhpcRefundOriginalOrderMapper xhpcRefundOriginalOrderMapper;
    @Resource
    private IXhpcCommonPayment xhpcCommonPayment;
    @Resource
    private XhpcUserAccountStatementServiceImpl xhpcUserAccountStatementService;
    @Resource
    private IXhpcRechargeOrderService iXhpcRechargeOrderService;
    @Resource
    private XhpcUserAccountStatementMapper xhpcUserAccountStatementMapper;
    @Resource
    private IXhpcRefundAuditService iXhpcRefundAuditService;
    @Resource
    private IXhpcRefundOrderService iXhpcRefundOrderService;
    @Resource
    private SmsService smsService;

    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    private static final Logger logger = LoggerFactory.getLogger(XhpcRefundOriginalOrderServiceImpl.class);

    @Override
    public R zhbRefundOriginalOrder(Long refundOrderId) {

        Date date = new Date();
        String endTime = DateUtil.formatDateTime(date);
        LocalDateTime localDate = LocalDateTime.now().minusDays(363);
        String startTime = localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd  HH:mm:ss"));//转为String类型
        XhpcRefundOrder xhpcRefundOrder = xhpcRefundOriginalOrderMapper.getXhpcRefundOrder(refundOrderId);

        Map<String, Object> stringIntegerMap = xhpcRefundOriginalOrderMapper.compareTotalTimeMoney(refundOrderId, startTime, endTime);
        XhpcSettingConfig xhpcSettingConfig = xhpcCommonPayment.getXhpcSettingConfigTenantId(UserTypeUtil.OPERATION_ALI_PAY_TYPE,xhpcRefundOrder.getTenantId());
        if(xhpcSettingConfig ==null){
            return R.fail(HttpStatus.ALREADY_EXISTING, "支付宝退款失败,请联系客服");
        }
        if(stringIntegerMap !=null && stringIntegerMap.get("zfbStatus") !=null && stringIntegerMap.get("refundStatus") !=null){
            //查询退款金额
            BigDecimal amount = xhpcRefundOrder.getAmount();
            BigDecimal zfbMoney = new BigDecimal(stringIntegerMap.get("zfbMoney").toString());
            BigDecimal wxMoney = new BigDecimal(stringIntegerMap.get("wxMoney").toString());
            BigDecimal totalMoney = new BigDecimal(stringIntegerMap.get("totalMoney").toString());
            BigDecimal zero = new BigDecimal(0);
//            logger.info("=============endTime============="+endTime);
//            logger.info("=============startTime============="+startTime);
            //支付宝充值的金额大于退款金额
            if("1".equals(stringIntegerMap.get("zfbStatus").toString()) && zfbMoney.compareTo(zero)>0){
                List<XhpcRechargeOrder> xhpcRechargeOrderList = xhpcRefundOriginalOrderMapper.getXhpcRechargeOrderList(2, refundOrderId, startTime, endTime);
                for (int i = 0; i <xhpcRechargeOrderList.size() ; i++) {
                    XhpcRechargeOrder rechargeOrder = xhpcRechargeOrderList.get(i);
                    BigDecimal rechargeAmount = rechargeOrder.getAmount();//充值金额
                    BigDecimal refundFee = rechargeOrder.getRefundFee();//已退款总金额
                    String orderNumber = StringUtils.numFormat(rechargeOrder.getUserId(), 1, StatusConstants.FLOWING_WATER_REFUND_TYPE);
                    int number =0;//退款失败在调用一次
                    if(rechargeOrder.getRefundStatus()==0){
                        if(amount.compareTo(rechargeAmount)<=0) {
                            //退还一部分
                            R r = getalipayTradeRefund(xhpcSettingConfig, xhpcRefundOrder, rechargeOrder, amount, orderNumber, number);
                            if(r.getCode()==200){
                                //修改退款订单状态
                                updateXhpcRefundOrder(xhpcRefundOrder,refundFee,1,2);
                            }else{
                                updateXhpcRefundOrder(xhpcRefundOrder,refundFee,4,2);
                            }
                            return R.ok("支付宝退款成功");
                        }else{
                            //还差一部分
                            R r = getalipayTradeRefund(xhpcSettingConfig, xhpcRefundOrder, rechargeOrder, rechargeAmount, orderNumber, number);
                            if(r.getCode()==200){
                                amount = amount.subtract(rechargeAmount);
                            }
                        }
                    }else if(rechargeOrder.getRefundStatus()==1){
                        //该订单剩余金额
                        BigDecimal subtract = rechargeAmount.subtract(refundFee);
                        if(amount.compareTo(subtract)<=0) {
                            //退还一部分
                            R r = getalipayTradeRefund(xhpcSettingConfig, xhpcRefundOrder, rechargeOrder, amount, orderNumber, number);
                            if(r.getCode()==200){
                                //修改退款订单状态
                                updateXhpcRefundOrder(xhpcRefundOrder,refundFee,1,2);
                            }else{
                                updateXhpcRefundOrder(xhpcRefundOrder,refundFee,4,2);
                            }
                            return R.ok("支付宝退款成功");
                        }else{
                            //还差一部分
                            R r =getalipayTradeRefund(xhpcSettingConfig,xhpcRefundOrder,rechargeOrder,subtract,orderNumber,number);
                            if(r.getCode()==200){
                                amount = amount.subtract(subtract);
                            }
                        }
                    }
                }
            }else if("2".equals(stringIntegerMap.get("zfbStatus").toString()) && "1".equals(stringIntegerMap.get("refundStatus").toString())){
                //支付宝充值的金额 小于支付宝微信总充值的金额
                if(UserTypeUtil.USER_TYPE.equals(xhpcRefundOrder.getSource())){
                    if(zfbMoney.compareTo(zero)>0){
                        List<XhpcRechargeOrder> xhpcRechargeOrderList = xhpcRefundOriginalOrderMapper.getXhpcRechargeOrderList(2, refundOrderId, startTime, endTime);
                        for (int i = 0; i <xhpcRechargeOrderList.size() ; i++) {
                            XhpcRechargeOrder rechargeOrder = xhpcRechargeOrderList.get(i);
                            BigDecimal rechargeAmount = rechargeOrder.getAmount();//充值金额
                            BigDecimal refundFee = rechargeOrder.getRefundFee();//已退款总金额
                            String orderNumber = StringUtils.numFormat(11L, 1, StatusConstants.FLOWING_WATER_REFUND_TYPE);
                            int number =0;//退款失败在调用一次
                            if(rechargeOrder.getRefundStatus()==0){
                                R r = getalipayTradeRefund(xhpcSettingConfig, xhpcRefundOrder, rechargeOrder, rechargeAmount, orderNumber, number);
                                if(r.getCode()==200){
                                    amount = amount.subtract(rechargeAmount);
                                }
                            }else{
                                //该订单剩余金额
                                BigDecimal subtract = rechargeAmount.subtract(refundFee);
                                R r =getalipayTradeRefund(xhpcSettingConfig,xhpcRefundOrder,rechargeOrder,subtract,orderNumber,number);
                                if(r.getCode()==200){
                                    amount = amount.subtract(subtract);
                                }
                            }
                        }
                    }
                    //微信退款
                    return wxRefund(xhpcRefundOrder, amount);
                }else if(UserTypeUtil.COMMUNIT_TYPE.equals(xhpcRefundOrder.getSource())){

                    if(zfbMoney.compareTo(zero)>0){
                        //支付宝微信都有充值记录且大于退款金额
                        List<XhpcRechargeOrder> xhpcRechargeOrderList = xhpcRefundOriginalOrderMapper.getXhpcRechargeOrderList(2, refundOrderId, startTime, endTime);
                        for (int i = 0; i <xhpcRechargeOrderList.size() ; i++) {
                            XhpcRechargeOrder rechargeOrder = xhpcRechargeOrderList.get(i);
                            BigDecimal rechargeAmount = rechargeOrder.getAmount();//充值金额
                            BigDecimal refundFee = rechargeOrder.getRefundFee();//已退款总金额
                            String orderNumber = StringUtils.numFormat(11L, 1, StatusConstants.FLOWING_WATER_REFUND_TYPE);
                            int number =0;//退款失败在调用一次
                            if(rechargeOrder.getRefundStatus()==0){
                                if(amount.compareTo(rechargeAmount)<=0) {
                                    //退还一部分
                                    R r = getalipayTradeRefund(xhpcSettingConfig, xhpcRefundOrder, rechargeOrder, amount, orderNumber, number);
                                    if(r.getCode()==200){
                                        //修改退款订单状态
                                        updateXhpcRefundOrder(xhpcRefundOrder,refundFee,1,2);
                                    }else{
                                        updateXhpcRefundOrder(xhpcRefundOrder,refundFee,4,2);
                                    }
                                    return R.ok("支付宝退款成功");
                                }else{
                                    //还差一部分
                                    R r = getalipayTradeRefund(xhpcSettingConfig, xhpcRefundOrder, rechargeOrder, rechargeAmount, orderNumber, number);
                                    if(r.getCode()==200){
                                        amount = amount.subtract(rechargeAmount);
                                    }
                                }
                            }else if(rechargeOrder.getRefundStatus()==1){
                                //该订单剩余金额
                                BigDecimal subtract = rechargeAmount.subtract(refundFee);
                                if(amount.compareTo(subtract)<=0) {
                                    //退还一部分
                                    R r = getalipayTradeRefund(xhpcSettingConfig, xhpcRefundOrder, rechargeOrder, amount, orderNumber, number);
                                    if(r.getCode()==200){
                                        //修改退款订单状态
                                        updateXhpcRefundOrder(xhpcRefundOrder,refundFee,1,2);
                                    }else{
                                        updateXhpcRefundOrder(xhpcRefundOrder,refundFee,4,2);
                                    }
                                    return R.ok("支付宝退款成功");
                                }else{
                                    //还差一部分
                                    R r =getalipayTradeRefund(xhpcSettingConfig,xhpcRefundOrder,rechargeOrder,subtract,orderNumber,number);
                                    if(r.getCode()==200){
                                        amount = amount.subtract(subtract);
                                    }
                                }
                            }
                        }
                    }
                    if(wxMoney.compareTo(zero)>0){
                        R r = wxRefund(xhpcRefundOrder, amount);
                        Map<String, Object> map = (Map<String, Object>)r.getData();
                        if(map !=null && map.get("refundFee") !=null){
                            //零钱图款
                            amount = new BigDecimal(map.get("refundFee").toString());
                        }
                    }
                    if(zfbMoney.add(wxMoney).compareTo(amount)<0){
                        if(zero.compareTo(amount)<0){
                            zhbCheckOut(xhpcSettingConfig,xhpcRefundOrder,amount);
                        }
                    }
                }
            }else if("2".equals(stringIntegerMap.get("zfbStatus").toString()) && "2".equals(stringIntegerMap.get("refundStatus").toString())){
                //查询该用所有充值记录
                Map<String, Object> objectMap = xhpcRefundOriginalOrderMapper.compareTotalMoney(xhpcRefundOrder.getUserId(), xhpcRefundOrder.getSource());
                BigDecimal totalAmount = new BigDecimal(objectMap.get("totalAmount").toString());
                //支付宝充值的金额 小于(支付宝+微信)总充值的金额
                if(UserTypeUtil.USER_TYPE.equals(xhpcRefundOrder.getSource()) || UserTypeUtil.COMMUNIT_TYPE.equals(xhpcRefundOrder.getSource())){
                    if(totalAmount.compareTo(amount)>=0){
                        //支付宝微信都有充值记录且大于退款金额
                        List<XhpcRechargeOrder> xhpcRechargeOrderList = xhpcRefundOriginalOrderMapper.getXhpcRechargeOrderList(2, refundOrderId, startTime, endTime);
                        for (int i = 0; i <xhpcRechargeOrderList.size() ; i++) {
                            XhpcRechargeOrder rechargeOrder = xhpcRechargeOrderList.get(i);
                            BigDecimal rechargeAmount = rechargeOrder.getAmount();//充值金额
                            BigDecimal refundFee = rechargeOrder.getRefundFee();//已退款总金额
                            String orderNumber = StringUtils.numFormat(11L, 1, StatusConstants.FLOWING_WATER_REFUND_TYPE);
                            int number =0;//退款失败在调用一次
                            if(rechargeOrder.getRefundStatus()==0){
                                if(amount.compareTo(rechargeAmount)<=0) {
                                    //退还一部分
                                    R r = getalipayTradeRefund(xhpcSettingConfig, xhpcRefundOrder, rechargeOrder, amount, orderNumber, number);
                                    if(r.getCode()==200){
                                        //修改退款订单状态
                                        updateXhpcRefundOrder(xhpcRefundOrder,refundFee,1,2);
                                    }else{
                                        updateXhpcRefundOrder(xhpcRefundOrder,refundFee,4,2);
                                    }
                                    return R.ok("支付宝退款成功");
                                }else{
                                    //还差一部分
                                    R r = getalipayTradeRefund(xhpcSettingConfig, xhpcRefundOrder, rechargeOrder, rechargeAmount, orderNumber, number);
                                    if(r.getCode()==200){
                                        amount = amount.subtract(rechargeAmount);
                                    }
                                }
                            }else if(rechargeOrder.getRefundStatus()==1){
                                //该订单剩余金额
                                BigDecimal subtract = rechargeAmount.subtract(refundFee);
                                if(amount.compareTo(subtract)<=0) {
                                    //退还一部分
                                    R r = getalipayTradeRefund(xhpcSettingConfig, xhpcRefundOrder, rechargeOrder, amount, orderNumber, number);
                                    if(r.getCode()==200){
                                        //修改退款订单状态
                                        updateXhpcRefundOrder(xhpcRefundOrder,refundFee,1,2);
                                    }else{
                                        updateXhpcRefundOrder(xhpcRefundOrder,refundFee,4,2);
                                    }
                                    return R.ok("支付宝退款成功");
                                }else{
                                    //还差一部分
                                    R r =getalipayTradeRefund(xhpcSettingConfig,xhpcRefundOrder,rechargeOrder,subtract,orderNumber,number);
                                    if(r.getCode()==200){
                                        amount = amount.subtract(subtract);
                                    }
                                }
                            }
                        }
                        if(wxMoney.compareTo(zero)>0){
                            //微信退款
                            R r = wxRefund(xhpcRefundOrder, amount);
                            Map<String, Object> map = (Map<String, Object>)r.getData();
                            if(map !=null && map.get("refundFee") !=null){
                                //零钱图款
                                BigDecimal bigDecimal = new BigDecimal(map.get("refundFee").toString());
                                if(zero.compareTo(bigDecimal)<0){
                                    zhbCheckOut(xhpcSettingConfig,xhpcRefundOrder,bigDecimal);
                                }
                            }
                        }else{
                            zhbCheckOut(xhpcSettingConfig,xhpcRefundOrder,amount);
                        }

                        return R.ok("支付宝退款成功");
                    }else{
                        // 没有这种情况，出现则需要通知管理员
                        return R.fail("退款异常订单,请管理员进行查看");
                    }
                }
            }else{
                // 没有这种情况，出现则需要通知管理员
                return R.fail("退款异常订单,请管理员进行查看！！");
            }

        }
        return R.ok("支付宝退款成功");
    }


    @Override
    public R wxRefundOriginalOrder(Long refundOrderId) {
        Date date = new Date();
        String endTime = DateUtil.formatDateTime(date);
        LocalDateTime localDate = LocalDateTime.now().minusDays(363);
        String startTime = localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd  HH:mm:ss"));//转为String类型
        XhpcRefundOrder xhpcRefundOrder = xhpcRefundOriginalOrderMapper.getXhpcRefundOrder(refundOrderId);

        XhpcSettingConfig xhpcSettingConfig = xhpcCommonPayment.getXhpcSettingConfigTenantId(UserTypeUtil.OPERATION_WX_TYPE,xhpcRefundOrder.getTenantId());
        if(xhpcSettingConfig ==null){
            return R.fail(HttpStatus.ALREADY_EXISTING, "微信退款失败,请联系客服");
        }

        Map<String, Object> stringIntegerMap = xhpcRefundOriginalOrderMapper.compareTotalTimeMoney(refundOrderId, startTime, endTime);
        if(stringIntegerMap !=null && stringIntegerMap.get("wxStatus") !=null && stringIntegerMap.get("refundStatus") !=null){
            //查询退款金额
            BigDecimal amount = xhpcRefundOrder.getAmount();
            BigDecimal zfbMoney = new BigDecimal(stringIntegerMap.get("zfbMoney").toString());
            BigDecimal wxMoney = new BigDecimal(stringIntegerMap.get("wxMoney").toString());
            BigDecimal totalMoney = new BigDecimal(stringIntegerMap.get("totalMoney").toString());
            BigDecimal zero = new BigDecimal(0);
            //微信充值的金额大于退款金额
            if("1".equals(stringIntegerMap.get("wxStatus").toString()) && wxMoney.compareTo(zero)>0){
                System.out.println("===========微信充值的金额大于退款金额==================");
                return wxRefund(xhpcRefundOrder,amount);
            }else if("2".equals(stringIntegerMap.get("wxStatus").toString()) && "1".equals(stringIntegerMap.get("refundStatus").toString())){
                //微信充值的金额 小于（支付宝+微信）总充值的金额
                if(UserTypeUtil.USER_TYPE.equals(xhpcRefundOrder.getSource())){
                    BigDecimal bigDecimal = amount;
                    if(wxMoney.compareTo(zero)>0){
                        R r1 = wxRefund(xhpcRefundOrder, amount);
                        if(r1.getCode()==200){
                            Map<String, Object> map = (Map<String, Object>)r1.getData();
                            if(map !=null && map.get("refundFee") !=null){
                                bigDecimal = new BigDecimal(map.get("refundFee").toString());
                            }
                        }
                    }
                    List<XhpcRechargeOrder> xhpcRechargeOrderList = xhpcRefundOriginalOrderMapper.getXhpcRechargeOrderList(2, refundOrderId, startTime, endTime);
                    for (int i = 0; i <xhpcRechargeOrderList.size() ; i++) {
                        XhpcRechargeOrder rechargeOrder = xhpcRechargeOrderList.get(i);
                        BigDecimal rechargeAmount = rechargeOrder.getAmount();//充值金额
                        BigDecimal refundFee = rechargeOrder.getRefundFee();//已退款总金额
                        String orderNumber = StringUtils.numFormat(11L, 1, StatusConstants.FLOWING_WATER_REFUND_TYPE);
                        int number =0;//退款失败在调用一次
                        if(rechargeOrder.getRefundStatus()==0){
                            if(bigDecimal.compareTo(rechargeAmount)>=0){
                                R r = getalipayTradeRefund(xhpcSettingConfig, xhpcRefundOrder, rechargeOrder, rechargeAmount, orderNumber, number);
                                if(r.getCode()==200){
                                    bigDecimal = bigDecimal.subtract(rechargeAmount);
                                    if(i==xhpcRechargeOrderList.size()-1){
                                        updateXhpcRefundOrder(xhpcRefundOrder,refundFee,1,2);
                                    }
                                }
                            }else{
                                R r = getalipayTradeRefund(xhpcSettingConfig, xhpcRefundOrder, rechargeOrder, bigDecimal, orderNumber, number);
                                if(r.getCode()==200){
                                    updateXhpcRefundOrder(xhpcRefundOrder,refundFee,1,2);
                                }else{
                                    updateXhpcRefundOrder(xhpcRefundOrder,refundFee,4,2);
                                }
                                return R.ok("退款订单已提交支付宝,退款中...");
                            }
                        }else{
                            BigDecimal subtract1 = rechargeAmount.subtract(rechargeOrder.getRefundFee());
                            if(bigDecimal.compareTo(subtract1)>=0){
                                R r = getalipayTradeRefund(xhpcSettingConfig, xhpcRefundOrder, rechargeOrder, subtract1, orderNumber, number);
                                if(r.getCode()==200){
                                    bigDecimal = bigDecimal.subtract(rechargeAmount);
                                    if(i==xhpcRechargeOrderList.size()-1){
                                        updateXhpcRefundOrder(xhpcRefundOrder,refundFee,1,2);
                                    }
                                }
                            }else{
                                R r = getalipayTradeRefund(xhpcSettingConfig, xhpcRefundOrder, rechargeOrder, bigDecimal, orderNumber, number);
                                if(r.getCode()==200){
                                    //修改退款订单状态
                                    updateXhpcRefundOrder(xhpcRefundOrder,refundFee,1,2);
                                }else{
                                    updateXhpcRefundOrder(xhpcRefundOrder,refundFee,4,2);
                                }
                                return R.ok("退款订单已提交支付宝,退款中...");
                            }
                        }
                    }
                    return R.ok("C端用户退款成功");
                }else if(UserTypeUtil.COMMUNIT_TYPE.equals(xhpcRefundOrder.getSource())){
                    BigDecimal bigDecimal = amount;
                    if(wxMoney.compareTo(zero)>0){
                        R r1 = wxRefund(xhpcRefundOrder, amount);
                        if(r1.getCode()==200){
                            Map<String, Object> map = (Map<String, Object>)r1.getData();
                            if(map !=null && map.get("refundFee") !=null){
                                bigDecimal = new BigDecimal(map.get("refundFee").toString());
                            }
                        }
                    }
                    if(zfbMoney.compareTo(zero)>0){
                        List<XhpcRechargeOrder> xhpcRechargeOrderList = xhpcRefundOriginalOrderMapper.getXhpcRechargeOrderList(2, refundOrderId, startTime, endTime);
                        for (int i = 0; i <xhpcRechargeOrderList.size() ; i++) {
                            XhpcRechargeOrder rechargeOrder = xhpcRechargeOrderList.get(i);
                            BigDecimal rechargeAmount = rechargeOrder.getAmount();//充值金额
                            BigDecimal refundFee = rechargeOrder.getRefundFee();//已退款总金额
                            String orderNumber = StringUtils.numFormat(11L, 1, StatusConstants.FLOWING_WATER_REFUND_TYPE);
                            int number =0;//退款失败在调用一次
                            if(rechargeOrder.getRefundStatus()==0){
                                if(bigDecimal.compareTo(rechargeAmount)>=0){
                                    R r = getalipayTradeRefund(xhpcSettingConfig, xhpcRefundOrder, rechargeOrder, rechargeAmount, orderNumber, number);
                                    if(r.getCode()==200){
                                        bigDecimal = bigDecimal.subtract(rechargeAmount);
                                    }
                                }else{
                                    R r = getalipayTradeRefund(xhpcSettingConfig, xhpcRefundOrder, rechargeOrder, bigDecimal, orderNumber, number);
                                    if(r.getCode()==200){
                                        updateXhpcRefundOrder(xhpcRefundOrder,refundFee,1,2);
                                    }else{
                                        updateXhpcRefundOrder(xhpcRefundOrder,refundFee,4,2);
                                    }
                                    return R.ok("退款订单已提交支付宝,退款中...");
                                }
                            }else{
                                BigDecimal subtract1 = rechargeAmount.subtract(rechargeOrder.getRefundFee());
                                if(bigDecimal.compareTo(subtract1)>=0){
                                    R r = getalipayTradeRefund(xhpcSettingConfig, xhpcRefundOrder, rechargeOrder, subtract1, orderNumber, number);
                                    if(r.getCode()==200){
                                        bigDecimal = bigDecimal.subtract(rechargeAmount);
                                    }
                                }else{
                                    R r = getalipayTradeRefund(xhpcSettingConfig, xhpcRefundOrder, rechargeOrder, bigDecimal, orderNumber, number);
                                    if(r.getCode()==200){
                                        //修改退款订单状态
                                        updateXhpcRefundOrder(xhpcRefundOrder,refundFee,1,2);
                                    }else{
                                        updateXhpcRefundOrder(xhpcRefundOrder,refundFee,4,2);
                                    }
                                    return R.ok("退款订单已提交支付宝,退款中...");
                                }
                            }
                        }
                    }
                    //微信退款
                    if(zfbMoney.add(wxMoney).compareTo(amount)<0){
                        if(zero.compareTo(bigDecimal)<0){
                            wxCheckOut(xhpcRefundOrder,bigDecimal);
                        }
                    }
                    return R.ok("社区用户退款成功");
                }
            }else if("2".equals(stringIntegerMap.get("wxStatus").toString()) && "2".equals(stringIntegerMap.get("refundStatus").toString())){
                //查询该用所有充值记录
                Map<String, Object> objectMap = xhpcRefundOriginalOrderMapper.compareTotalMoney(xhpcRefundOrder.getUserId(), xhpcRefundOrder.getSource());
                BigDecimal totalAmount = new BigDecimal(objectMap.get("totalAmount").toString());
                //微信充值的金额 小于（支付宝+微信）总充值的金额
                if(totalAmount.compareTo(amount)>=0){
                    //支付宝微信都有充值记录且大于退款金额
                    List<XhpcRechargeOrder> xhpcRechargeOrderList = xhpcRefundOriginalOrderMapper.getXhpcRechargeOrderList(2, refundOrderId, startTime, endTime);
                    for (int i = 0; i <xhpcRechargeOrderList.size() ; i++) {
                        XhpcRechargeOrder rechargeOrder = xhpcRechargeOrderList.get(i);
                        BigDecimal rechargeAmount = rechargeOrder.getAmount();//充值金额
                        BigDecimal refundFee = rechargeOrder.getRefundFee();//已退款总金额
                        String orderNumber = StringUtils.numFormat(11L, 1, StatusConstants.FLOWING_WATER_REFUND_TYPE);
                        int number =0;//退款失败在调用一次
                        if(rechargeOrder.getRefundStatus()==0){
                            if(amount.compareTo(rechargeAmount)<=0) {
                                //退还一部分
                                R r = getalipayTradeRefund(xhpcSettingConfig, xhpcRefundOrder, rechargeOrder, amount, orderNumber, number);
                                if(r.getCode()==200){
                                    //修改退款订单状态
                                    updateXhpcRefundOrder(xhpcRefundOrder,refundFee,1,2);
                                }else{
                                    updateXhpcRefundOrder(xhpcRefundOrder,refundFee,4,2);
                                }
                                return R.ok("退款订单已提交支付宝,退款中...");
                            }else{
                                //还差一部分
                                R r = getalipayTradeRefund(xhpcSettingConfig, xhpcRefundOrder, rechargeOrder, rechargeAmount, orderNumber, number);
                                if(r.getCode()==200){
                                    amount = amount.subtract(rechargeAmount);
                                }
                            }
                        }else if(rechargeOrder.getRefundStatus()==1){
                            //该订单剩余金额
                            BigDecimal subtract = rechargeAmount.subtract(refundFee);
                            if(amount.compareTo(subtract)<=0) {
                                //退还一部分
                                R r = getalipayTradeRefund(xhpcSettingConfig, xhpcRefundOrder, rechargeOrder, amount, orderNumber, number);
                                if(r.getCode()==200){
                                    //修改退款订单状态
                                    updateXhpcRefundOrder(xhpcRefundOrder,refundFee,1,2);
                                }else{
                                    updateXhpcRefundOrder(xhpcRefundOrder,refundFee,4,2);
                                }
                                return R.ok("退款订单已提交支付宝,退款中...");
                            }else{
                                //还差一部分
                                R r =getalipayTradeRefund(xhpcSettingConfig,xhpcRefundOrder,rechargeOrder,subtract,orderNumber,number);
                                if(r.getCode()==200){
                                    amount = amount.subtract(subtract);
                                }
                            }
                        }
                    }
                    if(wxMoney.compareTo(zero)>0){
                        //微信退款
                        R r = wxRefund(xhpcRefundOrder, amount);
                        Map<String, Object> map = (Map<String, Object>)r.getData();
                        if(map !=null && map.get("refundFee") !=null){
                            //零钱图款
                            BigDecimal bigDecimal = new BigDecimal(map.get("refundFee").toString());
                            if(zero.compareTo(bigDecimal)<0){
                                wxCheckOut(xhpcRefundOrder,bigDecimal);
                            }
                        }
                    }else{
                        wxCheckOut(xhpcRefundOrder,amount);
                    }
                    return R.ok();
                }
            }
        }
        return R.ok();
    }

    @Override
    public void updateXhpcRefundOriginalOrderV3(TransferBatchNotifyData notifyData) {

        XhpcRefundOriginalOrder xhpcRefundOriginalOrder = xhpcRefundOriginalOrderMapper.getXhpcRefundOriginalOrderRefundId(notifyData.getBatchId());
        if(xhpcRefundOriginalOrder !=null){
            if ("FINISHED".equals(notifyData.getBatchStatus())) {
                //退款成功
                xhpcRefundOriginalOrder.setStatus(1);
                BigDecimal refundFeeAmount = xhpcRefundOriginalOrder.getRefundFee();

                XhpcRechargeOrder xhpcRechargeOrder = xhpcRefundOriginalOrderMapper.getXhpcRechargeOrder(xhpcRefundOriginalOrder.getRechargeOrderId());
                BigDecimal amount = xhpcRechargeOrder.getAmount();
                if(xhpcRechargeOrder.getRefundStatus()==0){
                    //修改支付订单付款金额和状态
                    if(amount.compareTo(refundFeeAmount)==0){
                        //全部退完
                        iXhpcRechargeOrderService.updateRechargeOrderFeundFee(xhpcRechargeOrder.getRechargeOrderId(),amount,2);
                    }else if(amount.compareTo(refundFeeAmount)>0){
                        //退了一部分
                        iXhpcRechargeOrderService.updateRechargeOrderFeundFee(xhpcRechargeOrder.getRechargeOrderId(),refundFeeAmount,1);
                    }
                }else{
                    BigDecimal subtract = xhpcRechargeOrder.getAmount().subtract(xhpcRechargeOrder.getRefundFee());
                    //修改支付订单付款金额和状态
                    if(subtract.compareTo(refundFeeAmount)==0){
                        //全部退完
                        iXhpcRechargeOrderService.updateRechargeOrderFeundFee(xhpcRechargeOrder.getRechargeOrderId(),amount,2);
                    }else if(subtract.compareTo(refundFeeAmount)>0){
                        //退了一部分
                        iXhpcRechargeOrderService.updateRechargeOrderFeundFee(xhpcRechargeOrder.getRechargeOrderId(),xhpcRechargeOrder.getRefundFee().add(refundFeeAmount),1);
                    }
                }
                //修改用户金额
                Long userId = xhpcRefundOriginalOrder.getUserId();
                Integer source = xhpcRefundOriginalOrder.getSource();
                //增加用户流水记录
                xhpcUserAccountStatementService.add(xhpcRefundOriginalOrder.getRefundOrderId(), "-"+refundFeeAmount.toString(), userId.toString(), StatusConstants.FLOWING_WATER_REFUND,source,xhpcRefundOriginalOrder.getTenantId());
                if(UserTypeUtil.USER_TYPE.equals(source)){
                    Map<String, Object> appUserInfo = xhpcUserAccountStatementMapper.appUserInfo(userId);
                    String balance = StringUtils.valueOf(appUserInfo.get("balance"));
                    //减少用户余额
                    XhpcAppUser xhpcAppUser = new XhpcAppUser();
                    xhpcAppUser.setAppUserId(userId);
                    BigDecimal surplus =new BigDecimal(balance).subtract(refundFeeAmount);
                    xhpcAppUser.setBalance(surplus);
                    if(xhpcRefundOriginalOrder.getLastOne()==1){
                        xhpcAppUser.setIsRefundApplication(0);
                    }
                    xhpcUserAccountStatementMapper.updateAppUserBalance(xhpcAppUser);

                    if(surplus.compareTo(new BigDecimal(0))==0){
                        xhpcRefundOriginalOrderMapper.updateRechargeOrderRefundStatus(userId,source);
                    }
                }else if(UserTypeUtil.COMMUNIT_TYPE.equals(source)){
                    Map<String, Object> communityPersonnel = iXhpcRefundAuditService.getCommunityPersonnelById(userId, xhpcRefundOriginalOrder.getTenantId());
                    BigDecimal surplus =new BigDecimal(communityPersonnel.get("balance").toString()).subtract(refundFeeAmount);
                    if(xhpcRefundOriginalOrder.getLastOne()==1){
                        int i = iXhpcRefundAuditService.updateCommunityPersonnelMoney(userId, surplus,0);
                    }else{
                        int i = iXhpcRefundAuditService.updateCommunityPersonnelMoney(userId, surplus,null);
                    }
                    if(surplus.compareTo(new BigDecimal(0))==0){
                        xhpcRefundOriginalOrderMapper.updateRechargeOrderRefundStatus(userId,source);
                    }
                }else if(UserTypeUtil.INTERNET_TYPE.equals(source) && userId>10000){
                    System.out.println("=================查询微信支付信息==========修改金额=======================");
                    System.out.println("=================查询微信支付信息==========修改金额=======================");
                    Map<String, Object> appUserInfo = xhpcUserAccountStatementMapper.getAppInternetUser(userId);
                    String balance = StringUtils.valueOf(appUserInfo.get("balance"));
                    //减少用户余额
                    XhpcAppInternetUser xhpcAppUser = new XhpcAppInternetUser();
                    xhpcAppUser.setAppInternetUserId(userId);
                    BigDecimal surplus =new BigDecimal(balance).subtract(refundFeeAmount);
                    xhpcAppUser.setBalance(surplus);
                    if(xhpcRefundOriginalOrder.getLastOne()==1){
                        xhpcAppUser.setIsRefundApplication(0);
                    }
                    xhpcUserAccountStatementMapper.updateAppInternetUserBalance(xhpcAppUser);
                    if(surplus.compareTo(new BigDecimal(0))==0){
                        xhpcRefundOriginalOrderMapper.updateRechargeOrderRefundStatus(userId,source);
                    }
                }
            }else{
                //退款失败
                xhpcRefundOriginalOrder.setStatus(2);
            }

            xhpcRefundOriginalOrderMapper.updateXhpcRefundOriginalOrder(xhpcRefundOriginalOrder);

        }
    }

    @Override
    public void updateXhpcRefundOriginalOrder(Map<String, String> reqInfo) {
        XhpcRefundOriginalOrder xhpcRefundOriginalOrder = xhpcRefundOriginalOrderMapper.getXhpcRefundOriginalOrderRefundId(reqInfo.get("refund_id").toString());
        if(xhpcRefundOriginalOrder !=null){
            if(reqInfo.get("refund_status").equals("SUCCESS")){
                //查询微信支付信息
//                boolean couponRefundFee =false;
//                try{
//                    Map<String, String> stringStringMap = refundqueryUrl(xhpcRefundOriginalOrder.getTransactionId());
//                    if(stringStringMap !=null && "SUCCESS".equals(stringStringMap.get("result_code"))&& "SUCCESS".equals(stringStringMap.get("return_code"))){
//                        if(xhpcRefundOriginalOrder.getRefundFee().compareTo(new BigDecimal(stringStringMap.get("cash_fee").toString()))>0){
//                            //说明用户充值时有优惠券
//                            if(stringStringMap.get("coupon_refund_fee") !=null){
//                                xhpcRefundOriginalOrder.setCouponRefundFee(new BigDecimal(stringStringMap.get("coupon_refund_fee").toString()));
//                                couponRefundFee=true;
//                            }
//                        }
//                    }
//                }catch (Exception e){
//                    System.out.println("=============微信订单查询失败==============");
//                }
                //退款成功
                xhpcRefundOriginalOrder.setStatus(1);
                BigDecimal refundFeeAmount = xhpcRefundOriginalOrder.getRefundFee();
//                BigDecimal refundFeeAmount =new BigDecimal(0);
//                if(couponRefundFee){
//                    refundFeeAmount = xhpcRefundOriginalOrder.getCashRefundFee().add(xhpcRefundOriginalOrder.getCouponRefundFee());
//                }else{
//                    refundFeeAmount = xhpcRefundOriginalOrder.getCashRefundFee();
//                }
                XhpcRechargeOrder xhpcRechargeOrder = xhpcRefundOriginalOrderMapper.getXhpcRechargeOrder(xhpcRefundOriginalOrder.getRechargeOrderId());
                BigDecimal amount = xhpcRechargeOrder.getAmount();
                if(xhpcRechargeOrder.getRefundStatus()==0){
                    //修改支付订单付款金额和状态
                    if(amount.compareTo(refundFeeAmount)==0){
                        //全部退完
                        iXhpcRechargeOrderService.updateRechargeOrderFeundFee(xhpcRechargeOrder.getRechargeOrderId(),amount,2);
                    }else if(amount.compareTo(refundFeeAmount)>0){
                        //退了一部分
                        iXhpcRechargeOrderService.updateRechargeOrderFeundFee(xhpcRechargeOrder.getRechargeOrderId(),refundFeeAmount,1);
                    }
                }else{
                    BigDecimal subtract = xhpcRechargeOrder.getAmount().subtract(xhpcRechargeOrder.getRefundFee());
                    //修改支付订单付款金额和状态
                    if(subtract.compareTo(refundFeeAmount)==0){
                        //全部退完
                        iXhpcRechargeOrderService.updateRechargeOrderFeundFee(xhpcRechargeOrder.getRechargeOrderId(),amount,2);
                    }else if(subtract.compareTo(refundFeeAmount)>0){
                        //退了一部分
                        iXhpcRechargeOrderService.updateRechargeOrderFeundFee(xhpcRechargeOrder.getRechargeOrderId(),xhpcRechargeOrder.getRefundFee().add(refundFeeAmount),1);
                    }
                }
                //修改用户金额
                Long userId = xhpcRefundOriginalOrder.getUserId();
                Integer source = xhpcRefundOriginalOrder.getSource();
                //增加用户流水记录
                xhpcUserAccountStatementService.add(xhpcRefundOriginalOrder.getRefundOrderId(), "-"+refundFeeAmount.toString(), userId.toString(), StatusConstants.FLOWING_WATER_REFUND,source,xhpcRefundOriginalOrder.getTenantId());
                if(UserTypeUtil.USER_TYPE.equals(source)){
                    Map<String, Object> appUserInfo = xhpcUserAccountStatementMapper.appUserInfo(userId);
                    String balance = StringUtils.valueOf(appUserInfo.get("balance"));
                    //减少用户余额
                    XhpcAppUser xhpcAppUser = new XhpcAppUser();
                    xhpcAppUser.setAppUserId(userId);
                    BigDecimal surplus =new BigDecimal(balance).subtract(refundFeeAmount);
                    xhpcAppUser.setBalance(surplus);
                    if(xhpcRefundOriginalOrder.getLastOne()==1){
                        xhpcAppUser.setIsRefundApplication(0);
                    }
                    xhpcUserAccountStatementMapper.updateAppUserBalance(xhpcAppUser);

                    if(surplus.compareTo(new BigDecimal(0))==0){
                        xhpcRefundOriginalOrderMapper.updateRechargeOrderRefundStatus(userId,source);
                    }
                }else if(UserTypeUtil.COMMUNIT_TYPE.equals(source)){
                    Map<String, Object> communityPersonnel = iXhpcRefundAuditService.getCommunityPersonnelById(userId, xhpcRefundOriginalOrder.getTenantId());
                    BigDecimal surplus =new BigDecimal(communityPersonnel.get("balance").toString()).subtract(refundFeeAmount);
                    if(xhpcRefundOriginalOrder.getLastOne()==1){
                        int i = iXhpcRefundAuditService.updateCommunityPersonnelMoney(userId, surplus,0);
                    }else{
                        int i = iXhpcRefundAuditService.updateCommunityPersonnelMoney(userId, surplus,null);
                    }
                    if(surplus.compareTo(new BigDecimal(0))==0){
                        xhpcRefundOriginalOrderMapper.updateRechargeOrderRefundStatus(userId,source);
                    }
                }else if(UserTypeUtil.INTERNET_TYPE.equals(source) && userId>10000){
                    System.out.println("=================查询微信支付信息==========修改金额=======================");
                    System.out.println("=================查询微信支付信息==========修改金额=======================");
                    Map<String, Object> appUserInfo = xhpcUserAccountStatementMapper.getAppInternetUser(userId);
                    String balance = StringUtils.valueOf(appUserInfo.get("balance"));
                    //减少用户余额
                    XhpcAppInternetUser xhpcAppUser = new XhpcAppInternetUser();
                    xhpcAppUser.setAppInternetUserId(userId);
                    BigDecimal surplus =new BigDecimal(balance).subtract(refundFeeAmount);
                    xhpcAppUser.setBalance(surplus);
                    if(xhpcRefundOriginalOrder.getLastOne()==1){
                        xhpcAppUser.setIsRefundApplication(0);
                    }
                    xhpcUserAccountStatementMapper.updateAppInternetUserBalance(xhpcAppUser);
                    if(surplus.compareTo(new BigDecimal(0))==0){
                        xhpcRefundOriginalOrderMapper.updateRechargeOrderRefundStatus(userId,source);
                    }
                }
            }else{
                //退款失败
                xhpcRefundOriginalOrder.setStatus(2);
            }
            if(reqInfo.get("settlement_total_fee") !=null && !"".equals(reqInfo.get("settlement_total_fee"))){
                xhpcRefundOriginalOrder.setSettlementTotalFee(new BigDecimal(reqInfo.get("settlement_total_fee")).divide(new BigDecimal(100)));
            }
            xhpcRefundOriginalOrder.setRefundStatus(reqInfo.get("refund_status"));
            if(reqInfo.get("success_time") !=null && !"".equals(reqInfo.get("success_time"))){
                xhpcRefundOriginalOrder.setSuccessTime(reqInfo.get("success_time"));
            }
            xhpcRefundOriginalOrder.setRefundRecvAccout(reqInfo.get("refund_recv_accout"));
            xhpcRefundOriginalOrder.setRefundAccount(reqInfo.get("refund_account"));
            xhpcRefundOriginalOrder.setRefundRequestSource(reqInfo.get("refund_request_source"));

            xhpcRefundOriginalOrderMapper.updateXhpcRefundOriginalOrder(xhpcRefundOriginalOrder);
        }
    }

    //微信退款原路退回
    public R getWxTradeRefundYu(XhpcRefundOrder xhpcRefundOrder,XhpcRechargeOrder rechargeOrder,String orderNumber,BigDecimal refundFee,Integer type){
        try {
            readWriteLock.writeLock().lock();//取
            XhpcSettingConfig config  = xhpcCommonPayment.getXhpcSettingConfigTenantId(UserTypeUtil.OPERATION_WX_TYPE, rechargeOrder.getTenantId());

            if (config == null) {
                return R.fail(HttpStatus.ALREADY_EXISTING, "微信退款配置缺失");
            }
            // 构建V3配置（自动管理平台证书）
            Config v3Config = new RSAAutoCertificateConfig.Builder()
                    .merchantId(config.getWxMchId())
                    .privateKeyFromPath(config.getWxApiclientKeyPem())
                    .merchantSerialNumber(config.getWxApiSerialNo())
                    .apiV3Key(config.getWxApiV3Key())
                    .build();

            TransferBatchService transferService = new TransferBatchService.Builder().config(v3Config).build();
            // 4. 构建请求参数
            InitiateBatchTransferRequest request = new InitiateBatchTransferRequest();
            request.setAppid(config.getWxAppId());
            request.setOutBatchNo(orderNumber);
            request.setBatchName("用户退款");
            request.setBatchRemark("退款至零钱");

            // 总金额（分）
            Long totalAmount = refundFee.multiply(BigDecimal.valueOf(100)).longValue();
            request.setTotalAmount(totalAmount);
            request.setTotalNum(1); // 单笔转账

            // 构建明细列表
            List<TransferDetailInput> detailList = new ArrayList<>();
            TransferDetailInput detail = new TransferDetailInput();
            //商家明细单号
            String outDetailNo = StringUtils.numFormat(11L, 1, StatusConstants.FLOWING_WATER_REFUND_TYPE);
            detail.setOutDetailNo(outDetailNo);
            detail.setTransferAmount(totalAmount);
            detail.setTransferRemark("退款");
            detail.setOpenid(xhpcRefundOrder.getOpenId());
            // 如果单笔金额 >= 2000元，需要加密用户姓名
            // if (totalAmount >= 200000) {
            //     detail.setUserName(encryptUserName(userName));
            // }
            detailList.add(detail);
            request.setTransferDetailList(detailList);
            //v3回调地址在微信商户后台配置
            request.setNotifyUrl(config.getWxV3CallbackUrl());


            InitiateBatchTransferResponse response = transferService.initiateBatchTransfer(request);
            // 6. 直接从响应中获取返回信息
            String outBatchNoResp = response.getOutBatchNo();
            String batchId = response.getBatchId();
            String createTime = response.getCreateTime();
            String batchStatus = response.getBatchStatus();



            XhpcRefundOriginalOrder xhpcRefundOriginalOrder = new XhpcRefundOriginalOrder();
            if ("ACCEPTED".equals(batchStatus) || "PROCESSING".equals(batchStatus) || "FINISHED".equals(batchStatus)) {
                xhpcRefundOriginalOrder.setStatus(0);

            } else {
                xhpcRefundOriginalOrder.setStatus(2);
            }
            xhpcRefundOriginalOrder.setOutTradeNo(outBatchNoResp);
            xhpcRefundOriginalOrder.setRefundId(batchId);
            xhpcRefundOriginalOrder.setCashRefundFee(refundFee);
            //入库
            xhpcRefundOriginalOrder.setUserId(rechargeOrder.getUserId());
            xhpcRefundOriginalOrder.setType(1);
            xhpcRefundOriginalOrder.setSource(rechargeOrder.getSource());
            xhpcRefundOriginalOrder.setDelFlag(0);
            xhpcRefundOriginalOrder.setCreateTime(new Date());
            xhpcRefundOriginalOrder.setRemark("微信退款");
            xhpcRefundOriginalOrder.setTenantId(rechargeOrder.getTenantId());
            xhpcRefundOriginalOrder.setAppId(config.getWxAppId());
            xhpcRefundOriginalOrder.setMchId(config.getWxMchId());
            xhpcRefundOriginalOrder.setTransactionId(rechargeOrder.getPrepayId());
            xhpcRefundOriginalOrder.setOutRefundNo(orderNumber);
            xhpcRefundOriginalOrder.setOutDetailNo(outDetailNo);
            xhpcRefundOriginalOrder.setTotalFee(rechargeOrder.getAmount());
            xhpcRefundOriginalOrder.setRefundFee(refundFee);
            xhpcRefundOriginalOrder.setRefundOrderId(xhpcRefundOrder.getRefundOrderId());
            xhpcRefundOriginalOrder.setRechargeOrderId(rechargeOrder.getRechargeOrderId());
            xhpcRefundOriginalOrder.setLastOne(type);
            xhpcRefundOriginalOrderMapper.addXhpcRefundOriginalOrder(xhpcRefundOriginalOrder);

            Thread.sleep(500);

            return R.ok();

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            readWriteLock.writeLock().unlock();//释放锁
        }
        return R.fail();
    }





    public R getWxTradeRefund(XhpcRefundOrder xhpcRefundOrder,XhpcRechargeOrder rechargeOrder,String orderNumber,BigDecimal refundFee,Integer type){
        try {
            readWriteLock.writeLock().lock();//取
            XhpcSettingConfig xhpcSettingConfig = xhpcCommonPayment.getXhpcSettingConfigTenantId(UserTypeUtil.OPERATION_WX_TYPE, rechargeOrder.getTenantId());
            CloseableHttpClient httpClient = null;
            try {
                //证书的地址
                httpClient = initCert(xhpcSettingConfig);
            } catch (Exception e) {
                e.printStackTrace();
            }
            boolean fals = false;
            String result = "";
            HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/secapi/pay/refund");
            //随机字符串
            String nonceStr = WXPayUtil.generateNonceStr();
            StringEntity postEntity = new StringEntity(creatXMLParam(xhpcSettingConfig, rechargeOrder, orderNumber, refundFee, nonceStr), "UTF-8");
            httpPost.addHeader("Content-Type", "text/xml");
            httpPost.setEntity(postEntity);
            try {
                HttpResponse response = null;
                try {
                    response = httpClient.execute(httpPost);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                HttpEntity entity = response.getEntity();
                try {
                    result = EntityUtils.toString(entity, "UTF-8");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                httpPost.abort();
            }
            try {
                Map<String, String> map = WXPayUtil.xmlToMap(result);
                String result_code = map.get("result_code");
                String return_code = map.get("return_code");
                logger.info("+++++++原路退款+++++退款信息++++++++++++++++");
                logger.info("+++++++原路退款+++++退款信息++++++++++++++++" + map.toString());
                logger.info("+++++++原路退款+++++退款信息++++++++++++++++");
                XhpcRefundOriginalOrder xhpcRefundOriginalOrder = new XhpcRefundOriginalOrder();
                if ("SUCCESS".equals(result_code) && "SUCCESS".equals(return_code)) {
                    xhpcRefundOriginalOrder.setStatus(0);
                    xhpcRefundOriginalOrder.setOutTradeNo(map.get("out_trade_no").toString());
                    xhpcRefundOriginalOrder.setRefundId(map.get("refund_id").toString());
                    xhpcRefundOriginalOrder.setCashRefundFee(new BigDecimal(map.get("cash_refund_fee").toString()).divide(new BigDecimal(100)));
                    fals = true;
                } else {
                    xhpcRefundOriginalOrder.setStatus(2);
                }
                //入库
                xhpcRefundOriginalOrder.setUserId(rechargeOrder.getUserId());
                xhpcRefundOriginalOrder.setType(1);
                xhpcRefundOriginalOrder.setSource(rechargeOrder.getSource());
                xhpcRefundOriginalOrder.setDelFlag(0);
                xhpcRefundOriginalOrder.setCreateTime(new Date());
                xhpcRefundOriginalOrder.setRemark("微信退款");
                xhpcRefundOriginalOrder.setTenantId(rechargeOrder.getTenantId());
                xhpcRefundOriginalOrder.setAppId(xhpcSettingConfig.getWxAppId());
                xhpcRefundOriginalOrder.setMchId(xhpcSettingConfig.getWxMchId());
                xhpcRefundOriginalOrder.setNonceStr(nonceStr);
                xhpcRefundOriginalOrder.setTransactionId(rechargeOrder.getPrepayId());
                xhpcRefundOriginalOrder.setOutRefundNo(orderNumber);
                xhpcRefundOriginalOrder.setTotalFee(rechargeOrder.getAmount());
                xhpcRefundOriginalOrder.setRefundFee(refundFee);
                xhpcRefundOriginalOrder.setRefundOrderId(xhpcRefundOrder.getRefundOrderId());
                xhpcRefundOriginalOrder.setRechargeOrderId(rechargeOrder.getRechargeOrderId());
                xhpcRefundOriginalOrder.setLastOne(type);
                xhpcRefundOriginalOrderMapper.addXhpcRefundOriginalOrder(xhpcRefundOriginalOrder);
            } catch (Exception e) {
                e.printStackTrace();
            }
            Thread.sleep(500);
            if (fals) {
                return R.ok();
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            readWriteLock.writeLock().unlock();//释放锁
        }
        return R.fail();
    }

    // 企业退款生成xml格式  添加参数时，按照abcd26个字母顺序添加
    /**
     * 生成xml格式  添加参数时，按照abcd26个字母顺序添加
     *
     * @param openid           用户openid
     * @param partner_trade_no 商户退款单号
     * @param amount           退款金额
     * @param refund_desc      退款原因
     * @return
     */
    private String qyXMLParam(String partner_trade_no, String amount, String refund_desc, String openid,XhpcSettingConfig xhpcSettingConfig) {
        String param = "";
        //随机字符串
        String nonceStr = WXPayUtil.generateNonceStr();
        //退款金额
        param += "amount=" + amount;
        //校验用户姓名选项
        param += "&check_name=" + "NO_CHECK";
        //退款原因
        param += "&desc=" + refund_desc;
        param += "&mch_appid=" + xhpcSettingConfig.getWxAppId();
        //商户id
        param += "&mchid=" + xhpcSettingConfig.getWxMchId();
        //随机字符串
        param += "&nonce_str=" + nonceStr;
        //用户openid
        param += "&openid=" + openid;
        //商户退款单号 一个订单唯一
        param += "&partner_trade_no=" + partner_trade_no;
        //生成签名  添加key值
        String stringSignTemp = param + "&key=" + xhpcSettingConfig.getWxMchKey();
        //签名  不参与签名  默认MD5算法
        String sign = StringUtils.md5(stringSignTemp);
        if(sign.length()!=32){
            sign="0"+sign;
        }
        String xmlString = "<xml>\n" +
                "   <amount>" + amount + "</amount>\n" +
                "   <check_name>" + "NO_CHECK" + "</check_name>\n" +
                "   <desc>" + refund_desc + "</desc>\n" +
                "   <mch_appid>" + xhpcSettingConfig.getWxAppId() + "</mch_appid>\n" +
                "   <mchid>" + xhpcSettingConfig.getWxMchId() + "</mchid>\n" +
                "   <nonce_str>" + nonceStr + "</nonce_str>\n" +
                "   <openid>" + openid + "</openid>\n" +
                "   <partner_trade_no>" + partner_trade_no + "</partner_trade_no>\n" +
                "   <sign>" + sign + "</sign>\n" +
                "</xml> ";

        logger.info("++++++++++++xmlString++++++++++++++++"+xmlString);
        return xmlString;
    }




    // 原路退回生成xml格式  添加参数时，按照abcd26个字母顺序添加
    private String creatXMLParam(XhpcSettingConfig xhpcSettingConfig,XhpcRechargeOrder rechargeOrder,String orderNumber,BigDecimal refundFee,String nonceStr) {
        String param = "";
        //公众账号ID
        String wxAppId = xhpcSettingConfig.getWxAppId();
        param += "appid=" + wxAppId;
        String wxMchId = xhpcSettingConfig.getWxMchId();
        //商户号
        param += "&mch_id=" + wxMchId;
        //随机字符串
        param += "&nonce_str=" + nonceStr;
        //退款结果通知url
        String url="https://www.scxhua.cn/prod-api/xhpc-payment/refundOriginalOrder/paymentCallback";
        param += "&notify_url=" + url;
        //商户退款单号
        param += "&out_refund_no=" + orderNumber;
        int refund_fee = refundFee.multiply(new BigDecimal(100)).intValue();
        //退款金额
        param += "&refund_fee=" + refund_fee;
        BigDecimal multiply = rechargeOrder.getAmount().multiply(new BigDecimal(100));
        //订单金额
        param += "&total_fee=" + multiply.intValue();
        //微信支付订单号
        param += "&transaction_id=" + rechargeOrder.getPrepayId();

        param += "&key=" + xhpcSettingConfig.getWxMchKey();

        //生成签名  添加key值
        String stringSignTemp = param;
        //签名  不参与签名  默认MD5算法
        String sign = StringUtils.md5(stringSignTemp);
        if(sign.length()!=32){
            sign="0"+sign;
        }
        String xmlString = "<xml>\n" +
                "   <appid>" + wxAppId + "</appid>\n" +
                "   <mch_id>" + wxMchId + "</mch_id>\n" +
                "   <nonce_str>" + nonceStr + "</nonce_str>\n" +
                "   <notify_url>" + url + "</notify_url>\n" +
                "   <out_refund_no>" + orderNumber + "</out_refund_no>\n" +
                "   <refund_fee>" + refund_fee + "</refund_fee>\n" +
                "   <total_fee>" + multiply.intValue() + "</total_fee>\n" +
                "   <transaction_id>" + rechargeOrder.getPrepayId() + "</transaction_id>\n" +
                "   <sign>" + sign + "</sign>\n" +
                "</xml> ";
        logger.info("=================xmlString========================"+xmlString);
        return xmlString;
    }

    /**
     * 加载证书
     *
     * @param
     * @throws Exception
     */
    private CloseableHttpClient initCert(XhpcSettingConfig xhpcSettingConfig) throws Exception {
        //String path = "apiclient_cert.p12";
        //File file = new File(this.getClass().getResource("/").getPath() + path);
        //线上地址
        File file = new File(xhpcSettingConfig.getWxApiclientCertPem());
        // 证书密码，默认为商户ID
        String key = xhpcSettingConfig.getWxMchId();
        // 指定读取证书格式为PKCS12
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        // 读取本机存放的PKCS12证书文件
        FileInputStream instream = new FileInputStream(file);
        try {
            // 指定PKCS12的密码(商户ID)
            keyStore.load(instream, key.toCharArray());
        } finally {
            instream.close();
        }
        SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, key.toCharArray()).build();
        SSLConnectionSocketFactory sslsf =
                new SSLConnectionSocketFactory(sslcontext, new String[]{"TLSv1","TLSv1.2"}, null,
                        SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        return HttpClients.custom().setSSLSocketFactory(sslsf).build();
    }


    //支付宝退款原路退回
    public R getalipayTradeRefund(XhpcSettingConfig xhpcSettingConfig,XhpcRefundOrder xhpcRefundOrder,XhpcRechargeOrder rechargeOrder,BigDecimal refundFee,String orderNumber,int number){
        try{
            readWriteLock.writeLock().lock();//取
            /** 初始化 **/
            CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
            /** 支付宝网关 **/
            certAlipayRequest.setServerUrl("https://openapi.alipay.com/gateway.do");
            /** 应用id，如何获取请参考：https://opensupport.alipay.com/support/helpcenter/190/201602493024 **/
            certAlipayRequest.setAppId(xhpcSettingConfig.getZfbAppId());
            /** 应用私钥, 如何获取请参考：https://opensupport.alipay.com/support/helpcenter/207/201602471154?ant_source=antsupport  **/
            certAlipayRequest.setPrivateKey(xhpcSettingConfig.getZfbPrivateKey());
            /** 应用公钥证书路径，下载后保存位置的绝对路径  **/
            certAlipayRequest.setCertPath(xhpcSettingConfig.getZfbAppCertPublicKey());
            /** 支付宝公钥证书路径，下载后保存位置的绝对路径 **/
            certAlipayRequest.setAlipayPublicCertPath(xhpcSettingConfig.getZfbAlipayCertPublicKeyRsa());
            /** 支付宝根证书路径，下载后保存位置的绝对路径 **/
            certAlipayRequest.setRootCertPath(xhpcSettingConfig.getZfbAlipayRootCert());
            /** 设置签名类型 **/
            certAlipayRequest.setSignType("RSA2");
            /** 设置请求格式，固定值json **/
            certAlipayRequest.setFormat("json");
            /** 设置编码格式 **/
            certAlipayRequest.setCharset("UTF-8");

            AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
            /** 实例化具体API对应的request类，类名称和接口名称对应,当前调用接口名称：alipay.fund.trans.uni.transfer(单笔转账接口) **/
            AlipayTradeRefundRequest request  = new AlipayTradeRefundRequest();
            /** 设置业务参数，具体接口参数传值以文档说明为准：https://opendocs.alipay.com/apis/api_28/alipay.fund.trans.uni.transfer/ **/
            //AlipayFundTransUniTransferModel model = new AlipayFundTransUniTransferModel();
            JSONObject bizContent = new JSONObject();
            bizContent.put("trade_no", rechargeOrder.getAlipayNumber());
            bizContent.put("refund_amount", refundFee);
            bizContent.put("out_request_no", orderNumber);
            request.setBizContent(bizContent.toString());
            logger.info("=====支付宝退款订单=======bizContent=========================="+bizContent.toString());
            AlipayTradeRefundResponse response = alipayClient.certificateExecute(request);
            if("Y".equals(response.getFundChange())){
                System.out.println("调用退款成功");
                paymentCallback(xhpcRefundOrder,rechargeOrder,refundFee);
                addXhpcRefundOriginalOrder(response,xhpcRefundOrder,rechargeOrder,refundFee);
                return R.ok();
            }else{
                //查询订单
                R r = alipayTradeFastpayRefundQuery(xhpcSettingConfig, xhpcRefundOrder, rechargeOrder, refundFee, orderNumber, number);
                if(r.getCode()==200){
                    paymentCallback(xhpcRefundOrder,rechargeOrder,refundFee);
                    addXhpcRefundOriginalOrder(response,xhpcRefundOrder,rechargeOrder,refundFee);
                    return R.ok();
                }

            }
            Thread.sleep(500);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            readWriteLock.writeLock().unlock();//释放锁
        }
        return R.fail();
    }

    //阿里云统一收单交易退款查询
    public R alipayTradeFastpayRefundQuery(XhpcSettingConfig xhpcSettingConfig,XhpcRefundOrder xhpcRefundOrder,XhpcRechargeOrder rechargeOrder,BigDecimal refundFee,String orderNumber,int number){
        try{
            AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",xhpcSettingConfig.getZfbAppId(),xhpcSettingConfig.getZfbPrivateKey(),"json","GBK",xhpcSettingConfig.getZfbAppCertPublicKey(),"RSA2");
            AlipayTradeFastpayRefundQueryRequest request = new AlipayTradeFastpayRefundQueryRequest();
            JSONObject bizContent = new JSONObject();
            bizContent.put("trade_no", rechargeOrder.getAlipayNumber());
            bizContent.put("out_request_no", orderNumber);
            request.setBizContent(bizContent.toString());
            AlipayTradeFastpayRefundQueryResponse response = alipayClient.execute(request);
            if(response.isSuccess() && "10000".equals(response.getCode()) && "REFUND_SUCCESS".equals(response.getRefundStatus())){
                System.out.println("调用成功");
                paymentCallback(xhpcRefundOrder,rechargeOrder,refundFee);
                return R.ok();
            } else {
                System.out.println("调用失败");
                //重新调用一次
                if(number==0){
                    number++;
                    R r = getalipayTradeRefund(xhpcSettingConfig, xhpcRefundOrder, rechargeOrder, refundFee, orderNumber, number);
                    if(r.getCode() !=200){
                        return R.fail();
                    }
                }else{
                    System.out.println("第二次调用失败");
                    return R.fail();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return R.fail();
    }

    //微信退款
    public R wxRefund(XhpcRefundOrder xhpcRefundOrder,BigDecimal refundFee){

        Map<String,Object> map =new HashMap<>();
        Date date = new Date();
        String endTime = DateUtil.formatDateTime(date);
        LocalDateTime localDate = LocalDateTime.now().minusDays(363);
        String startTime = localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd  HH:mm:ss"));//转为String类型
        Long refundOrderId = xhpcRefundOrder.getRefundOrderId();
        XhpcSettingConfig xhpcSettingConfig = xhpcCommonPayment.getXhpcSettingConfigTenantId(UserTypeUtil.OPERATION_WX_TYPE,xhpcRefundOrder.getTenantId());
        if(xhpcSettingConfig ==null){
            return R.fail(HttpStatus.ALREADY_EXISTING, "微信退款失败,请联系客服");
        }
        List<XhpcRechargeOrder> xhpcRechargeOrderList = xhpcRefundOriginalOrderMapper.getXhpcRechargeOrderList(1, refundOrderId, startTime, endTime);
        for (int i = 0; i <xhpcRechargeOrderList.size() ; i++) {
            XhpcRechargeOrder xhpcRechargeOrder = xhpcRechargeOrderList.get(i);
            Integer refundStatus = xhpcRechargeOrder.getRefundStatus();
            BigDecimal amount = xhpcRechargeOrder.getAmount();
            String orderNumber = StringUtils.numFormat(11L, 1, StatusConstants.FLOWING_WATER_REFUND_TYPE);
            if(refundStatus==0){
                if(refundFee.compareTo(amount)>=0){
                    //全额退款
                    if(refundFee.compareTo(amount)==0){
                        R wxTradeRefund = getWxTradeRefund(xhpcRefundOrder,xhpcRechargeOrder, orderNumber,amount ,1);
                        if(wxTradeRefund.getCode()==200){
                            updateXhpcRefundOrder(xhpcRefundOrder,refundFee,1,1);
                            return R.ok(map);
                        }
                    }
                    R wxTradeRefund = getWxTradeRefund(xhpcRefundOrder,xhpcRechargeOrder, orderNumber,amount ,0);
                    if(wxTradeRefund.getCode()==200){
                        refundFee =refundFee.subtract(amount);
                        map.put("refundFee",refundFee);
                    }
                }else{
                    R wxTradeRefund = getWxTradeRefund(xhpcRefundOrder,xhpcRechargeOrder, orderNumber, refundFee,1);
                    if(wxTradeRefund.getCode()==200){
                        updateXhpcRefundOrder(xhpcRefundOrder,refundFee,1,1);
                        return R.ok(map);
                    }
                }
            }else{
                BigDecimal subtract = amount.subtract(xhpcRechargeOrder.getRefundFee());
                if(refundFee.compareTo(subtract)>=0){
                    if(refundFee.compareTo(subtract)==0){
                        R wxTradeRefund = getWxTradeRefund(xhpcRefundOrder,xhpcRechargeOrder, orderNumber, subtract,1);
                        if(wxTradeRefund.getCode()==200){
                            updateXhpcRefundOrder(xhpcRefundOrder,refundFee,1,1);
                            return R.ok(map);
                        }
                    }
                    R wxTradeRefund = getWxTradeRefund(xhpcRefundOrder,xhpcRechargeOrder, orderNumber, subtract,0);
                    if(wxTradeRefund.getCode()==200){
                        refundFee =refundFee.subtract(subtract);
                        map.put("refundFee",refundFee);
                    }
                }else{
                    R wxTradeRefund = getWxTradeRefund(xhpcRefundOrder,xhpcRechargeOrder, orderNumber, refundFee,1);
                    if(wxTradeRefund.getCode()==200){
                        updateXhpcRefundOrder(xhpcRefundOrder,refundFee,1,1);
                        return R.ok(map);
                    }
                }
            }
        }
        return R.ok(map);
    }

    public void paymentCallback(XhpcRefundOrder xhpcRefundOrder,XhpcRechargeOrder rechargeOrder,BigDecimal refundFee){
        BigDecimal amount = rechargeOrder.getAmount();
        //总共退款金额
        BigDecimal refundFeeAmount = refundFee.add(rechargeOrder.getRefundFee());
        //修改支付订单付款金额和转改
        if(amount.compareTo(refundFeeAmount)==0){
            //全部退完
            iXhpcRechargeOrderService.updateRechargeOrderFeundFee(rechargeOrder.getRechargeOrderId(),amount,2);
        }else if(amount.compareTo(refundFeeAmount)>0){
            //退了一部分
            iXhpcRechargeOrderService.updateRechargeOrderFeundFee(rechargeOrder.getRechargeOrderId(),refundFeeAmount,1);
        }
        //修改用户金额
        Long userId = rechargeOrder.getUserId();
        Integer source = rechargeOrder.getSource();
        //增加用户流水记录
        xhpcUserAccountStatementService.add(xhpcRefundOrder.getRefundOrderId(), "-"+refundFee.toString(), userId.toString(), StatusConstants.FLOWING_WATER_REFUND,source,rechargeOrder.getTenantId());
        if(UserTypeUtil.USER_TYPE.equals(source)){
            Map<String, Object> appUserInfo = xhpcUserAccountStatementMapper.appUserInfo(userId);
            String balance = StringUtils.valueOf(appUserInfo.get("balance"));
            //减少用户余额
            XhpcAppUser xhpcAppUser = new XhpcAppUser();
            xhpcAppUser.setAppUserId(userId);
            BigDecimal surplus =new BigDecimal(balance).subtract(refundFee);
            xhpcAppUser.setBalance(surplus);
            xhpcUserAccountStatementMapper.updateAppUserBalance(xhpcAppUser);
            if(surplus.compareTo(new BigDecimal(0))==0){
                xhpcRefundOriginalOrderMapper.updateRechargeOrderRefundStatus(userId,source);
            }
        }else if(UserTypeUtil.COMMUNIT_TYPE.equals(source)){
            Map<String, Object> communityPersonnel = iXhpcRefundAuditService.getCommunityPersonnelById(userId, rechargeOrder.getTenantId());
            BigDecimal surplus =new BigDecimal(communityPersonnel.get("balance").toString()).subtract(refundFee);
            int i = iXhpcRefundAuditService.updateCommunityPersonnelMoney(userId, surplus,null);
            if(surplus.compareTo(new BigDecimal(0))==0){
                xhpcRefundOriginalOrderMapper.updateRechargeOrderRefundStatus(userId,source);
            }
        }else if(UserTypeUtil.INTERNET_TYPE.equals(source) && userId>10000){
            Map<String, Object> appUserInfo = xhpcUserAccountStatementMapper.getAppInternetUser(userId);
            String balance = StringUtils.valueOf(appUserInfo.get("balance"));
            //减少用户余额
            XhpcAppInternetUser xhpcAppUser = new XhpcAppInternetUser();
            xhpcAppUser.setAppInternetUserId(userId);
            BigDecimal surplus =new BigDecimal(balance).subtract(refundFee);
            xhpcAppUser.setBalance(surplus);
            xhpcUserAccountStatementMapper.updateAppInternetUserBalance(xhpcAppUser);
            if(surplus.compareTo(new BigDecimal(0))==0){
                xhpcRefundOriginalOrderMapper.updateRechargeOrderRefundStatus(userId,source);
            }
        }
    }

    /**
     * 修改订单状态
     * @param refundOrder
     * @param refundFee  退款总金额
     * @param type         1成功 2失败 4需要管理员审核
     * @param status         1微信 2支付宝
     */
    @Override
    public void updateXhpcRefundOrder(XhpcRefundOrder refundOrder,BigDecimal refundFee,Integer type,Integer status){
        System.out.println("============修改订单状态================");
        System.out.println("============修改订单状态================");
        Long userId = refundOrder.getUserId();
        Integer source = refundOrder.getSource();
        String phone ="";
        if(UserTypeUtil.USER_TYPE.equals(source)){
            Map<String, Object> appUserInfo = xhpcUserAccountStatementMapper.appUserInfo(userId);
            phone =appUserInfo.get("phone").toString();
            //减少用户余额
            XhpcAppUser xhpcAppUser = new XhpcAppUser();
            xhpcAppUser.setAppUserId(userId);
            xhpcAppUser.setIsRefundApplication(0);

            xhpcUserAccountStatementMapper.updateAppUserBalance(xhpcAppUser);
        }else if(UserTypeUtil.COMMUNIT_TYPE.equals(source)){
            Map<String, Object> communityPersonnel = iXhpcRefundAuditService.getCommunityPersonnelById(userId, refundOrder.getTenantId());
            phone =communityPersonnel.get("phone").toString();
            int i = iXhpcRefundAuditService.updateCommunityPersonnelMoney(userId, null,0);
        }else if(UserTypeUtil.INTERNET_TYPE.equals(source) && userId>10000){
            Map<String, Object> appUserInfo = xhpcUserAccountStatementMapper.getAppInternetUser(userId);
            phone =appUserInfo.get("phone").toString();
            //减少用户余额
            XhpcAppInternetUser xhpcAppUser = new XhpcAppInternetUser();
            xhpcAppUser.setAppInternetUserId(userId);
            xhpcAppUser.setIsRefundApplication(0);
            xhpcUserAccountStatementMapper.updateAppInternetUserBalance(xhpcAppUser);

        }
        if(type==1){
            refundOrder.setStatus(1);
            refundOrder.setExamineStatus(1);
//            if(status==1){
//                refundOrder.setRemark("微信退款成功");
//            }else{
//                refundOrder.setRemark("支付宝退款成功");
//            }
        }else if(type==2){
            refundOrder.setStatus(2);
            refundOrder.setExamineStatus(1);
//            if(status==1){
//                refundOrder.setRemark("微信退款失败");
//            }else{
//                refundOrder.setRemark("支付宝退款失败");
//            }
//            try{
//                //发送短信
//                HashMap<String, String> paramMap = new HashMap<>();
//                paramMap.put("phone", phone);
//                paramMap.put("content", "【小华充电】退款-尊敬的用户，当前退款人数较多，申请退款失败，请您重新提交申请！");
//                smsService.sendNotice(paramMap);
//            }catch (Exception e){
//
//            }
        }else{
            refundOrder.setStatus(4);
            refundOrder.setExamineStatus(0);
            HashMap<String, String> paramMap = new HashMap<>();
            paramMap.put("number",refundOrder.getRefundOrderId()+"");
            paramMap.put("phone", "18123374652");
            paramMap.put("content", "【翔桦充电】尊敬的管理员，用户退款订单："+refundOrder.getRefundOrderId()+"，有问题请速速查看。");
            //smsService.sendNotice(paramMap);
        }
        iXhpcRefundOrderService.update(refundOrder);
    }

    @Override
    public void addXhpcRefundOrder(XhpcRefundOrder xhpcRefundOrder) {
        xhpcRefundOriginalOrderMapper.addXhpcRefundOrder(xhpcRefundOrder);
    }

    //添加原路退回订单记录
    public void addXhpcRefundOriginalOrder(AlipayTradeRefundResponse response,XhpcRefundOrder refundOrder,XhpcRechargeOrder rechargeOrder,BigDecimal refundFee){
        XhpcRefundOriginalOrder xhpcRefundOriginalOrder = new XhpcRefundOriginalOrder();
        xhpcRefundOriginalOrder.setUserId(refundOrder.getUserId());
        xhpcRefundOriginalOrder.setType(2);
        xhpcRefundOriginalOrder.setSource(refundOrder.getSource());
        if("Y".equals(response.getFundChange())){
            xhpcRefundOriginalOrder.setStatus(1);
        }else{
            xhpcRefundOriginalOrder.setStatus(2);
        }
        xhpcRefundOriginalOrder.setDelFlag(0);
        xhpcRefundOriginalOrder.setCreateTime(new Date());
        xhpcRefundOriginalOrder.setRemark("支付宝退款");
        xhpcRefundOriginalOrder.setTenantId(refundOrder.getTenantId());
        xhpcRefundOriginalOrder.setOutTradeNo(response.getOutTradeNo());
        xhpcRefundOriginalOrder.setTradeNo(response.getTradeNo());
        xhpcRefundOriginalOrder.setTotalFee(refundOrder.getAmount());
        xhpcRefundOriginalOrder.setSettlementTotalFee(refundFee);
        xhpcRefundOriginalOrder.setBuyerUserId(response.getBuyerUserId());
        xhpcRefundOriginalOrder.setRefundOrderId(refundOrder.getRefundOrderId());
        xhpcRefundOriginalOrder.setRechargeOrderId(rechargeOrder.getRechargeOrderId());
        xhpcRefundOriginalOrder.setCashRefundFee(refundFee);
        xhpcRefundOriginalOrder.setRefundFee(refundFee);
        xhpcRefundOriginalOrderMapper.addXhpcRefundOriginalOrder(xhpcRefundOriginalOrder);
    }

    //微信企业退款
    public R wxCheckOut(XhpcRefundOrder refundOrder,BigDecimal refundFee){

        Long userId = refundOrder.getUserId();
        Integer source = refundOrder.getSource();
        Map<String, Object> appUserInfo = new HashMap<>();
        if(UserTypeUtil.USER_TYPE.equals(source)){
            appUserInfo = xhpcUserAccountStatementMapper.appUserInfo(userId);
        }else if(UserTypeUtil.COMMUNIT_TYPE.equals(source)){
            appUserInfo = iXhpcRefundAuditService.getCommunityPersonnelById(userId, refundOrder.getTenantId());
        }else if(UserTypeUtil.INTERNET_TYPE.equals(source) && userId>10000){
            appUserInfo = xhpcUserAccountStatementMapper.getAppInternetUser(userId);
        }
        XhpcSettingConfig xhpcSettingConfig = xhpcCommonPayment.getXhpcSettingConfigTenantId(UserTypeUtil.OPERATION_WX_TYPE,refundOrder.getTenantId());
        if(xhpcSettingConfig ==null){
            return R.fail(HttpStatus.ALREADY_EXISTING, "微信退款失败,请联系客服");
        }
        CloseableHttpClient httpClient = null;
        try {
            //证书的地址
            httpClient = initCert(xhpcSettingConfig);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String orderOutNumber =refundOrder.getRefundOrderNumber();
        String openId = StringUtils.valueOf(appUserInfo.get("weixinOpenId"));
        //Double amount = Double.parseDouble(StringUtils.valueOf(xhpcRefundOrder.get("amount")));
        //退款金额单位为分
        BigDecimal value = refundFee.multiply(new BigDecimal(100));
        Integer refund_fee = value.intValue();
        String result = "";
        HttpPost httpPost = new HttpPost(xhpcSettingConfig.getWxTransfersUrl());
        StringEntity postEntity = new StringEntity(qyXMLParam(orderOutNumber, refund_fee.toString(), "退款申请", openId,xhpcSettingConfig), "UTF-8");
        httpPost.addHeader("Content-Type", "text/xml");
        httpPost.setEntity(postEntity);
        try {
            HttpResponse response = null;
            try {
                response = httpClient.execute(httpPost);
            } catch (IOException e) {
                e.printStackTrace();
            }
            HttpEntity entity = response.getEntity();
            try {
                result = EntityUtils.toString(entity, "UTF-8");
            } catch (IOException e) {
                e.printStackTrace();
            }
        } finally {
            httpPost.abort();
        }
        try{
            Map<String, String> map = WXPayUtil.xmlToMap(result);
            String result_code = map.get("result_code");
            if ("FAIL".equals(result_code)) {
                refundOrder.setStatus(2);
                refundOrder.setRemark(map.get("err_code_des").toString());
                updateXhpcRefundOrder(refundOrder,refundFee,2,1);
                logger.info("++++++++++++审核失败原因++++++++++++++++"+map.get("err_code_des").toString()+"错误代码："+map.get("err_code").toString());
                return R.fail(map.get("err_code_des"));
            } else {
                //退款成功修改订单
                if(UserTypeUtil.USER_TYPE.equals(source)){
                    String balance = StringUtils.valueOf(appUserInfo.get("balance"));
                    //减少用户余额
                    XhpcAppUser xhpcAppUser = new XhpcAppUser();
                    xhpcAppUser.setAppUserId(userId);
                    BigDecimal surplus =new BigDecimal(balance).subtract(refundFee);
                    xhpcAppUser.setBalance(surplus);
                    xhpcUserAccountStatementMapper.updateAppUserBalance(xhpcAppUser);

                }else if(UserTypeUtil.COMMUNIT_TYPE.equals(source)){
                    Map<String, Object> communityPersonnel = iXhpcRefundAuditService.getCommunityPersonnelById(userId, refundOrder.getTenantId());
                    BigDecimal surplus =new BigDecimal(communityPersonnel.get("balance").toString()).subtract(refundFee);
                    int i = iXhpcRefundAuditService.updateCommunityPersonnelMoney(userId, surplus,null);
                }else if(UserTypeUtil.INTERNET_TYPE.equals(source) && userId>10000){
                    String balance = StringUtils.valueOf(appUserInfo.get("balance"));
                    //减少用户余额
                    XhpcAppInternetUser xhpcAppUser = new XhpcAppInternetUser();
                    xhpcAppUser.setAppInternetUserId(userId);
                    BigDecimal surplus =new BigDecimal(balance).subtract(refundFee);
                    xhpcAppUser.setBalance(surplus);
                    xhpcUserAccountStatementMapper.updateAppInternetUserBalance(xhpcAppUser);
                }
                refundOrder.setStatus(1);
                refundOrder.setRemark("微信零钱退款成功");
                refundOrder.setPaymentNo(map.get("payment_no").toString());
                refundOrder.setPaymentTime(map.get("payment_time").toString());
                updateXhpcRefundOrder(refundOrder,refundFee,1,1);

                XhpcRefundOriginalOrder xhpcRefundOriginalOrder = new XhpcRefundOriginalOrder();
                xhpcRefundOriginalOrder.setUserId(refundOrder.getUserId());
                xhpcRefundOriginalOrder.setType(3);
                xhpcRefundOriginalOrder.setSource(refundOrder.getSource());
                xhpcRefundOriginalOrder.setStatus(1);
                xhpcRefundOriginalOrder.setDelFlag(0);
                xhpcRefundOriginalOrder.setCreateTime(new Date());
                xhpcRefundOriginalOrder.setRemark("微信零钱退款");
                xhpcRefundOriginalOrder.setTenantId(refundOrder.getTenantId());
                xhpcRefundOriginalOrder.setTradeNo(orderOutNumber);
                xhpcRefundOriginalOrder.setTotalFee(refundFee);
                xhpcRefundOriginalOrder.setSettlementTotalFee(refundFee);
                xhpcRefundOriginalOrder.setRefundFee(refundFee);
                xhpcRefundOriginalOrder.setCashRefundFee(refundFee);
                xhpcRefundOriginalOrder.setBuyerUserId(openId);
                xhpcRefundOriginalOrder.setRefundOrderId(refundOrder.getRefundOrderId());
                xhpcRefundOriginalOrderMapper.addXhpcRefundOriginalOrder(xhpcRefundOriginalOrder);
                //查询以前充值记录
                logger.info("===微信=======查询以前充值记录=========");
                //增加用户流水记录
                xhpcUserAccountStatementService.add(refundOrder.getRefundOrderId(), "-"+refundFee, userId.toString(), StatusConstants.FLOWING_WATER_REFUND,source,refundOrder.getTenantId());

                LocalDateTime localDate = LocalDateTime.now().minusDays(363);
                String createTime = localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd  HH:mm:ss"));//转为String类型

                List<XhpcRechargeOrder> totalMoneyList = xhpcRefundOriginalOrderMapper.getTotalMoneyList(userId, source,createTime);
                for (int i = 0; i <totalMoneyList.size() ; i++) {
                    XhpcRechargeOrder xhpcRechargeOrder = totalMoneyList.get(i);
                    BigDecimal amount = xhpcRechargeOrder.getAmount();
                    if(xhpcRechargeOrder.getRefundStatus()==0){
                        if(amount.compareTo(refundFee)>0){
                            iXhpcRechargeOrderService.updateRechargeOrderFeundFee(xhpcRechargeOrder.getRechargeOrderId(),refundFee,1);
                        }else{
                            iXhpcRechargeOrderService.updateRechargeOrderFeundFee(xhpcRechargeOrder.getRechargeOrderId(),amount,2);
                            break;
                        }
                    }else{
                        BigDecimal refundFeeAmount = amount.subtract(xhpcRechargeOrder.getRefundFee());
                        if(refundFeeAmount.compareTo(refundFee)>0){
                            iXhpcRechargeOrderService.updateRechargeOrderFeundFee(xhpcRechargeOrder.getRechargeOrderId(),refundFee,1);
                        }else{
                            iXhpcRechargeOrderService.updateRechargeOrderFeundFee(xhpcRechargeOrder.getRechargeOrderId(),amount,2);
                            break;
                        }
                    }
                }
                return R.ok("退款订单已提交微信,退款中...");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        refundOrder.setStatus(2);
        refundOrder.setRemark("审核异常");
        updateXhpcRefundOrder(refundOrder,refundFee,2,1);
        return R.fail();
    }

    //支付宝零钱退款
    public R zhbCheckOut(XhpcSettingConfig xhpcSettingConfig,XhpcRefundOrder refundOrder,BigDecimal refundFee){
        try {
            Long userId = refundOrder.getUserId();
            Integer source = refundOrder.getSource();
            Map<String, Object> appUserInfo = new HashMap<>();
            if(UserTypeUtil.USER_TYPE.equals(source)){
                appUserInfo = xhpcUserAccountStatementMapper.appUserInfo(userId);
            }else if(UserTypeUtil.COMMUNIT_TYPE.equals(source)){
                appUserInfo = iXhpcRefundAuditService.getCommunityPersonnelById(userId, refundOrder.getTenantId());
            }
            String phone=appUserInfo.get("phone").toString();
            String uid = StringUtils.valueOf(appUserInfo.get("alipayOpenId"));
            String orderNumber = "alipay" + DateUtils.timePath();
            /** 初始化 **/
            CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
            /** 支付宝网关 **/
            certAlipayRequest.setServerUrl(xhpcSettingConfig.getZhbServerUrl());
            /** 应用id，如何获取请参考：https://opensupport.alipay.com/support/helpcenter/190/201602493024 **/
            certAlipayRequest.setAppId(xhpcSettingConfig.getZfbAppId());
            /** 应用私钥, 如何获取请参考：https://opensupport.alipay.com/support/helpcenter/207/201602471154?ant_source=antsupport  **/
            certAlipayRequest.setPrivateKey(xhpcSettingConfig.getZfbPrivateKey());
            /** 应用公钥证书路径，下载后保存位置的绝对路径  **/
            certAlipayRequest.setCertPath(xhpcSettingConfig.getZfbAppCertPublicKey());
            /** 支付宝公钥证书路径，下载后保存位置的绝对路径 **/
            certAlipayRequest.setAlipayPublicCertPath(xhpcSettingConfig.getZfbAlipayCertPublicKeyRsa());
            /** 支付宝根证书路径，下载后保存位置的绝对路径 **/
            certAlipayRequest.setRootCertPath(xhpcSettingConfig.getZfbAlipayRootCert());
            /** 设置签名类型 **/
            certAlipayRequest.setSignType("RSA2");
            /** 设置请求格式，固定值json **/
            certAlipayRequest.setFormat("json");
            /** 设置编码格式 **/
            certAlipayRequest.setCharset("UTF-8");

            AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
            /** 实例化具体API对应的request类，类名称和接口名称对应,当前调用接口名称：alipay.fund.trans.uni.transfer(单笔转账接口) **/
            AlipayFundTransUniTransferRequest request = new AlipayFundTransUniTransferRequest();
            /** 设置业务参数，具体接口参数传值以文档说明为准：https://opendocs.alipay.com/apis/api_28/alipay.fund.trans.uni.transfer/ **/
            AlipayFundTransUniTransferModel model = new AlipayFundTransUniTransferModel();
            /** 商户端的唯一订单号，对于同一笔转账请求，商户需保证该订单号唯一 **/
            model.setOutBizNo(orderNumber);
            /** 转账金额，TRANS_ACCOUNT_NO_PWD产品取值最低0.1  **/
            String money = refundFee.toString();
            model.setTransAmount(money);
            /** 产品码，单笔无密转账到支付宝账户固定为：TRANS_ACCOUNT_NO_PWD **/
            model.setProductCode("TRANS_ACCOUNT_NO_PWD");
            /** 场景码，单笔无密转账到支付宝账户固定为：DIRECT_TRANSFER  **/
            model.setBizScene("DIRECT_TRANSFER");
            /** 转账业务的标题，用于在支付宝用户的账单里显示 **/
            model.setOrderTitle("转账标题");
            Participant participant = new Participant();
            /** 参与方的唯一标识,收款支付宝账号或者支付宝吧账号唯一会员ID **/
            participant.setIdentity(uid);
            /** 参与方的标识类型：ALIPAY_USER_ID 支付宝的会员ID  **/
            participant.setIdentityType("ALIPAY_USER_ID");
            model.setPayeeInfo(participant);
            /** 业务备注  **/
            String orderOutNumber = StringUtils.valueOf(refundOrder.getRefundOrderNumber());
            model.setRemark("单笔转账--"+orderOutNumber);
            request.setBizModel(model);
            AlipayFundTransUniTransferResponse response = alipayClient.certificateExecute(request);
            /** 获取接口调用结果，如果调用失败，可根据返回错误信息到该文档寻找排查方案：https://opensupport.alipay.com/support/helpcenter/107 **/
            if (response.isSuccess()) {
                //退款成功修改订单
                if(UserTypeUtil.USER_TYPE.equals(source)){
                    Map<String, Object> appUserInfo1 = xhpcUserAccountStatementMapper.appUserInfo(userId);
                    if (StringUtils.isNotNull(appUserInfo1)) {
                        String balance1 = StringUtils.valueOf(appUserInfo1.get("balance"));
                        //减少用户余额
                        XhpcAppUser xhpcAppUser = new XhpcAppUser();
                        xhpcAppUser.setAppUserId(userId);
                        BigDecimal surplus1 =new BigDecimal(balance1).subtract(refundFee);
                        xhpcAppUser.setBalance(surplus1);
                        xhpcUserAccountStatementMapper.updateAppUserBalance(xhpcAppUser);
                    }
                }else{
                    Map<String, Object> communityPersonnel = iXhpcRefundAuditService.getCommunityPersonnelById(userId, refundOrder.getTenantId());
                    BigDecimal surplus1 =new BigDecimal(communityPersonnel.get("balance").toString()).subtract(refundFee);
                    int i = iXhpcRefundAuditService.updateCommunityPersonnelMoney(userId, surplus1,null);
                }
                //增加用户流水记录
                refundOrder.setStatus(1);
                refundOrder.setRemark("支付宝退款成功");
                refundOrder.setOrderId(response.getOrderId());
                refundOrder.setPayFundOrderId(response.getPayFundOrderId());
                refundOrder.setTransPayTime(response.getTransDate());
                updateXhpcRefundOrder(refundOrder,refundFee,1,2);
                XhpcRefundOriginalOrder xhpcRefundOriginalOrder = new XhpcRefundOriginalOrder();
                xhpcRefundOriginalOrder.setUserId(refundOrder.getUserId());
                xhpcRefundOriginalOrder.setType(3);
                xhpcRefundOriginalOrder.setSource(refundOrder.getSource());
                xhpcRefundOriginalOrder.setStatus(1);
                xhpcRefundOriginalOrder.setDelFlag(0);
                xhpcRefundOriginalOrder.setCreateTime(new Date());
                xhpcRefundOriginalOrder.setRemark("支付宝零钱退款");
                xhpcRefundOriginalOrder.setTenantId(refundOrder.getTenantId());
                xhpcRefundOriginalOrder.setTradeNo(orderNumber);
                xhpcRefundOriginalOrder.setTotalFee(refundFee);
                xhpcRefundOriginalOrder.setSettlementTotalFee(refundFee);
                xhpcRefundOriginalOrder.setRefundFee(refundFee);
                xhpcRefundOriginalOrder.setCashRefundFee(refundFee);
                xhpcRefundOriginalOrder.setBuyerUserId(uid);
                xhpcRefundOriginalOrder.setRefundOrderId(refundOrder.getRefundOrderId());
                xhpcRefundOriginalOrderMapper.addXhpcRefundOriginalOrder(xhpcRefundOriginalOrder);
                //增加用户流水记录
                xhpcUserAccountStatementService.add(refundOrder.getRefundOrderId(), "-"+refundFee, userId.toString(), StatusConstants.FLOWING_WATER_REFUND,source,refundOrder.getTenantId());
                //查询以前充值记录
                Date date = new Date();
                String createTime = DateUtil.formatDateTime(date);
                List<XhpcRechargeOrder> totalMoneyList = xhpcRefundOriginalOrderMapper.getTotalMoneyList(userId, source,createTime);
                for (int i = 0; i <totalMoneyList.size() ; i++) {
                    XhpcRechargeOrder xhpcRechargeOrder = totalMoneyList.get(i);
                    BigDecimal amount = xhpcRechargeOrder.getAmount();
                    if(xhpcRechargeOrder.getRefundStatus()==0){
                        if(amount.compareTo(refundFee)>0){
                            iXhpcRechargeOrderService.updateRechargeOrderFeundFee(xhpcRechargeOrder.getRechargeOrderId(),refundFee,1);
                        }else{
                            iXhpcRechargeOrderService.updateRechargeOrderFeundFee(xhpcRechargeOrder.getRechargeOrderId(),amount,2);
                            break;
                        }
                    }else{
                        BigDecimal refundFeeAmount = amount.subtract(xhpcRechargeOrder.getRefundFee());
                        if(refundFeeAmount.compareTo(refundFee)>0){
                            iXhpcRechargeOrderService.updateRechargeOrderFeundFee(xhpcRechargeOrder.getRechargeOrderId(),refundFee,1);
                        }else{
                            iXhpcRechargeOrderService.updateRechargeOrderFeundFee(xhpcRechargeOrder.getRechargeOrderId(),amount,2);
                            break;
                        }
                    }
                }
                return R.ok("退款成功");
            }else{

            }
        }catch (Exception e){
            e.printStackTrace();
            logger.info("++++++++++++支付宝审核异常++++++++++++++++"+e.getMessage());
        }
        return R.fail();
    }

    //退款失败统一发送一条短信提示
    @Override
    public void getTestSms(String number){
        HashMap<String, String> paramMap = new HashMap<>();
        paramMap.put("phone", "18123374652");
        paramMap.put("content", "【翔桦充电】尊敬的管理员，用户退款订单："+number+"，有问题请速速查看。");
        // smsService.sendNotice(paramMap);
    }

    @Override
    public R getRefundOriginalOrderList(Long refundOrderId) {
        List<Map<String, Object>> refundOriginalOrderList = xhpcRefundOriginalOrderMapper.getRefundOriginalOrderList(refundOrderId);
        return R.ok(refundOriginalOrderList,"查询成功");
    }

    @Override
    public Map<String, String> orderqueryUrl(String transactionId){
        XhpcSettingConfig xhpcSettingConfig = xhpcCommonPayment.getXhpcSettingConfigTenantId(UserTypeUtil.OPERATION_WX_TYPE,"000000");
        if(xhpcSettingConfig ==null){

        }
        System.out.println("============查看微信订单信息===============");
        //发送请求
        PrintWriter out = null;
        BufferedReader in = null;
        StringBuffer result = new StringBuffer();
        try{
            URL realUrl = new URL("https://api.mch.weixin.qq.com/pay/orderquery");
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("Content-Type", "text/xml");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            out.print(orderqueryXml(xhpcSettingConfig, transactionId));
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应

            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
                System.out.println(result);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        try{
            Map<String, String> map = WXPayUtil.xmlToMap(result.toString());
            System.out.println("============map==============="+map.toString());
            return map;
        }catch (Exception e){

        }
        return new HashMap<>();
    }

    //查询微信支付信息
    public String orderqueryXml(XhpcSettingConfig xhpcSettingConfig,String transactionId){

        String param = "";
        //随机字符串
        String nonceStr = WXPayUtil.generateNonceStr();
        //公众号id
        param += "appid=" + xhpcSettingConfig.getWxAppId();
        //商户id
        param += "&mch_id=" + xhpcSettingConfig.getWxMchId();
        //随机字符串
        param += "&nonce_str=" + nonceStr;
        //微信订单号
        param += "&transaction_id=" + transactionId;
        //生成签名  添加key值
        String stringSignTemp = param + "&key=" + xhpcSettingConfig.getWxMchKey();
        //签名  不参与签名  默认MD5算法
        String sign = StringUtils.md5(stringSignTemp);
        if(sign.length()!=32){
            sign="0"+sign;
        }
        String xmlString = "<xml>\n" +
                "   <appid>" +  xhpcSettingConfig.getWxAppId() + "</appid>\n" +
                "   <mch_id>" + xhpcSettingConfig.getWxMchId() + "</mch_id>\n" +
                "   <nonce_str>" + nonceStr + "</nonce_str>\n" +
                "   <transaction_id>" + transactionId + "</transaction_id>\n" +
                "   <sign>" + sign + "</sign>\n" +
                "</xml> ";
        logger.info("++++++++++++xmlString++++++++++++++++"+xmlString);
        return xmlString;
    }

    @Override
    public Map<String, String> refundqueryUrl(String transactionId){
        XhpcSettingConfig xhpcSettingConfig = xhpcCommonPayment.getXhpcSettingConfigTenantId(UserTypeUtil.OPERATION_WX_TYPE,"000000");
        if(xhpcSettingConfig ==null){

        }
        System.out.println("============查看微信退款订单信息===============");
        //发送请求
        PrintWriter out = null;
        BufferedReader in = null;
        StringBuffer result = new StringBuffer();
        try{
            URL realUrl = new URL("https://api.mch.weixin.qq.com/pay/refundquery");
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("Content-Type", "text/xml");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            out.print(refundqueryXml(xhpcSettingConfig, transactionId));
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应

            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
                System.out.println(result);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        try{
            Map<String, String> map = WXPayUtil.xmlToMap(result.toString());
            System.out.println("============map==============="+map.toString());
            return map;
        }catch (Exception e){

        }
        return new HashMap<>();
    }


    public String refundqueryXml(XhpcSettingConfig xhpcSettingConfig,String transactionId){

        String param = "";
        //随机字符串
        String nonceStr = WXPayUtil.generateNonceStr();
        //公众号id
        param += "appid=" + xhpcSettingConfig.getWxAppId();
        //商户id
        param += "&mch_id=" + xhpcSettingConfig.getWxMchId();
        //随机字符串
        param += "&nonce_str=" + nonceStr;
        //微信订单号
        param += "&transaction_id=" + transactionId;
        //生成签名  添加key值
        String stringSignTemp = param + "&key=" + xhpcSettingConfig.getWxMchKey();
        //签名  不参与签名  默认MD5算法
        String sign = StringUtils.md5(stringSignTemp);
        if(sign.length()!=32){
            sign="0"+sign;
        }
        String xmlString = "<xml>\n" +
                "   <appid>" +  xhpcSettingConfig.getWxAppId() + "</appid>\n" +
                "   <mch_id>" + xhpcSettingConfig.getWxMchId() + "</mch_id>\n" +
                "   <nonce_str>" + nonceStr + "</nonce_str>\n" +
                "   <transaction_id>" + transactionId + "</transaction_id>\n" +
                "   <sign>" + sign + "</sign>\n" +
                "</xml> ";
        logger.info("++++++退款查询++++++xmlString++++++++++++++++"+xmlString);
        return xmlString;
    }

    public static void main(String[] args) throws AlipayApiException {
        String privateKey ="MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCw/+WnBJiVAqs2j4ghmQBYLH8dQY4mRD45ZhXlDJsNGkNap4uKCi1Q1UkNajWO949j4nZ+pDa0hCEIK4f8QQ/JBc+5PTGitRIKh5LUdk0KVBevivsfMZNhdvIJG2zcF5ht7q+MRnhUQvRDMVcEBTPCBWxSkjy+6sOat8yaP8/V1GzZ94Pz5WQpEgBKYwrabSvqtdk6OYw0wnhgbHfAcPi40+xtNazQvVAPKGb+EAq/qxFOxzuaZ4Al7ZZ2x/zNJorgxWMxXgolC8u71vLM35UThd+/CGFSls2BNl6cYRxdKllgTKD763gWwbkB9v0IgjsT0PtQNaWPqo3jahmdy/CdAgMBAAECggEATvb7R9X/FIuKQt8qBoMx6iR/2VeDyYKsmAL5RaSoD+Jlpi4VTNJZgTSGUNvPZScA67j+0GUGmuZPrkttcZa9KhvTnnq0iDhsAhKV6P+WQ0NdBc3lVvdRHyxnsrRvjolgUbsoylYuHLl6K/f5MCv5+VdeCkB/pVUrSv0w5KgPWv+Z+nOQuHzrNmUNJaAf8x4IFlrVD/rKcrhpWpe5PKQ1BJ9Sbr/+fxY+p+1810Rg27jVErznB8g2cAGAyihGKH++sz3x9Kk7nsZRJ0AjUUtqdN0RD+EBtAV4HRHXcbjfSpFtxqBC03Vt5FFp3g70m92GjU+NWZzQ9Wtn1IsFF8+S6QKBgQDik0pwokU3X6nA/EQXMee0jNMZK/V6BQ/eQMIa0LCAUL5L60FYPZGQQaQhrT29DEki4IstVkHxgLXsQ0vnATHDGbCpaGPGj9Ur+97fuC5PL+Uqxp/dQBwKiHAioE/MDWH8qPDm1cEsgony5NhZX0L/v7Du0VHiUVJcNIA0/1QudwKBgQDH/Gn6kx8nNOPmUtICmimAyNZx3CY+ytL65pYRmVrso++Hw2iT+XLmiWDbGiPacH3R9fLXpFgBe82pOTOetkcgUw/Y2FedeBelmjzxLwF6R/AEV2zB4O3qcBkKn6gqgmJsypFsDOlVWkLSbc4mmsgHES2P1sK/olTtDmnnrR56iwKBgHNwljnjA58d95CjN1IWFDcSlS+7DPxZfedAWWVuNK979CkcORPrcrHsL+MUsGMU0mKZw2+bBkg0yvwQoaiWHDOKcE8wJ73wZK1fTAPyhG3GOl3cC3GgC2l2cKPDyERwAR/JN8x01lKGRCDkZjLK7Yj+svhK4AyOYIcoHLZj7RErAoGAMIcotFxE//+OmdJZEbaVAaI6n1B7m1seTTHtEoIzFR9GvZwGYXnzjsuhTCmQr64CahOThQ5lKJ8BLeIqi4XRxp9BRi5hPF3q5w2BYkk0w5Z3QKZyRq2tLelbuj850G7pMVsKZLzRVhvcATISBz4h8c0SUEgd4+ChWRDZVBWnQrcCgYEAvStqps5r3RB1dk5gn3Ob32zPXu5ZxNJDaykcDK83LsaFf8PT/a6fpkLjaCZ4IT5pbXkD1pef5Gx9GSfygy0ceZzsJ/pWlqYYyLdtljU6gdJZhgoyI655nEhbpwsM0o3sjna4tkB/vdPKXqAfOKxp+yow9Al8usBkjEt8sI5MRro=";
        /** 初始化 **/
        CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
        /** 支付宝网关 **/
        certAlipayRequest.setServerUrl("https://openapi.alipay.com/gateway.do");
        /** 应用id，如何获取请参考：https://opensupport.alipay.com/support/helpcenter/190/201602493024 **/
        certAlipayRequest.setAppId("2021002156615717");
        /** 应用私钥, 如何获取请参考：https://opensupport.alipay.com/support/helpcenter/207/201602471154?ant_source=antsupport  **/
        certAlipayRequest.setPrivateKey(privateKey);
        /** 应用公钥证书路径，下载后保存位置的绝对路径  **/
        certAlipayRequest.setCertPath("E:\\111\\appCertPublicKey.crt");
        /** 支付宝公钥证书路径，下载后保存位置的绝对路径 **/
        certAlipayRequest.setAlipayPublicCertPath("E:\\111\\alipayCertPublicKey_RSA2.crt");
        /** 支付宝根证书路径，下载后保存位置的绝对路径 **/
        certAlipayRequest.setRootCertPath("E:\\111\\alipayRootCert.crt");
        /** 设置签名类型 **/
        certAlipayRequest.setSignType("RSA2");
        /** 设置请求格式，固定值json **/
        certAlipayRequest.setFormat("json");
        /** 设置编码格式 **/
        certAlipayRequest.setCharset("UTF-8");

        AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
        /** 实例化具体API对应的request类，类名称和接口名称对应,当前调用接口名称：alipay.fund.trans.uni.transfer(单笔转账接口) **/
        AlipayTradeRefundRequest request  = new AlipayTradeRefundRequest();
        /** 设置业务参数，具体接口参数传值以文档说明为准：https://opendocs.alipay.com/apis/api_28/alipay.fund.trans.uni.transfer/ **/
        AlipayFundTransUniTransferModel model = new AlipayFundTransUniTransferModel();
        JSONObject bizContent = new JSONObject();
        bizContent.put("trade_no", "2023082322001456711412373759");
        bizContent.put("refund_amount", 2);
        bizContent.put("out_request_no", "HZ01RF002");
        request.setBizContent(bizContent.toString());

        AlipayTradeRefundResponse response = alipayClient.certificateExecute(request);
        System.out.println("response>>>>>>"+response);
        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }

    }
}
