package cn.iocoder.yudao.module.payment.controller;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.module.inspection.service.AppInspectionPartnerService;
import cn.iocoder.yudao.module.partner.entity.PartnerBankInfo;
import cn.iocoder.yudao.module.payment.entity.FzRecord;
import cn.iocoder.yudao.module.payment.entity.OrderInfo;
import cn.iocoder.yudao.module.payment.entity.OrderInfoDetail;
import cn.iocoder.yudao.module.payment.service.IFzRecordService;
import cn.iocoder.yudao.module.payment.service.IOrderInfoDetailService;
import cn.iocoder.yudao.module.payment.service.OrderInfoService;
import cn.iocoder.yudao.module.shop.entity.ShopConfig;
import cn.iocoder.yudao.module.shop.entity.ShopCoupon;
import cn.iocoder.yudao.module.shop.service.IShopConfigService;
import cn.iocoder.yudao.module.shop.service.IShopCouponService;
import cn.iocoder.yudao.module.shop.service.IUserBalanceService;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import cn.iocoder.yudao.util.WechatPayConfig;
import cn.iocoder.yudao.util.WechatPayRequest;
import cn.iocoder.yudao.util.WechatPayUrlEnum;
import cn.iocoder.yudao.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruoyi.partner.service.IPartnerBankInfoService;
import com.wechat.pay.contrib.apache.httpclient.util.AesUtil;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.service.payments.jsapi.JsapiService;
import com.wechat.pay.java.service.payments.jsapi.model.*;
import com.wechat.pay.java.service.profitsharing.ProfitsharingService;
import com.wechat.pay.java.service.profitsharing.model.CreateOrderReceiver;
import com.wechat.pay.java.service.profitsharing.model.CreateOrderRequest;
import com.wechat.pay.java.service.profitsharing.model.OrdersEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.util.*;
import java.util.concurrent.locks.ReentrantLock;


@RestController
@RequestMapping("/admin-api/payApi")
public class WxPayController {

    @Resource
    private WechatPayConfig wechatPayConfig;
    @Autowired
    private IShopCouponService shopCouponService;
    @Resource
    private WechatPayRequest wechatPayRequest;
    @Autowired
    private OrderInfoService orderInfoService;
    @Autowired
    private IPartnerBankInfoService partnerBankInfoService;
    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    private IShopConfigService configService;
    @Autowired
    private IOrderInfoDetailService orderInfoDetailService;
    @Autowired
    private IUserBalanceService userBalanceService;
    @Autowired
    private AppInspectionPartnerService partnerService;
    @Autowired
    private IFzRecordService fzRecordService;
    private final ReentrantLock lock = new ReentrantLock();

    /**
     * type：h5、jsapi、app、native、sub_jsapi
     * @param type
     * @return
     */

    @GetMapping("/prepayment")
    public Map<String,Object> transactions(String type,Long orderId) throws SignatureException, NoSuchAlgorithmException, InvalidKeyException, IOException {
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        AdminUserDO user = adminUserService.getUser(loginUser.getId());
        OrderInfo orderInfo = orderInfoService.getById(orderId);
        // 统一参数封装
        Map<String, Object> params = new HashMap<>(8);
        params.put("appid", wechatPayConfig.getJcAppId());
        params.put("mchid", wechatPayConfig.getMchId());
        params.put("description", orderInfo.getGoodsTitle());
        params.put("out_trade_no", orderInfo.getOrderNo());
        params.put("notify_url", wechatPayConfig.getJcNotifyUrl());
        Map<String, Object> amountMap = new HashMap<>(4);
        // 金额单位为分
        amountMap.put("total", orderInfo.getPayMoney());
        //人民币
        amountMap.put("currency", "CNY");
        params.put("amount", amountMap);

        // 场景信息
        Map<String, Object> sceneInfoMap = new HashMap<>(4);
        // 客户端IP
        sceneInfoMap.put("payer_client_ip", "127.0.0.1");
        // 商户端设备号（门店号或收银设备ID）
        sceneInfoMap.put("device_id", "127.0.0.1");
        // 除H5与JSAPI有特殊参数外，其他的支付方式都一样
        if (type.equals(WechatPayUrlEnum.H5.getType())) {
            Map<String, Object> h5InfoMap = new HashMap<>(4);
            // 场景类型:iOS, Android, Wap
            h5InfoMap.put("type", "IOS");
            sceneInfoMap.put("h5_info", h5InfoMap);
        } else if (type.equals(WechatPayUrlEnum.JSAPI.getType()) || type.equals(WechatPayUrlEnum.SUB_JSAPI.getType())) {
            Map<String, Object> payerMap = new HashMap<>(4);
            payerMap.put("openid", user.getOpenId());
            params.put("payer", payerMap);
        }
        params.put("scene_info", sceneInfoMap);
        String paramsStr = JSON.toJSONString(params);

        String resStr = wechatPayRequest.wechatHttpPost("https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi",paramsStr);
        Map<String, Object> resMap = JSONObject.parseObject(resStr);
        Map<String, Object> signMap = paySignMsg(resMap.get("prepay_id").toString(), wechatPayConfig.getAppId(),null);
        return signMap;
    }

    /**
     * type：h5、jsapi、app、native、sub_jsapi
     * @param type
     * @return
     */

    @GetMapping("/jcPrepayment2")
    public Map<String,Object> jcPrepayment2(String type,Long orderId) throws SignatureException, NoSuchAlgorithmException, InvalidKeyException, IOException {
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        AdminUserDO user = adminUserService.getUser(loginUser.getId());
        OrderInfo orderInfo = orderInfoService.getById(orderId);
        // 统一参数封装
        Map<String, Object> params = new HashMap<>(8);
        params.put("appid", wechatPayConfig.getJcAppId());
        params.put("mchid", wechatPayConfig.getMchId());
        params.put("description", orderInfo.getGoodsTitle());
        params.put("out_trade_no", orderInfo.getOrderNo());
        params.put("notify_url", wechatPayConfig.getJcNotifyUrl());
        Map<String, Object> amountMap = new HashMap<>(4);
        // 金额单位为分
        amountMap.put("total", orderInfo.getPayMoney());
        //人民币
        amountMap.put("currency", "CNY");
        params.put("amount", amountMap);

        // 场景信息
        Map<String, Object> sceneInfoMap = new HashMap<>(4);
        // 客户端IP
        sceneInfoMap.put("payer_client_ip", "127.0.0.1");
        // 商户端设备号（门店号或收银设备ID）
        sceneInfoMap.put("device_id", "127.0.0.1");
        // 除H5与JSAPI有特殊参数外，其他的支付方式都一样
        if (type.equals(WechatPayUrlEnum.H5.getType())) {
            Map<String, Object> h5InfoMap = new HashMap<>(4);
            // 场景类型:iOS, Android, Wap
            h5InfoMap.put("type", "IOS");
            sceneInfoMap.put("h5_info", h5InfoMap);
        } else if (type.equals(WechatPayUrlEnum.JSAPI.getType()) || type.equals(WechatPayUrlEnum.SUB_JSAPI.getType())) {
            Map<String, Object> payerMap = new HashMap<>(4);
            payerMap.put("openid", user.getJcOpenId());
            params.put("payer", payerMap);
        }
        params.put("scene_info", sceneInfoMap);
        String paramsStr = JSON.toJSONString(params);

        String resStr = wechatPayRequest.wechatHttpPost("https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi",paramsStr);
        Map<String, Object> resMap = JSONObject.parseObject(resStr);
        Map<String, Object> signMap = paySignMsg(resMap.get("prepay_id").toString(), wechatPayConfig.getAppId(),null);
        return signMap;
    }

    /**
     * type：h5、jsapi、app、native、sub_jsapi
     * @param type
     * @return
     */

    @GetMapping("/jcPrepayment")
    @TenantIgnore
    public Map<String,Object> jcPrepayment(String type,Long orderId) throws SignatureException, NoSuchAlgorithmException, InvalidKeyException, IOException {

        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        AdminUserDO user = adminUserService.getUser(loginUser.getId());
        OrderInfo orderInfo = orderInfoService.getById(orderId);
        LambdaQueryWrapper<PartnerBankInfo> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(PartnerBankInfo::getPartnerId,orderInfo.getPartnerId());
        PartnerBankInfo bankInfo = partnerBankInfoService.getOne(queryWrapper);

        String prepayId = this.toGetPayInfo(wechatPayConfig.getJcAppId(), bankInfo.getMchId(), bankInfo.getApiclientKey(), orderInfo.getPayMoney().intValue()
                , user.getJcOpenId(), bankInfo.getSerialNo(), bankInfo.getApiV3Key(), orderInfo.getGoodsTitle(),
                wechatPayConfig.getJcNotifyUrl(), orderInfo.getOrderNo());
        Map<String, Object> resMap = paySignMsg(prepayId, wechatPayConfig.getJcAppId(),bankInfo.getApiclientKey());
        return resMap;
    }
    private  Map<String, Object>  paySignMsg(String prepayId,String appId,String privateKeyStr) throws IOException, NoSuchAlgorithmException, InvalidKeyException, SignatureException {
        long timeMillis = System.currentTimeMillis();
        String timeStamp = timeMillis/1000+"";
        String nonceStr = timeMillis+"";
        String packageStr = "prepay_id="+prepayId;
        // 公共参数
        Map<String, Object> resMap = new HashMap<>();
        resMap.put("nonceStr",nonceStr);
        resMap.put("timeStamp",timeStamp);
        resMap.put("appId",appId);
        resMap.put("package", packageStr);
        // 使用字段appId、timeStamp、nonceStr、package进行签名
        //从下往上依次生成
        String message = buildMessage(appId, timeStamp, nonceStr, packageStr);
        //签名
        String paySign = sign(message.getBytes("utf-8"), privateKeyStr);
        resMap.put("paySign", paySign);
        resMap.put("signType", "RSA");
        return resMap;
    }


    String sign(byte[] message,String privateKeyStr) throws NoSuchAlgorithmException, SignatureException, IOException, InvalidKeyException {
        //签名方式
        Signature sign = Signature.getInstance("SHA256withRSA");
        //私钥，通过MyPrivateKey来获取，这是个静态类可以接调用方法 ，需要的是_key.pem文件的绝对路径配上文件名
        PrivateKey privateKey =null;
        if (StringUtils.isNotEmpty(privateKeyStr)){
             privateKey = PemUtil.loadPrivateKey(privateKeyStr);
        }else {
             privateKey =  wechatPayConfig.getPrivateKey(wechatPayConfig.getKeyPemPath());
        }

        sign.initSign(privateKey);
        sign.update(message);
        return Base64.getEncoder().encodeToString(sign.sign());
    }

    /**
     *  按照前端签名文档规范进行排序，\n是换行
     * @param timestamp
     * @param nonceStr
     * @param prepay_id
     * @return
     */
    String buildMessage(String appId, String timestamp,String nonceStr,String prepay_id) {

        return appId + "\n"
                + timestamp + "\n"
                + nonceStr + "\n"
                + prepay_id + "\n";
    }


    public String toGetPayInfo(String appId, String merchantId,String privateKey,Integer total,String openId,
                      String merchantSerialNumber,String apiV3Key,String title,String notifyUrl,String orderNo){
        Config config =
                new RSAAutoCertificateConfig.Builder()
                        .merchantId(merchantId)
                        .privateKey(privateKey)
                        .merchantSerialNumber(merchantSerialNumber)
                        .apiV3Key(apiV3Key)
                        .build();
        // 构建service
        JsapiService service = new JsapiService.Builder().config(config).build();
        // request.setXxx(val)设置所需参数，具体参数可见Request定义
        PrepayRequest request = new PrepayRequest();
        Amount amount = new Amount();
        amount.setTotal(total);
        amount.setCurrency("CNY");

        request.setAmount(amount);
        request.setAppid(appId);
        request.setMchid(merchantId);
        request.setDescription(title);
        request.setNotifyUrl(notifyUrl);
        request.setOutTradeNo(orderNo);
        Payer payer =new Payer();
        payer.setOpenid(openId);
        request.setPayer(payer);
        SettleInfo settleInfo =new SettleInfo();
        settleInfo.setProfitSharing(true);
        request.setSettleInfo(settleInfo);
        // 调用下单方法，得到应答
        PrepayResponse response = service.prepay(request);
        return response.getPrepayId();
    }


    @PostMapping("/payNotify")
    public Map<String, String> payNotify(@RequestBody JSONObject jsonObject) {
        String method = Thread.currentThread().getStackTrace()[1].getMethodName();

        try {
            String key = wechatPayConfig.getApiV3Key();
            String json = jsonObject.toString();
            String associated_data = (String) JSONUtil.getByPath(JSONUtil.parse(json), "resource.associated_data");
            String ciphertext = (String) JSONUtil.getByPath(JSONUtil.parse(json), "resource.ciphertext");
            String nonce = (String) JSONUtil.getByPath(JSONUtil.parse(json), "resource.nonce");

            String decryptData = new AesUtil(key.getBytes(StandardCharsets.UTF_8)).decryptToString(associated_data.getBytes(StandardCharsets.UTF_8), nonce.getBytes(StandardCharsets.UTF_8), ciphertext);
            //验签成功
            JSONObject decryptDataObj = JSONObject.parseObject(decryptData, JSONObject.class);
            if(lock.tryLock()) {
                try {
                    ShopConfig shopConfig = configService.selectShopConfigById(1L);
                    // 解密resource中的通知数据
                    String orderNo = decryptDataObj.get("out_trade_no").toString();
                    OrderInfo orderInfo = orderInfoService.getOrderByOrderNo(orderNo);
                    //追加订单明细记录
                    orderInfoDetailService.save(new OrderInfoDetail(orderInfo.getId(),"支付成功",new Date(),orderInfo.getPayMoney(),"0"));
                    JSONObject balanceObject =new JSONObject();
                    balanceObject.put("goodsType",orderInfo.getGoodsType());
                    balanceObject.put("goodsTitle",orderInfo.getGoodsTitle());
                    if (orderInfo.getOrderStatus().equals("0")){
                        orderInfo.setTransactionId(decryptDataObj.get("transaction_id").toString());
                        // 生成16位核销码 加到支付回调里
                        UUID uuid = UUID.randomUUID();
                        long mostSignificantBits = uuid.getMostSignificantBits();
                        long leastSignificantBits = uuid.getLeastSignificantBits();

                        String combinedBits = mostSignificantBits+ String.valueOf(leastSignificantBits);
                        String shortUuid = combinedBits.substring(combinedBits.length() - 16);
                        orderInfo.setAccessCode(shortUuid);
                        if (orderInfo.getGoodsType().equals("cz")){
                            balanceObject.put("silverNum", shopConfig.getShopUserSilver().longValue());
                            balanceObject.put("goldNum", shopConfig.getShopUserGold().longValue());
                            balanceObject.put("platinum", shopConfig.getShopUserPlatinum().longValue());
                            //积分充值的逻辑处理
                            orderInfo.setPayTime(new Date());
                            //状态直接值为 3  已完成  忽略  使用 评价的过程
                            orderInfo.setOrderStatus("3");
                            orderInfoService.updateById(orderInfo);
                            //处理 用户积分的变化
                            userBalanceService.addBalance(orderInfo.getPayMoney(),orderInfo.getUserId(),balanceObject);
                        }else if(orderInfo.getGoodsType().equals("jymd")){
                            //救援买单 忽略核销过程 直接修改为待评价
                            orderInfo.setPayTime(new Date());
                            orderInfo.setOrderStatus("2");
                            orderInfoService.updateById(orderInfo);
                            if (!ObjectUtil.isEmpty(orderInfo.getBalance())&&orderInfo.getBalance()>0){
                                //处理积分
                                userBalanceService.subtractFrozenBalance(orderInfo.getBalance(),orderInfo.getUserId(),balanceObject);
                            }
                        }else {
                            orderInfo.setPayTime(new Date());
                            orderInfo.setOrderStatus("1");
                            orderInfoService.updateById(orderInfo);
                            if (!ObjectUtil.isEmpty(orderInfo.getIsCoupon())&&orderInfo.getIsCoupon().equals("1")){
                                ShopCoupon shopCoupon = shopCouponService.selectShopCouponByCouponId(orderInfo.getCouponId());
                                //处理优惠卷
                                shopCoupon.setCouponStatus("1");
                                shopCoupon.setOrderId(orderInfo.getId());
                                shopCoupon.setUseTime(new Date());
                                shopCouponService.updateShopCoupon(shopCoupon);
                                orderInfo.setCouponId(shopCoupon.getCouponId());
                                orderInfo.setCouponDiscount(orderInfo.getCouponDiscount());
                            }
                            if (!ObjectUtil.isEmpty(orderInfo.getBalance())&&orderInfo.getBalance()>0){
                                //处理积分
                                userBalanceService.subtractFrozenBalance(orderInfo.getBalance(),orderInfo.getUserId(),balanceObject);
                            }
                            //店铺销量+1
                            if (orderInfo.getPartnerId()!=null){
                                partnerService.addSalesNum(orderInfo.getPartnerId());
                            }
                        }
                        //最后处理邀请人的积分奖励
                        AdminUserDO sysUser = adminUserService.getUser(orderInfo.getUserId());
                        if (ObjectUtil.isNotEmpty(sysUser.getInviteId())){
                            AdminUserDO inviteUser = adminUserService.getUser(sysUser.getInviteId());
                            userBalanceService.inviteSpend(inviteUser.getId(),orderInfo.getPayMoney());
                        }
                        //处理分账功能
                        if (ObjectUtil.isNotEmpty(shopConfig.getFzRatio())&&shopConfig.getFzRatio()>0d&&orderInfo.getSkuName().contains("环检")){
                            Timer timer = new Timer();
                            TimerTask task = new TimerTask() {
                                @Override
                                public void run() {
                                    LambdaQueryWrapper<PartnerBankInfo> queryWrapper =new LambdaQueryWrapper<>();
                                    queryWrapper.eq(PartnerBankInfo::getPartnerId,orderInfo.getPartnerId());
                                    PartnerBankInfo bankInfo = partnerBankInfoService.getOne(queryWrapper);
                                    profitsharing(wechatPayConfig.getAppId(),bankInfo.getMchId(),bankInfo.getApiclientKey(),3000L,
                                            bankInfo.getSerialNo(),bankInfo.getApiV3Key(),orderInfo.getOrderNo(),orderInfo.getTransactionId(),orderInfo.getPartnerId()
                                            ,orderInfo.getPartnerName(),orderInfo.getId(),orderInfo.getPayMoney());
                                }
                            };
                            long delay = 300 * 1000; // 一分钟后执行，单位是毫秒
                            timer.schedule(task, delay);
                        }
                    }
                } finally {
                    //要主动释放锁
                    lock.unlock();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        Map<String, String> res = new HashMap<>();
        res.put("code", "SUCCESS");
        res.put("message", "成功");
        return res;
    }

    @PostMapping("/profitsharing")
    void  profitsharing(String appId, String merchantId,String privateKey,Long amount,
                        String merchantSerialNumber,String apiV3Key,String orderNo,String transactionId
            ,Long partnerId,String partnerName,Long orderId,Long totalAmount){
        try {
            Config config =
                    new RSAAutoCertificateConfig.Builder()
                            .merchantId(merchantId)
                            .privateKey(privateKey)
                            .merchantSerialNumber(merchantSerialNumber)
                            .apiV3Key(apiV3Key)
                            .build();
            // 构建service
            ProfitsharingService service = new ProfitsharingService.Builder().config(config).build();
            CreateOrderRequest request =new  CreateOrderRequest();
            request.setAppid(appId);
            request.setTransactionId(transactionId);
            request.setOutOrderNo(orderNo);
            request.setUnfreezeUnsplit(true);
            List<CreateOrderReceiver> receivers =new ArrayList<>();
            CreateOrderReceiver receiver =new CreateOrderReceiver();
            receiver.setType("MERCHANT_ID");
            receiver.setAccount(wechatPayConfig.getMchId());
            receiver.setName("官方");
            receiver.setAmount(amount);
            receiver.setDescription("平台收取一定费用");
            receivers.add(receiver);
            request.setReceivers(receivers);
            OrdersEntity order = service.createOrder(request);
            FzRecord fzRecord =new FzRecord();
            fzRecord.setPartnerId(partnerId);
            fzRecord.setPartnerName(partnerName);
            fzRecord.setOrderId(orderId);
            fzRecord.setOrderNo(orderNo);
            fzRecord.setIsSuccess("1");
            fzRecord.setReason(JSONObject.toJSONString(order));
            fzRecord.setAmount(amount);
            fzRecord.setTotalAmount(totalAmount);
            fzRecordService.save(fzRecord);
        }catch (Exception e){
            FzRecord fzRecord =new FzRecord();
            fzRecord.setPartnerId(partnerId);
            fzRecord.setPartnerName(partnerName);
            fzRecord.setOrderId(orderId);
            fzRecord.setOrderNo(orderNo);
            fzRecord.setIsSuccess("0");
            fzRecord.setReason(e.getMessage());
            fzRecord.setAmount(amount);
            fzRecord.setTotalAmount(totalAmount);
            fzRecordService.save(fzRecord);
        }



    }

    @PostMapping("/refundNotify")
    public Map<String, String> refundNotify(@RequestBody JSONObject jsonObject) throws GeneralSecurityException, IOException {
        String key = wechatPayConfig.getApiV3Key();
        String json = jsonObject.toString();
        String associated_data = (String) JSONUtil.getByPath(JSONUtil.parse(json), "resource.associated_data");
        String ciphertext = (String) JSONUtil.getByPath(JSONUtil.parse(json), "resource.ciphertext");
        String nonce = (String) JSONUtil.getByPath(JSONUtil.parse(json), "resource.nonce");

        String decryptData = new AesUtil(key.getBytes(StandardCharsets.UTF_8)).decryptToString(associated_data.getBytes(StandardCharsets.UTF_8), nonce.getBytes(StandardCharsets.UTF_8), ciphertext);
        //验签成功
        JSONObject decryptDataObj = JSONObject.parseObject(decryptData, JSONObject.class);
        if(lock.tryLock()) {
            try {
                String orderNo = decryptDataObj.get("out_trade_no").toString();
                //根据订单编号进行退款处理
                OrderInfo orderInfo = orderInfoService.getOrderByOrderNo(orderNo);
                //追加订单明细记录
                orderInfoDetailService.save(new OrderInfoDetail(orderInfo.getId(),"退款成功",new Date(),orderInfo.getPayMoney(),"1"));
                if (orderInfo.getOrderStatus().equals("4")){
                    if (orderInfo.getIsCoupon().equals("1")){
                        //处理优惠卷
                        ShopCoupon shopCoupon = shopCouponService.selectShopCouponByCouponId(orderInfo.getCouponId());
                        shopCoupon.setCouponStatus("0");
                        shopCouponService.hfStatus(shopCoupon);
                    }
                    //申请退款的状态
                    //处理订单状态
                    orderInfo.setOrderStatus("5");
                    orderInfoService.updateById(orderInfo);
                    if (null!=orderInfo.getBalance()&&orderInfo.getBalance()>0){
                        //1处理积分
                        Long balance = orderInfo.getBalance();
                        JSONObject balanceObject =new JSONObject();
                        balanceObject.put("goodsType",orderInfo.getGoodsType());
                        balanceObject.put("goodsTitle",orderInfo.getGoodsTitle());
                        userBalanceService.refundBalance(orderInfo.getUserId(),balance,balanceObject);
                    }
                }
                //log.warn("=========== 根据订单号，做幂等处理 ===========");
            } finally {
                //要主动释放锁
                lock.unlock();
            }
        }
        //成功应答
        Map<String, String> res = new HashMap<>();
        res.put("code", "SUCCESS");
        res.put("message", "成功");
        return res;
    }

}
