package com.xhpc.payment.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayFundTransUniTransferModel;
import com.alipay.api.domain.Participant;
import com.alipay.api.request.AlipayFundTransUniTransferRequest;
import com.alipay.api.response.AlipayFundTransUniTransferResponse;
import com.google.gson.annotations.SerializedName;
import com.xhpc.common.api.SmsService;
import com.xhpc.common.api.WorkOrderYuService;
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.HttpUtils;
import com.xhpc.common.core.utils.StringUtils;
import com.xhpc.common.core.utils.WXPayUtil;
import com.xhpc.common.core.web.controller.BaseController;
import com.xhpc.common.core.web.domain.AjaxResult;
import com.xhpc.common.core.web.page.TableDataInfo;
import com.xhpc.common.log.annotation.Log;
import com.xhpc.common.log.enums.BusinessType;
import com.xhpc.common.security.service.TokenService;
import com.xhpc.common.util.UserTypeUtil;
import com.xhpc.payment.domain.XhpcAppInternetUser;
import com.xhpc.payment.domain.XhpcAppUser;
import com.xhpc.payment.domain.XhpcRefundAudit;
import com.xhpc.common.domain.XhpcRefundOrder;
import com.xhpc.common.domain.XhpcSettingConfig;
import com.xhpc.payment.mapper.XhpcUserAccountStatementMapper;
import com.xhpc.payment.service.IXhpcCommonPayment;
import com.xhpc.payment.service.IXhpcRefundAuditService;
import com.xhpc.payment.service.IXhpcRefundOrderService;
import com.xhpc.payment.service.IXhpcUserAccountStatementService;
import com.xhpc.payment.service.impl.XhpcUserAccountStatementServiceImpl;
import com.xhpc.payment.util.TransferBillStatus;
import com.xhpc.payment.util.WXPayUtility;
import com.xhpc.system.api.model.LoginUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import javax.net.ssl.SSLContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.security.KeyStore;
import java.util.*;

@EnableScheduling
@RestController
@RequestMapping("/refund/audit")
@Api(value = "退款审核接口", tags = "退款审核接口")
public class XhpcRefundAuditController extends BaseController {

    @Autowired
    private IXhpcRefundAuditService iXhpcRefundAuditService;

    @Autowired
    private IXhpcRefundOrderService iXhpcRefundOrderService;

    @Autowired
    private XhpcUserAccountStatementMapper xhpcUserAccountStatementMapper;

    @Autowired
    private XhpcUserAccountStatementServiceImpl xhpcUserAccountStatementService;

    @Autowired
    private SmsService smsService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private IXhpcCommonPayment xhpcCommonPayment;
    @Autowired
    private WorkOrderYuService workOrderService;

    private static final Logger logger = LoggerFactory.getLogger(XhpcRefundAuditController.class);
    /**
     * 退款审核
     *
     * @param xhpcRefundAudit
     * @return
     */
    @Log(title = "退款-审核", businessType = BusinessType.UPDATE)
    @PostMapping("/examine")
    @ApiOperation(value = "退款审核")
    @Transactional
    public AjaxResult info(@RequestBody XhpcRefundAudit xhpcRefundAudit) {

        return getAjaxResult(xhpcRefundAudit);
    }

    private AjaxResult getAjaxResult(XhpcRefundAudit xhpcRefundAudit) {

        Long refundOrderId = xhpcRefundAudit.getRefundOrderId();
        Map<String, Object> map = iXhpcRefundOrderService.info(refundOrderId);

        if (null == map) {
            AjaxResult.error(HttpStatus.DATA_ERROR, "退款订单不存在");
        }
        String status = StringUtils.valueOf(map.get("status"));
        if (StatusConstants.REFUND_ORDER_STATUS_WAIT != Integer.parseInt(status)) {
            AjaxResult.error(HttpStatus.DATA_ERROR, "退款订单状态不能审核");
        }
        String examineStatus = StringUtils.valueOf(map.get("examineStatus"));
        if (StatusConstants.REFUND_ORDER_STATUS_WAIT != Integer.parseInt(examineStatus)) {
            AjaxResult.error(HttpStatus.DATA_ERROR, "退款订单状态不能审核");
        }
        AjaxResult ajaxResult = iXhpcRefundAuditService.insert(xhpcRefundAudit);
        if (StringUtils.isNotNull(ajaxResult)) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ajaxResult;
        }
        String userId = StringUtils.valueOf(map.get("userId"));
        int source = Integer.parseInt(map.get("source").toString());
        if(UserTypeUtil.USER_TYPE.equals(source)){
            XhpcAppUser xhpcAppUser = new XhpcAppUser();
            xhpcAppUser.setAppUserId(Long.parseLong(userId));
            xhpcAppUser.setIsRefundApplication(0);
            int refundApplication = xhpcUserAccountStatementMapper.updateAppUserRefundApplication(xhpcAppUser);
            if (refundApplication == 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error();
            }
        }else if(UserTypeUtil.COMMUNIT_TYPE.equals(source)){
            int i = iXhpcRefundAuditService.updateCommunityPersonnelMoney(Long.parseLong(userId), null, 0);
            if (i == 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error();
            }
        }else if(UserTypeUtil.INTERNET_TYPE.equals(source) && Long.parseLong(userId)>10000){
            //川逸充用户退款
            XhpcAppInternetUser xhpcAppUser = new XhpcAppInternetUser();
            xhpcAppUser.setAppInternetUserId(Long.parseLong(userId));
            xhpcAppUser.setIsRefundApplication(0);
            int refundApplication = xhpcUserAccountStatementMapper.updateAppInternetUserBalance(xhpcAppUser);
            if (refundApplication == 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error();
            }
        }else{
            AjaxResult.error(HttpStatus.DATA_ERROR, "该用户不能退款");
        }

        if (StatusConstants.REFUND_ORDER_STATUS_SUCCESS == xhpcRefundAudit.getStatus()) {
            String type = StringUtils.valueOf(map.get("type"));
            if (StatusConstants.OPERATION_WX_TYPE.equals(type)) {
               return enterpriseCheckOut(xhpcRefundAudit);
            }
            if (StatusConstants.OPERATION_ALI_PAY_TYPE.equals(type)) {
               return zhbCheckOut(xhpcRefundAudit);
            }
        }
        XhpcRefundOrder refundOrder=new XhpcRefundOrder();
        refundOrder.setRefundOrderId(refundOrderId);
        refundOrder.setStatus(2);
        refundOrder.setExamineStatus(2);
        refundOrder.setRemark("退款订单状态不对");

        String amount = "-" + StringUtils.valueOf(map.get("amount"));

        String phone="";
        if(UserTypeUtil.USER_TYPE.equals(source)){
            phone=map.get("phone").toString();
        }else{
            phone=map.get("communityPhone").toString();
        }
        updateXhpcRefundOrder(refundOrder,amount,userId,phone,2,source,map.get("tenantId").toString());

        return AjaxResult.success();
    }

    /**
     * 取消申请
     *
     * @param map
     * @return
     */
    @PostMapping("/cancelExamine")
    @ApiOperation(value = "取消申请")
    @Transactional
    public AjaxResult cancelExamine(HttpServletRequest request, @RequestBody Map<String, Object> map) {
        String userId = StringUtils.valueOf(map.get("userId"));
        if (StringUtils.isEmpty(userId)) {
            return AjaxResult.error(HttpStatus.NOT_NULL, "用户id不能为空");
        }
        LoginUser loginUser = tokenService.getLoginUser(request);
        Long userid = loginUser.getUserid();
        Integer userType = loginUser.getUserType();
        String tenantId = loginUser.getTenantId();
        Map<String, Object> refundOrder = iXhpcRefundOrderService.getNotRefundOrder(userid,userType,tenantId);
        if (StringUtils.isNull(refundOrder)) {
            return AjaxResult.error(HttpStatus.DATA_ERROR, "退款订单不存在");
        }
        String refundOrderId = StringUtils.valueOf(refundOrder.get("refundOrderId"));
        XhpcRefundOrder xhpcRefundOrder = new XhpcRefundOrder();
        xhpcRefundOrder.setRefundOrderId(Long.parseLong(refundOrderId));
        xhpcRefundOrder.setExamineStatus(1);
        xhpcRefundOrder.setStatus(StatusConstants.REFUND_ORDER_STATUS_CANCEL);
        int updateStatus = iXhpcRefundOrderService.updateStatus(xhpcRefundOrder);
        if (updateStatus == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error();
        }
        if(UserTypeUtil.USER_TYPE.equals(userType)){
            XhpcAppUser xhpcAppUser = new XhpcAppUser();
            xhpcAppUser.setAppUserId(Long.parseLong(userId));
            xhpcAppUser.setIsRefundApplication(0);
            xhpcUserAccountStatementMapper.updateAppUserRefundApplication(xhpcAppUser);
        }else if(UserTypeUtil.COMMUNIT_TYPE.equals(userType)){
            iXhpcRefundAuditService.updateCommunityPersonnelMoney(Long.parseLong(userId), null,0);
        }else{
            return AjaxResult.error(HttpStatus.DATA_ERROR, "该用户不能申请退款");
        }
        return AjaxResult.success();
    }

    /**
     * 退款审核页列表
     */
    //@PreAuthorize(hasPermi = "refund:audit:list")
    @GetMapping("/list")
    public TableDataInfo page(@RequestParam Long refundOrderId) {
        startPage();
        List<Map<String, Object>> list = iXhpcRefundAuditService.list(refundOrderId);
        return getDataTable(list);
    }


    /**
     * 企业退款
     *
     * @return
     */
    public AjaxResult enterpriseCheckOut(@RequestBody XhpcRefundAudit xhpcRefundAudit) {
        //只有审核通过才能退款
        XhpcRefundOrder refundOrder=new XhpcRefundOrder();
        Long refundOrderId = xhpcRefundAudit.getRefundOrderId();
        refundOrder.setRefundOrderId(refundOrderId);

        Map<String, Object> xhpcRefundOrder = iXhpcRefundOrderService.info(xhpcRefundAudit.getRefundOrderId());
        if (StringUtils.isNull(xhpcRefundOrder)) {
            return AjaxResult.error(HttpStatus.DATA_ERROR, "订单不存在");
        }
        int source = Integer.parseInt(xhpcRefundOrder.get("source").toString());

        String userId = StringUtils.valueOf(xhpcRefundOrder.get("userId"));
        String phone="";
        if(source==0 || (source==1 && Long.valueOf(userId)>10000)){
            phone=xhpcRefundOrder.get("phone").toString();
        }else{
            phone=xhpcRefundOrder.get("communityPhone").toString();
        }
        logger.info("++++++++++++xhpcRefundOrder++++++++++++++++");
        logger.info("++++++++++++xhpcRefundOrder++++++++++++++++"+xhpcRefundOrder.toString());
        logger.info("++++++++++++xhpcRefundOrder++++++++++++++++");


        BigDecimal amount = new BigDecimal(xhpcRefundOrder.get("amount").toString());
        logger.info("++++++++++++amount++++++++++++++++"+amount);
        String amountRefundOrder = "-" + amount.toString();
        String tenantId = StringUtils.valueOf(xhpcRefundOrder.get("tenantId"));
        XhpcSettingConfig xhpcSettingConfig = xhpcCommonPayment.getXhpcSettingConfigTenantId(UserTypeUtil.OPERATION_WX_TYPE, xhpcRefundOrder.get("tenantId").toString());
        if(xhpcSettingConfig ==null){
            refundOrder.setStatus(2);
            refundOrder.setRemark("订单状态不能退款");
            updateXhpcRefundOrder(refundOrder,amountRefundOrder,userId,phone,2,source,tenantId);
            return AjaxResult.error(HttpStatus.ERROR_STATUS, "订单状态不能退款");
        }

        String examineStatus = StringUtils.valueOf(xhpcRefundOrder.get("examineStatus"));
        if (!"1".equals(examineStatus)) {
            refundOrder.setStatus(2);
            refundOrder.setRemark("订单状态不能退款");
            updateXhpcRefundOrder(refundOrder,amountRefundOrder,userId,phone,2,source,tenantId);
            return AjaxResult.error(HttpStatus.ERROR_STATUS, "订单状态不能退款");
        }
        String status = StringUtils.valueOf(xhpcRefundOrder.get("status"));
        if (!"0".equals(status)) {
            refundOrder.setStatus(2);
            refundOrder.setRemark("订单状态不能退款");
            updateXhpcRefundOrder(refundOrder,amountRefundOrder,userId,phone,2,source,tenantId);
            return AjaxResult.error(HttpStatus.ERROR_STATUS, "订单状态不能退款");
        }



        CloseableHttpClient httpClient = null;
        try {
            //证书的地址
            //String certPath = ConfigListener.getConf().get("certPath");
            //System.out.println("certPath:"+certPath);
            httpClient = initCert(xhpcSettingConfig);
        } catch (Exception e) {
            e.printStackTrace();

        }
        String orderOutNumber = StringUtils.valueOf(xhpcRefundOrder.get("refundOrderNumber"));
        String openId = StringUtils.valueOf(xhpcRefundOrder.get("openId"));
        //Double amount = Double.parseDouble(StringUtils.valueOf(xhpcRefundOrder.get("amount")));
        //退款金额单位为分
        BigDecimal value = amount.multiply(new BigDecimal(100));
        Integer refund_fee = value.intValue();
        if (refund_fee <= 0) {
            refundOrder.setStatus(2);
            refundOrder.setRemark("订单金额出错");
            updateXhpcRefundOrder(refundOrder,amountRefundOrder,userId,phone,2,source,tenantId);
            return AjaxResult.error(HttpStatus.ERROR_STATUS, "订单金额出错");
        }
        if(UserTypeUtil.USER_TYPE.equals(source)){
            Map<String, Object> appUserInfo = xhpcUserAccountStatementMapper.appUserInfo(Long.parseLong(userId));
            String balance = StringUtils.valueOf(appUserInfo.get("balance"));
            if (StringUtils.isNull(appUserInfo)) {
                refundOrder.setStatus(2);
                refundOrder.setRemark("用户不存在");
                updateXhpcRefundOrder(refundOrder,amountRefundOrder,userId,phone,2,source,tenantId);
                return AjaxResult.error(HttpStatus.DATA_ERROR, "用户不存在");
            }
            BigDecimal surplus = BigDecimal.valueOf(Double.valueOf(balance)).subtract(amount);
            if (surplus.compareTo(BigDecimal.ZERO) == -1) {
                refundOrder.setStatus(2);
                refundOrder.setRemark("余额不足");
                updateXhpcRefundOrder(refundOrder,amountRefundOrder,userId,phone,2,source,tenantId);
                return AjaxResult.error(HttpStatus.ERROR_STATUS, "余额不足");
            }
        }else if(UserTypeUtil.COMMUNIT_TYPE.equals(source)){
            Map<String, Object> communityPersonnel = iXhpcRefundAuditService.getCommunityPersonnelById(Long.parseLong(userId), tenantId);
            if (StringUtils.isNull(communityPersonnel)) {
                refundOrder.setStatus(2);
                refundOrder.setRemark("用户不存在");
                updateXhpcRefundOrder(refundOrder,amountRefundOrder,userId,phone,2,source,tenantId);
                return AjaxResult.error(HttpStatus.DATA_ERROR, "用户不存在");
            }
            String balance = StringUtils.valueOf(communityPersonnel.get("balance"));
            BigDecimal surplus = BigDecimal.valueOf(Double.valueOf(balance)).subtract(amount);
            if (surplus.compareTo(BigDecimal.ZERO) == -1) {
                refundOrder.setStatus(2);
                refundOrder.setRemark("余额不足");
                updateXhpcRefundOrder(refundOrder,amountRefundOrder,userId,phone,2,source,tenantId);
                return AjaxResult.error(HttpStatus.ERROR_STATUS, "余额不足");
            }
        }else if(UserTypeUtil.INTERNET_TYPE.equals(source)){
            System.out.println("================获取退款川逸充用户信息========================================");
            System.out.println("================获取退款川逸充用户信息========================================");
            System.out.println("================获取退款川逸充用户信息========================================");
            Map<String, Object> appInternetUser = iXhpcRefundAuditService.getXhpcAppInternetUserById(Long.parseLong(userId), tenantId);
            if (StringUtils.isNull(appInternetUser)) {
                refundOrder.setStatus(2);
                refundOrder.setRemark("用户不存在");
                updateXhpcRefundOrder(refundOrder,amountRefundOrder,userId,phone,2,source,tenantId);
                return AjaxResult.error(HttpStatus.DATA_ERROR, "用户不存在");
            }
            String balance = StringUtils.valueOf(appInternetUser.get("balance"));
            BigDecimal surplus = BigDecimal.valueOf(Double.valueOf(balance)).subtract(amount);
            if (surplus.compareTo(BigDecimal.ZERO) == -1) {
                refundOrder.setStatus(2);
                refundOrder.setRemark("余额不足");
                updateXhpcRefundOrder(refundOrder,amountRefundOrder,userId,phone,2,source,tenantId);
                return AjaxResult.error(HttpStatus.ERROR_STATUS, "余额不足");
            }
        }else{
            return AjaxResult.error(HttpStatus.DATA_ERROR, "用户不存在");
        }

        String result = "";
        HttpPost httpPost = new HttpPost(xhpcSettingConfig.getWxTransfersUrl());
        StringEntity postEntity = new StringEntity(creatXMLParam(orderOutNumber, refund_fee.toString(), "退款申请", openId,xhpcSettingConfig,source), "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();
        }
        logger.info("++++++++++++amount++++++++++++++++"+amount);
        logger.info("++++++++++++amount++++++++++++++++"+amount);
        logger.info("++++++++++++amount++++++++++++++++"+amount);
        return parseXml(result, xhpcRefundAudit.getRefundOrderId(), amount, userId,phone,source,tenantId);
    }


    /**
     * 加载证书
     *
     * @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"}, null,
                        SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        return HttpClients.custom().setSSLSocketFactory(sslsf).build();
    }

    /**
     * 生成xml格式  添加参数时，按照abcd26个字母顺序添加
     *
     * @param openid           用户openid
     * @param partner_trade_no 商户退款单号
     * @param amount           退款金额
     * @param refund_desc      退款原因
     * @return
     */
    private String creatXMLParam(String partner_trade_no, String amount, String refund_desc, String openid,XhpcSettingConfig xhpcSettingConfig,Integer source) {
        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;
        if(source!=1){
            //用户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";
        if (source!=1) {
            xmlString += "   <openid>" + openid + "</openid>\n";
        }
        xmlString +=
                "   <partner_trade_no>" + partner_trade_no + "</partner_trade_no>\n" +
                "   <sign>" + sign + "</sign>\n" +
                "</xml> ";

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

    /**
     * 解析xml字符串
     *
     * @param result 请求后的结果
     * @return
     */
    private AjaxResult parseXml(String result, Long id, BigDecimal amount, String userId,String phone,Integer source,String tenantId) {
        XhpcRefundOrder refundOrder=new XhpcRefundOrder();
        refundOrder.setRefundOrderId(id);
        String amountRefundOrder = "-" + amount.toString();
        try {
            Map<String, String> map = WXPayUtil.xmlToMap(result);
            String result_code = map.get("result_code");
            logger.info("++++++++++++退款信息++++++++++++++++");
            logger.info("++++++++++++退款信息++++++++++++++++"+map.toString());
            logger.info("++++++++++++退款信息++++++++++++++++");
            if ("FAIL".equals(result_code)) {
                refundOrder.setStatus(2);
                refundOrder.setRemark(map.get("err_code_des").toString());
                updateXhpcRefundOrder(refundOrder,amountRefundOrder,userId,phone,2,source,tenantId);
                logger.info("++++++++++++审核失败原因++++++++++++++++"+map.get("err_code_des").toString()+"错误代码："+map.get("err_code").toString());
                return AjaxResult.error(map.get("err_code_des"));
            } else {
                //退款成功修改订单
                if(UserTypeUtil.USER_TYPE.equals(source)){
                    Map<String, Object> appUserInfo = xhpcUserAccountStatementMapper.appUserInfo(Long.parseLong(userId));
                    String balance = StringUtils.valueOf(appUserInfo.get("balance"));
                    //减少用户余额
                    XhpcAppUser xhpcAppUser = new XhpcAppUser();
                    xhpcAppUser.setAppUserId(Long.parseLong(userId));
                    BigDecimal surplus =new BigDecimal(balance).subtract(amount);
                    xhpcAppUser.setBalance(surplus);
                    xhpcUserAccountStatementMapper.updateAppUserBalance(xhpcAppUser);

                }else if(UserTypeUtil.COMMUNIT_TYPE.equals(source)){
                    Map<String, Object> communityPersonnel = iXhpcRefundAuditService.getCommunityPersonnelById(Long.parseLong(userId), tenantId);
                    BigDecimal surplus =new BigDecimal(communityPersonnel.get("balance").toString()).subtract(amount);
                    int i = iXhpcRefundAuditService.updateCommunityPersonnelMoney(Long.parseLong(userId), surplus,null);
                }else if(UserTypeUtil.INTERNET_TYPE.equals(source) && Long.valueOf(userId)>10000){
                    Map<String, Object> appUserInfo = xhpcUserAccountStatementMapper.getAppInternetUser(Long.parseLong(userId));
                    String balance = StringUtils.valueOf(appUserInfo.get("balance"));
                    //减少用户余额
                    XhpcAppInternetUser xhpcAppUser = new XhpcAppInternetUser();
                    xhpcAppUser.setAppInternetUserId(Long.parseLong(userId));
                    BigDecimal surplus =new BigDecimal(balance).subtract(amount);
                    xhpcAppUser.setBalance(surplus);
                    int i = xhpcUserAccountStatementMapper.updateAppInternetUserBalance(xhpcAppUser);
                    logger.info("++++++++++++退款信息+++++++44444444+++++++iii++"+i);
                }
                refundOrder.setStatus(1);
                refundOrder.setRemark("微信退款成功");
                refundOrder.setPaymentNo(map.get("payment_no").toString());
                refundOrder.setPaymentTime(map.get("payment_time").toString());
                updateXhpcRefundOrder(refundOrder,amountRefundOrder,userId,phone,1,source,tenantId);
                return AjaxResult.success("退款成功");
            }
        } catch (Exception e) {
            AjaxResult.error(e.getMessage());
            e.printStackTrace();
            logger.info("++++++++++++审核异常++++++++++++++++"+e.getMessage());
        }
        refundOrder.setStatus(2);
        refundOrder.setRemark("审核异常");
        updateXhpcRefundOrder(refundOrder,amountRefundOrder,userId,phone,2,source,tenantId);
        return AjaxResult.error();
    }

    /**
     * 25       * 支付宝转账到用户账号
     * 26       * @throws IOException
     * 27
     */
    public  AjaxResult zhbCheckOut(@RequestBody XhpcRefundAudit xhpcRefundAudit){
        XhpcRefundOrder refundOrder =new XhpcRefundOrder();
        //修改订单状态
        Long refundOrderId = xhpcRefundAudit.getRefundOrderId();
        refundOrder.setRefundOrderId(refundOrderId);
        //只有审核通过才能退款
        Map<String, Object> xhpcRefundOrder = iXhpcRefundOrderService.info(xhpcRefundAudit.getRefundOrderId());
        int source = Integer.parseInt(xhpcRefundOrder.get("source").toString());
        String phone="";
        if(source==0){
            phone=xhpcRefundOrder.get("phone").toString();
        }else{
            phone=xhpcRefundOrder.get("communityPhone").toString();
        }
        if (StringUtils.isNull(xhpcRefundOrder)) {
            return AjaxResult.error(HttpStatus.DATA_ERROR, "订单不存在");
        }
        String userId = StringUtils.valueOf(xhpcRefundOrder.get("userId"));
        String money = StringUtils.valueOf(xhpcRefundOrder.get("amount"));
        String amountRefundOrder = "-" + money;
        String examineStatus = StringUtils.valueOf(xhpcRefundOrder.get("examineStatus"));
        String tenantId = StringUtils.valueOf(xhpcRefundOrder.get("tenantId"));
        XhpcSettingConfig xhpcSettingConfig = xhpcCommonPayment.getXhpcSettingConfigTenantId(UserTypeUtil.OPERATION_ALI_PAY_TYPE,xhpcRefundOrder.get("tenantId").toString());
        if(xhpcSettingConfig ==null){
            refundOrder.setStatus(2);
            refundOrder.setRemark("订单状态不能退款");
            updateXhpcRefundOrder(refundOrder,amountRefundOrder,userId,phone,2,source,tenantId);
            return AjaxResult.error(HttpStatus.ERROR_STATUS, "订单状态不能退款");
        }
        if (!"1".equals(examineStatus)) {
            refundOrder.setStatus(2);
            refundOrder.setRemark("订单状态不能退款");
            updateXhpcRefundOrder(refundOrder,amountRefundOrder,userId,phone,2,source,tenantId);
            return AjaxResult.error(HttpStatus.ERROR_STATUS, "订单状态不能退款");
        }
        String status = StringUtils.valueOf(xhpcRefundOrder.get("status"));
        if (!"0".equals(status)) {
            refundOrder.setStatus(2);
            refundOrder.setRemark("订单状态不能退款");
            updateXhpcRefundOrder(refundOrder,amountRefundOrder,userId,phone,2,source,tenantId);
            return AjaxResult.error(HttpStatus.ERROR_STATUS, "订单状态不能退款");
        }
        String orderOutNumber = StringUtils.valueOf(xhpcRefundOrder.get("refundOrderNumber"));
        String uid = StringUtils.valueOf(xhpcRefundOrder.get("alipayId"));

        Double amount = Double.parseDouble(StringUtils.valueOf(xhpcRefundOrder.get("amount")));
        //退款金额单位为分
        Double value = amount * 100;
        Integer refund_fee = value.intValue();
        if (refund_fee <= 0) {
            refundOrder.setStatus(2);
            refundOrder.setRemark("订单金额出错");
            updateXhpcRefundOrder(refundOrder,amountRefundOrder,userId,phone,2,source,tenantId);
            return AjaxResult.error(HttpStatus.ERROR_STATUS, "订单金额出错");
        }
        if(UserTypeUtil.USER_TYPE.equals(source)){
            Map<String, Object> appUserInfo = xhpcUserAccountStatementMapper.appUserInfo(Long.parseLong(userId));
            String balance = StringUtils.valueOf(appUserInfo.get("balance"));
            if (StringUtils.isNull(appUserInfo)) {
                refundOrder.setStatus(2);
                refundOrder.setRemark("用户不存在");
                updateXhpcRefundOrder(refundOrder,amountRefundOrder,userId,phone,2,source,tenantId);
                return AjaxResult.error(HttpStatus.DATA_ERROR, "用户不存在");
            }
            BigDecimal surplus = BigDecimal.valueOf(Double.valueOf(balance)).subtract(BigDecimal.valueOf(amount));
            if (surplus.compareTo(BigDecimal.ZERO) == -1) {
                refundOrder.setStatus(2);
                refundOrder.setRemark("余额不足");
                updateXhpcRefundOrder(refundOrder,amountRefundOrder,userId,phone,2,source,tenantId);
                return AjaxResult.error(HttpStatus.ERROR_STATUS, "余额不足");
            }
        }else if(UserTypeUtil.COMMUNIT_TYPE.equals(source)){
            Map<String, Object> communityPersonnel = iXhpcRefundAuditService.getCommunityPersonnelById(Long.parseLong(userId), tenantId);
            if (StringUtils.isNull(communityPersonnel)) {
                refundOrder.setStatus(2);
                refundOrder.setRemark("用户不存在");
                updateXhpcRefundOrder(refundOrder,amountRefundOrder,userId,phone,2,source,tenantId);
                return AjaxResult.error(HttpStatus.DATA_ERROR, "用户不存在");
            }
            String balance = StringUtils.valueOf(communityPersonnel.get("balance"));
            BigDecimal surplus = BigDecimal.valueOf(Double.valueOf(balance)).subtract(BigDecimal.valueOf(amount));
            if (surplus.compareTo(BigDecimal.ZERO) == -1) {
                refundOrder.setStatus(2);
                refundOrder.setRemark("余额不足");
                updateXhpcRefundOrder(refundOrder,amountRefundOrder,userId,phone,2,source,tenantId);
                return AjaxResult.error(HttpStatus.ERROR_STATUS, "余额不足");
            }
        }else{
            return AjaxResult.error(HttpStatus.DATA_ERROR, "用户不存在");
        }
        try {
            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  **/
            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);
            /** 业务备注  **/
            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(Long.parseLong(userId));
                    if (StringUtils.isNotNull(appUserInfo1)) {
                        String balance1 = StringUtils.valueOf(appUserInfo1.get("balance"));
                        //减少用户余额
                        XhpcAppUser xhpcAppUser = new XhpcAppUser();
                        xhpcAppUser.setAppUserId(Long.parseLong(userId));
                        BigDecimal surplus1 =new BigDecimal(balance1).subtract(BigDecimal.valueOf(amount));
                        xhpcAppUser.setBalance(surplus1);
                        xhpcUserAccountStatementMapper.updateAppUserBalance(xhpcAppUser);
                    }
                }else{
                    Map<String, Object> communityPersonnel = iXhpcRefundAuditService.getCommunityPersonnelById(Long.parseLong(userId), tenantId);
                    BigDecimal surplus1 =new BigDecimal(communityPersonnel.get("balance").toString()).subtract(BigDecimal.valueOf(amount));
                    int i = iXhpcRefundAuditService.updateCommunityPersonnelMoney(Long.parseLong(userId), surplus1,null);
                }
                refundOrder.setStatus(1);
                refundOrder.setRemark("支付宝退款成功");
                refundOrder.setOrderId(response.getOrderId());
                refundOrder.setPayFundOrderId(response.getPayFundOrderId());
                refundOrder.setTransPayTime(response.getTransDate());
                updateXhpcRefundOrder(refundOrder,amountRefundOrder,userId,phone,1,source,tenantId);

            return AjaxResult.success("退款成功");
        } else {
            System.out.println("调用失败");

        }
        }catch (Exception e){
            e.printStackTrace();
            logger.info("++++++++++++支付宝审核异常++++++++++++++++"+e.getMessage());
        }
        refundOrder.setStatus(2);
        refundOrder.setRemark("调用失败");
        updateXhpcRefundOrder(refundOrder,amountRefundOrder,userId,phone,2,source,tenantId);
        return AjaxResult.error("退款失败");
    }


    /**
     * 修改退款订单号
     * @param refundOrder
     */
    /**
     * 修改退款订单号，增加用户流水，发送短信
     * @param refundOrder
     * @param amount
     * @param userId
     * @param phone
     * @param type          1成功 2失败
     */
    public void updateXhpcRefundOrder(XhpcRefundOrder refundOrder,String amount,String userId,String phone,Integer type,Integer source,String tenantId){
        iXhpcRefundOrderService.update(refundOrder);
        if(type ==1){
            xhpcUserAccountStatementService.add(refundOrder.getRefundOrderId(), amount, userId, StatusConstants.FLOWING_WATER_REFUND,source,tenantId);
        }else{
            xhpcUserAccountStatementService.add(refundOrder.getRefundOrderId(), amount, userId, StatusConstants.FLOWING_WATER_REFUND_ERROE,source,tenantId);
            try{
                //发送短信
                HashMap<String, String> paramMap = new HashMap<>();
                paramMap.put("phone", phone);
                paramMap.put("content", "【翔桦充电】退款-尊敬的用户，当前退款人数较多，申请退款失败，请您重新提交申请！");
                smsService.sendNotice(paramMap);
            }catch (Exception e){

            }
        }
    }

    /**
     * 定时任务，每20秒，扫描一次，退款订单金额小于100，自动审核通过
     *
     */
    //@Scheduled(cron = "0/20 * * * * ? ")
    @GetMapping("/moneyPage")
    public void moneyPage(){
        logger.info("++++++++++++每20秒，扫描一次，退款订单金额小于200，自动审核通过++++++++++++++++");
        try {
            List<Long> list = iXhpcRefundOrderService.moneyPage(1);
            logger.info("++++++++++++有自动退款订单+++++list+++++++++++"+list.size());
            if(list !=null && list.size()>0){
                for (int i = 0; i <list.size() ; i++) {
                    Long aLong = list.get(i);
                    XhpcRefundAudit xhpcRefundAudit =new XhpcRefundAudit();
                    xhpcRefundAudit.setRefundOrderId(aLong);
                    xhpcRefundAudit.setStatus(1);
                    xhpcRefundAudit.setRemark("自动审核通过");
                    getAjaxResult(xhpcRefundAudit);
                }
            }
        }catch (Exception e){
            logger.info("++++++++++++自动审核异常++++++++++++++++");
            e.printStackTrace();
            //后期可以增加短信通知
        }
    }

    @Scheduled(cron = "0 0/10 * * * ?")
    @GetMapping("/moneyPageTime")
    public void moneyPageTime(){
        logger.info("++++++++++++每10分钟，扫描一次，退款订单金额大于200，自动生成工单++++++++++++++++");
        try {
            List<Long> list = iXhpcRefundOrderService.moneyPage(2);
            if(list !=null && list.size()>0){
                Date date = DateUtil.date();
                String format = DateUtil.format(date, "yyyy-MM-dd");
                R r = workOrderService.workOrderMessage(3, format);
                if(r.getCode()==200){
                    workOrderService.addNewOrder("3","有退款订单待处理","定时任务自动扫描退款订单","","","","");
                }
            }
        }catch (Exception e){
            logger.info("++++++++++++每10分钟，扫描一次，退款订单金额大于100，自动生成工单异常++++++++++++++++");
            e.printStackTrace();
            //后期可以增加短信通知
        }
    }

    //新版微信商户退款到零钱
    public AjaxResult enterpriseCheckOutYu(@RequestBody XhpcRefundAudit xhpcRefundAudit) {
        //只有审核通过才能退款
        XhpcRefundOrder refundOrder = new XhpcRefundOrder();
        Long refundOrderId = xhpcRefundAudit.getRefundOrderId();
        refundOrder.setRefundOrderId(refundOrderId);

        Map<String, Object> xhpcRefundOrder = iXhpcRefundOrderService.info(xhpcRefundAudit.getRefundOrderId());
        if (StringUtils.isNull(xhpcRefundOrder)) {
            return AjaxResult.error(HttpStatus.DATA_ERROR, "订单不存在");
        }
        int source = Integer.parseInt(xhpcRefundOrder.get("source").toString());

        String userId = StringUtils.valueOf(xhpcRefundOrder.get("userId"));
        String phone = "";
        if (source == 0 || (source == 1 && Long.valueOf(userId) > 10000)) {
            phone = xhpcRefundOrder.get("phone").toString();
        } else {
            phone = xhpcRefundOrder.get("communityPhone").toString();
        }
        logger.info("++++++++++++xhpcRefundOrder++++++++++++++++");
        logger.info("++++++++++++xhpcRefundOrder++++++++++++++++" + xhpcRefundOrder.toString());
        logger.info("++++++++++++xhpcRefundOrder++++++++++++++++");


        BigDecimal amount = new BigDecimal(xhpcRefundOrder.get("amount").toString());
        logger.info("++++++++++++amount++++++++++++++++" + amount);
        String amountRefundOrder = "-" + amount.toString();
        String tenantId = StringUtils.valueOf(xhpcRefundOrder.get("tenantId"));
        XhpcSettingConfig xhpcSettingConfig = xhpcCommonPayment.getXhpcSettingConfigTenantId(UserTypeUtil.OPERATION_WX_TYPE, xhpcRefundOrder.get("tenantId").toString());
        if (xhpcSettingConfig == null) {
            refundOrder.setStatus(2);
            refundOrder.setRemark("订单状态不能退款");
            updateXhpcRefundOrder(refundOrder, amountRefundOrder, userId, phone, 2, source, tenantId);
            return AjaxResult.error(HttpStatus.ERROR_STATUS, "订单状态不能退款");
        }

        String examineStatus = StringUtils.valueOf(xhpcRefundOrder.get("examineStatus"));
        if (!"1".equals(examineStatus)) {
            refundOrder.setStatus(2);
            refundOrder.setRemark("订单状态不能退款");
            updateXhpcRefundOrder(refundOrder, amountRefundOrder, userId, phone, 2, source, tenantId);
            return AjaxResult.error(HttpStatus.ERROR_STATUS, "订单状态不能退款");
        }
        String status = StringUtils.valueOf(xhpcRefundOrder.get("status"));
        if (!"0".equals(status)) {
            refundOrder.setStatus(2);
            refundOrder.setRemark("订单状态不能退款");
            updateXhpcRefundOrder(refundOrder, amountRefundOrder, userId, phone, 2, source, tenantId);
            return AjaxResult.error(HttpStatus.ERROR_STATUS, "订单状态不能退款");
        }
        CloseableHttpClient httpClient = null;
        try {
            //证书的地址
            //String certPath = ConfigListener.getConf().get("certPath");
            //System.out.println("certPath:"+certPath);
            httpClient = initCert(xhpcSettingConfig);
        } catch (Exception e) {
            e.printStackTrace();

        }
        String orderOutNumber = StringUtils.valueOf(xhpcRefundOrder.get("refundOrderNumber"));
        String openId = StringUtils.valueOf(xhpcRefundOrder.get("openId"));
        //Double amount = Double.parseDouble(StringUtils.valueOf(xhpcRefundOrder.get("amount")));
        //退款金额单位为分
        BigDecimal value = amount.multiply(new BigDecimal(100));
        Integer refund_fee = value.intValue();
        if (refund_fee <= 0) {
            refundOrder.setStatus(2);
            refundOrder.setRemark("订单金额出错");
            updateXhpcRefundOrder(refundOrder,amountRefundOrder,userId,phone,2,source,tenantId);
            return AjaxResult.error(HttpStatus.ERROR_STATUS, "订单金额出错");
        }
        if(UserTypeUtil.USER_TYPE.equals(source)){
            Map<String, Object> appUserInfo = xhpcUserAccountStatementMapper.appUserInfo(Long.parseLong(userId));
            String balance = StringUtils.valueOf(appUserInfo.get("balance"));
            if (StringUtils.isNull(appUserInfo)) {
                refundOrder.setStatus(2);
                refundOrder.setRemark("用户不存在");
                updateXhpcRefundOrder(refundOrder,amountRefundOrder,userId,phone,2,source,tenantId);
                return AjaxResult.error(HttpStatus.DATA_ERROR, "用户不存在");
            }
            BigDecimal surplus = BigDecimal.valueOf(Double.valueOf(balance)).subtract(amount);
            if (surplus.compareTo(BigDecimal.ZERO) == -1) {
                refundOrder.setStatus(2);
                refundOrder.setRemark("余额不足");
                updateXhpcRefundOrder(refundOrder,amountRefundOrder,userId,phone,2,source,tenantId);
                return AjaxResult.error(HttpStatus.ERROR_STATUS, "余额不足");
            }
        }else if(UserTypeUtil.COMMUNIT_TYPE.equals(source)){
            Map<String, Object> communityPersonnel = iXhpcRefundAuditService.getCommunityPersonnelById(Long.parseLong(userId), tenantId);
            if (StringUtils.isNull(communityPersonnel)) {
                refundOrder.setStatus(2);
                refundOrder.setRemark("用户不存在");
                updateXhpcRefundOrder(refundOrder,amountRefundOrder,userId,phone,2,source,tenantId);
                return AjaxResult.error(HttpStatus.DATA_ERROR, "用户不存在");
            }
            String balance = StringUtils.valueOf(communityPersonnel.get("balance"));
            BigDecimal surplus = BigDecimal.valueOf(Double.valueOf(balance)).subtract(amount);
            if (surplus.compareTo(BigDecimal.ZERO) == -1) {
                refundOrder.setStatus(2);
                refundOrder.setRemark("余额不足");
                updateXhpcRefundOrder(refundOrder,amountRefundOrder,userId,phone,2,source,tenantId);
                return AjaxResult.error(HttpStatus.ERROR_STATUS, "余额不足");
            }
        }else if(UserTypeUtil.INTERNET_TYPE.equals(source)){
            System.out.println("================获取退款川逸充用户信息========================================");
            System.out.println("================获取退款川逸充用户信息========================================");
            System.out.println("================获取退款川逸充用户信息========================================");
            Map<String, Object> appInternetUser = iXhpcRefundAuditService.getXhpcAppInternetUserById(Long.parseLong(userId), tenantId);
            if (StringUtils.isNull(appInternetUser)) {
                refundOrder.setStatus(2);
                refundOrder.setRemark("用户不存在");
                updateXhpcRefundOrder(refundOrder,amountRefundOrder,userId,phone,2,source,tenantId);
                return AjaxResult.error(HttpStatus.DATA_ERROR, "用户不存在");
            }
            String balance = StringUtils.valueOf(appInternetUser.get("balance"));
            BigDecimal surplus = BigDecimal.valueOf(Double.valueOf(balance)).subtract(amount);
            if (surplus.compareTo(BigDecimal.ZERO) == -1) {
                refundOrder.setStatus(2);
                refundOrder.setRemark("余额不足");
                updateXhpcRefundOrder(refundOrder,amountRefundOrder,userId,phone,2,source,tenantId);
                return AjaxResult.error(HttpStatus.ERROR_STATUS, "余额不足");
            }
        }else{
            return AjaxResult.error(HttpStatus.DATA_ERROR, "用户不存在");
        }
        try{

        }catch (Exception e){

        }
        TransferToUser client = new TransferToUser(
                xhpcSettingConfig.getWxMchId(),   // 商户号，是由微信支付系统生成并分配给每个商户的唯一标识符，商户号获取方式参考 https://pay.weixin.qq.com/doc/v3/merchant/4013070756
                "1DDE55AD98Exxxxxxxxxx",         // 商户API证书序列号，如何获取请参考 https://pay.weixin.qq.com/doc/v3/merchant/4013053053
                "/path/to/apiclient_key.pem",     // 商户API证书私钥文件路径，本地文件路径
                "PUB_KEY_ID_xxxxxxxxxxxxx",      // 微信支付公钥ID，如何获取请参考 https://pay.weixin.qq.com/doc/v3/merchant/4013038816
                "/path/to/wxp_pub.pem"           // 微信支付公钥文件路径，本地文件路径
        );



        return null;
    }

}
