package com.liquidnet.service.order.service.impl;

import com.liquidnet.common.third.sqb.biz.SqbBiz;
import com.liquidnet.common.third.sqb.param.callback.CouponCallbackContent;
import com.liquidnet.common.third.sqb.param.callback.OrderCallbackContent;
import com.liquidnet.common.third.sqb.param.callback.RefundCallbackContent;
import com.liquidnet.common.third.sqb.param.request.CashierQueryRequest;
import com.liquidnet.common.third.sqb.param.request.CommonRequest;
import com.liquidnet.common.third.sqb.param.request.CreateWechatPrepayOrderRequest;
import com.liquidnet.common.third.sqb.param.request.SettlementCreateRequest;
import com.liquidnet.common.third.sqb.param.response.data.*;
import com.liquidnet.commons.lang.util.IDGenerator;
import com.liquidnet.commons.lang.util.JsonUtils;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.goblin.constant.GoblinStatusConst;
import com.liquidnet.service.goblin.dto.manage.GoblinSqbOrderParam;
import com.liquidnet.service.goblin.dto.vo.*;
import com.liquidnet.service.goblin.service.IGoblinSqbOrderService;
import com.liquidnet.service.order.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
@Slf4j
public class GoblinSqbOrderServiceImpl implements IGoblinSqbOrderService {


    @Autowired
    private GoblinRedisUtils goblinRedisUtils;

    @Autowired
    private GoblinSqbRedisUtils goblinSqbRedisUtils;

    @Autowired
    private GoblinMongoUtils goblinMongoUtils;

    @Autowired
    private QueueUtils queueUtils;

    @Autowired
    private SqbBiz sqbBiz;

    private static final DateTimeFormatter DTF = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Autowired
    private GoblinSqbConvertUtils sqbConvertUtils;

    // ================================ 创建订单 ================================

    @Override
    public ResponseDto<GoblinSqbOrderCreateVo> createOrder(String userId, GoblinSqbOrderParam orderParam) {
        log.info("[收钱吧下单] 下单开始 userId={}, param: {}", userId, JsonUtils.toJson(orderParam));

        String skuId = orderParam.getSkuId();
        String spuId = orderParam.getSpuId();
        String performancesId = orderParam.getPerformancesId();
        Integer quantity = orderParam.getQuantity();

        // Step 1: 分布式锁防重
        boolean locked = goblinSqbRedisUtils.tryOrderLock(userId, skuId);
        if (!locked) {
            log.warn("[收钱吧下单] 获取防重锁失败，userId={}, skuId={}", userId, skuId);
            return ResponseDto.failure("请勿重复下单");
        }

        try {
            // Step 2: 校验演出-商品关联
            List<GoblinSqbPerfGoodsVo> perfGoods = goblinSqbRedisUtils.getPerfGoods(performancesId);
            if (perfGoods.isEmpty()) {
                log.error("[收钱吧下单] 演出关联商品列表为空，performancesId={}, skuId={}", performancesId, skuId);
                return ResponseDto.failure("商品与演出关联不存在");
            }

            boolean skuIdExists = false;
            for (GoblinSqbPerfGoodsVo perfGood : perfGoods) {
                for (MallProductsQueryData.Sku skuResult : perfGood.getSkuResults()) {
                    if (skuId.equals(skuResult.getSkuId())) {
                        skuIdExists = true;
                    }
                }
            }
            if (!skuIdExists) {
                log.error("[收钱吧下单] 演出-商品关联不存在或已禁用，performancesId={}, skuId={}", performancesId, skuId);
                return ResponseDto.failure("商品与演出关联不存在");
            }

            GoblinGoodsSkuInfoVo skuVo = goblinRedisUtils.getGoodsSkuInfoVo(skuId);
            if (skuVo == null) {
                log.error("[收钱吧下单] 未找到商品, skuId: {}, spuId: {}", skuId, spuId);
                return ResponseDto.failure("商品不存在");
            }
            if (!skuId.equals(skuVo.getSkuId())) {
                return ResponseDto.failure("下单失败");
            }
            if (!skuVo.getShelvesStatus().equals("3")) {
                log.info("[收钱吧下单] 商品已下架 skuId: {}, spuId: {}", skuId, spuId);
                return ResponseDto.failure("商品已下架");
            }

            // Step 3: 原子扣减库存
            int remaining = goblinRedisUtils.decrSkuStock(null, skuId, quantity);
            if (remaining < 0) {
                goblinRedisUtils.incrSkuStock(null, skuId, quantity);
                log.warn("[收钱吧下单] 库存不足，skuId={}, quantity={}", skuId, quantity);
                return ResponseDto.failure("库存不足");
            }
            log.info("[收钱吧下单] 扣减库存成功，skuId={}, 剩余库存={}", skuId, remaining);

            //TODO 获取该商品对应的商城的编号和密码
            Map<String, String> sqbInfoMap = sqbConvertUtils.getSqbInfoByzhengzaiSkuIdAndSpuId(skuId, spuId);

            SettlementCreateData settlementData = sqbBiz.createSettlement(
                    sqbInfoMap.get("mallSn"),
                    sqbInfoMap.get("signature"),
                    userId,
                    Collections.singletonList(buildSqbCheckOutItem(skuVo,
                            quantity, sqbInfoMap.get("sqbSkuId"), sqbInfoMap.get("sqbSpuId"))));
            if (settlementData == null) {
                goblinRedisUtils.incrSkuStock(null, skuId, quantity);
                return ResponseDto.failure("创建结算明细失败");
            }
            final String checkoutItemsId = settlementData.getCheckoutItemsId();
            log.info("[收钱吧下单] 创建结算明细成功，checkoutItemsId={}", checkoutItemsId);

            // Step 4.2: createOrder → 得 sqbOrderSn + sqbOrderSignature + sqbAcquiringSn
            String goodsName = skuVo.getName();
            OrderCreateData orderData = sqbBiz.createOrder(
                    sqbInfoMap.get("mallSn"),
                    sqbInfoMap.get("signature"),
                    checkoutItemsId,
                    userId,
                    buildRequestId(IDGenerator.nextSnowId()),
                    buildTitle(goodsName)
            );
            if (orderData == null) {
                goblinRedisUtils.incrSkuStock(null, skuId, quantity);
                return ResponseDto.failure("创建收钱吧订单失败");
            }
            String sqbOrderSn = orderData.getOrderSn(); // 订单编号
            String sqbOrderSignature = orderData.getOrderSignature(); // 订单密钥
            String sqbAcquiringSn = orderData.getAcquiring() != null ? orderData.getAcquiring().getAcquiringSn() : null; // 收单号
            String sqbAcquiringSign = orderData.getAcquiring() != null ? orderData.getAcquiring().getSignature() : null; // 收单密钥
            log.info("[收钱吧下单] 创建订单成功，订单编号={}, 收单号={}", sqbOrderSn, sqbAcquiringSn);

            // Step 4.3: queryCashier → 得 selectedSignature + seq
            CashierQueryData cashierData = sqbBiz.queryCashier(sqbAcquiringSn, sqbAcquiringSign, userId);
            if (cashierData == null) {
                goblinRedisUtils.incrSkuStock(null, skuId, quantity);
                return ResponseDto.failure("查询收银台失败");
            }

            String selectedSignature = cashierData.getSelectedSignature(); // 支付工具签名
            String seq = cashierData.getSeq(); // 响应唯一序列号
            log.info("[收钱吧下单] 查询收银台成功，selectedSignature={}, seq={}", selectedSignature, seq);

            CreateWechatPrepayOrderData prepayData = sqbBiz.createWechatPrepayOrder(sqbAcquiringSn,
                    sqbAcquiringSign,
                    userId,
                    String.valueOf(cashierData.getAmount()),
                    buildRequestId(IDGenerator.nextSnowId()),
                    cashierData.getPayTools().get(0),
                    new HashMap<String, Object>(), // TODO 设置AppID
                    selectedSignature,
                    seq
            );

            if (prepayData == null || prepayData.getPaymentVoucher() == null) {
                goblinRedisUtils.incrSkuStock(null, skuId, quantity);
                return ResponseDto.failure("创建微信预支付失败");
            }
            CreateWechatPrepayOrderData.PaymentVoucher pv = prepayData.getPaymentVoucher();
            log.info("[收钱吧下单] 创建微信预支付订单成功，timeStamp={}", pv.getTimeStamp());

            String orderId = IDGenerator.nextSnowId();
            String masterOrderCode = IDGenerator.nextTimeId();
            String orderCode = IDGenerator.nextTimeId();
            String now = LocalDateTime.now().format(DTF);

            // 获取商品和 SKU 信息，供后续订单基础信息拼接使用
            GoblinGoodsInfoVo goodsInfo = goblinMongoUtils.getGoodsInfoVo(spuId);
            GoblinGoodsSkuInfoVo skuInfo = goblinMongoUtils.getGoodsSkuInfoVo(skuId);

            // 1) 构建基础商城订单 VO (GoblinStoreOrderVo)
            GoblinStoreOrderVo storeOrderVo = new GoblinStoreOrderVo();
            storeOrderVo.setMasterOrderCode(masterOrderCode);
            storeOrderVo.setOrderId(orderId);
            storeOrderVo.setStoreId(goodsInfo != null ? goodsInfo.getStoreId() : "SQB_STORE");
            storeOrderVo.setStoreName(goodsInfo != null ? goodsInfo.getStoreName() : "收钱吧商品聚合门店");
            storeOrderVo.setOrderCode(orderCode);
            storeOrderVo.setUserId(userId);
            // 姓名手机号为了兼容留空或占位即可
            storeOrderVo.setUserName("");
            storeOrderVo.setUserMobile("");

            BigDecimal skuPrice = skuInfo != null ? skuInfo.getPrice() : BigDecimal.ZERO;
            BigDecimal priceTotal = skuPrice.multiply(new BigDecimal(quantity));
            storeOrderVo.setPriceTotal(priceTotal);
            storeOrderVo.setPriceActual(priceTotal); // 收钱吧暂无运费及优惠逻辑，实际价格等于总价
            storeOrderVo.setPriceRefund(BigDecimal.ZERO);
            storeOrderVo.setPriceExpress(BigDecimal.ZERO);
            storeOrderVo.setPriceCoupon(BigDecimal.ZERO);
            storeOrderVo.setStorePriceCoupon(BigDecimal.ZERO);
            storeOrderVo.setPriceVoucher(BigDecimal.ZERO);
            // 待支付
            storeOrderVo.setStatus(0);
            storeOrderVo.setPayType("SQB_PAY"); // 标识为收钱吧支付类型
            storeOrderVo.setDeviceFrom("shouqianba");
            storeOrderVo.setOrderType(0);
            storeOrderVo.setWriteOffCode("EMPTY");
            storeOrderVo.setPayCountdownMinute(15);
            storeOrderVo.setCreatedAt(now);

            // 2) 构建基础商城 SKU VO (GoblinOrderSkuVo)
            String orderSkuId = IDGenerator.nextSnowId();
            GoblinOrderSkuVo orderSkuVo = new GoblinOrderSkuVo();
            orderSkuVo.setOrderSkuId(orderSkuId);
            orderSkuVo.setOrderId(orderId);
            orderSkuVo.setSpuId(spuId);
            orderSkuVo.setSpuName(goodsInfo != null ? goodsInfo.getName() : "收钱吧未知商品");
            orderSkuVo.setSkuId(skuId);
            orderSkuVo.setNum(quantity);
            orderSkuVo.setSkuPrice(skuPrice);
            orderSkuVo.setSkuPriceActual(priceTotal); // 按件数总价
            orderSkuVo.setSkuName(skuInfo != null ? skuInfo.getName() : "收钱吧未匹配SKU");
            orderSkuVo.setSkuImage(skuInfo != null ? skuInfo.getSkuPic() : "");
            orderSkuVo.setSkuSpecs("[]");
            orderSkuVo.setPriceVoucher(BigDecimal.ZERO);
            orderSkuVo.setCreatedAt(now);
            // 特殊标识类型：33
            orderSkuVo.setSkuType(33);

            // 存入 Redis 并绑定关系
            List<String> orderSkuVoIds = new ArrayList<>();
            orderSkuVoIds.add(orderSkuId);
            storeOrderVo.setOrderSkuVoIds(orderSkuVoIds);
            goblinRedisUtils.setGoblinOrderSku(orderSkuId, orderSkuVo);
            goblinRedisUtils.setGoblinOrder(orderId, storeOrderVo);
            goblinRedisUtils.setMasterCode(masterOrderCode, orderId);

            // 3) 构建收钱吧专属特有字段 (GoblinSqbOrderVo)
            GoblinSqbOrderVo orderVo = new GoblinSqbOrderVo();
            orderVo.setOrderId(orderId);
            orderVo.setUserId(userId);
            orderVo.setPerformancesId(performancesId);
            orderVo.setSpuId(spuId);
            orderVo.setSkuId(skuId);
            orderVo.setQuantity(quantity);
            orderVo.setAmount(sqbConvertUtils.yuanToFen(priceTotal));
            orderVo.setSqbOrderSn(sqbOrderSn);
            orderVo.setSqbOrderSignature(sqbOrderSignature);
            orderVo.setSqbAcquiringSn(sqbAcquiringSn);
            orderVo.setSqbAcquiringSign(sqbAcquiringSign);
            orderVo.setSqbCheckoutItemsId(checkoutItemsId);
            orderVo.setRefundReason("");
            // 内部状态同步使用
            orderVo.setStatus(0);
            orderVo.setCreatedAt(now);
            orderVo.setUpdatedAt(now);

            goblinSqbRedisUtils.setSqbOrder(orderId, orderVo);
            goblinSqbRedisUtils.addSqbOrderList(userId, orderId);
            log.info("[收钱吧下单] 订单写入 Redis 成功，orderId={}", orderId);

            // Step 6: 写 MongoDB + 发送复用的 SQL MQ
            // 写入 Mongo
            goblinMongoUtils.insertGoblinOrderSkuVo(orderSkuVo);
            goblinMongoUtils.insertGoblinStoreOrderVo(storeOrderVo);
            // 收钱吧扩展暂无需单独写 MongoDB 除非专门需要查询

            // 拼接 SQL 数据并丢队列
            LinkedList<String> sqls = new LinkedList<>();
            sqls.add(com.liquidnet.service.base.SqlMapping.get("goblin.order.create.sku_insert"));
            sqls.add(com.liquidnet.service.base.SqlMapping.get("goblin.order.create.order_insert"));
            sqls.add(com.liquidnet.service.base.SqlMapping.get("goblin_sqb_order.insert"));

            LinkedList<Object[]> sqlDataSku = new LinkedList<>();
            sqlDataSku.add(new Object[]{
                    orderSkuVo.getOrderSkuId(), orderSkuVo.getOrderId(), orderSkuVo.getSpuId(), orderSkuVo.getSpuName(), (goodsInfo != null ? goodsInfo.getCoverPic() : ""),
                    orderSkuVo.getSkuId(), orderSkuVo.getNum(), orderSkuVo.getSkuPrice(), orderSkuVo.getSkuPriceActual(), orderSkuVo.getSkuName(),
                    "", orderSkuVo.getSkuImage(), orderSkuVo.getSkuSpecs(), orderSkuVo.getPriceVoucher(),
                    "", "", "", "", 0, // ERP 等非必要参数直接置空
                    orderSkuVo.getCreatedAt()
            });

            LinkedList<Object[]> sqlDataOrder = new LinkedList<>();
            sqlDataOrder.add(new Object[]{
                    storeOrderVo.getMasterOrderCode(), storeOrderVo.getOrderId(), storeOrderVo.getStoreId(), storeOrderVo.getStoreName(), storeOrderVo.getOrderCode(),
                    storeOrderVo.getUserId(), storeOrderVo.getUserName(), storeOrderVo.getUserMobile(), storeOrderVo.getPriceTotal(), storeOrderVo.getPayCode(),
                    storeOrderVo.getPriceActual(), storeOrderVo.getPriceRefund(), storeOrderVo.getPriceExpress(), storeOrderVo.getPriceCoupon(), storeOrderVo.getStorePriceCoupon(),
                    storeOrderVo.getPriceVoucher(), storeOrderVo.getStatus(), storeOrderVo.getUcouponId(), storeOrderVo.getStoreCouponId(), storeOrderVo.getPayType(), storeOrderVo.getDeviceFrom(),
                    storeOrderVo.getSource(), storeOrderVo.getVersion(), storeOrderVo.getIsMember(), storeOrderVo.getOrderType(), storeOrderVo.getWriteOffCode(), storeOrderVo.getPayCountdownMinute(),
                    storeOrderVo.getIpAddress(), storeOrderVo.getMarketId(), storeOrderVo.getMarketType(), storeOrderVo.getCreatedAt(), "", ""
            });

            // 收钱吧订单扩展表写库数据
            // order_id, user_id, performances_id, spu_id, sku_id, quantity, amount(分),
            // sqb_order_sn, sqb_order_signature, sqb_acquiring_sn, sqb_checkout_items_id, status, created_at, updated_at
            LinkedList<Object[]> sqlDataSqbOrder = new LinkedList<>();
            sqlDataSqbOrder.add(new Object[]{
                    orderId, userId, performancesId, spuId, skuId, quantity,
                    sqbConvertUtils.yuanToFen(priceTotal),
                    sqbOrderSn, sqbOrderSignature, sqbAcquiringSn, sqbAcquiringSign, checkoutItemsId,
                    0, now, now
            });

            // 借用 Base 模块中 ConsumerGoblinOrderCPRdsReceiver 这个队列消费类进行写库
            if (queueUtils != null) {
                queueUtils.sendMsgByRedis(com.liquidnet.service.base.constant.MQConst.GoblinQueue.GOBLIN_ORDER_CREATE_PAY.getKey(),
                        com.liquidnet.service.base.SqlMapping.gets(sqls, sqlDataSku, sqlDataOrder, sqlDataSqbOrder));
                // 待支付超时回调等处理也可放入原有股票队列逻辑，暂省略
            }
            log.info("[收钱吧下单] 完成 MongoDB 及 MQ 落库，orderId={}, masterCode={}", orderId, masterOrderCode);

            // Step 7: 释放分布式锁，构建返回
            goblinSqbRedisUtils.releaseOrderLock(userId, skuId);

            GoblinSqbOrderCreateVo createVo = new GoblinSqbOrderCreateVo();
            createVo.setOrderId(orderId);
            createVo.setAcquiringSn(sqbAcquiringSn);
            createVo.setTimeStamp(pv.getTimeStamp());
            createVo.setPackageStr(pv.getPackageStr());
            createVo.setPaySign(pv.getPaySign());
            createVo.setAppId(pv.getAppId());
            createVo.setSignType(pv.getSignType());
            createVo.setNonceStr(pv.getNonceStr());

            log.info("[收钱吧下单] 下单成功，orderId={}", orderId);
            return ResponseDto.success(createVo);

        } catch (Exception e) {
            log.error("[收钱吧下单] 下单异常，userId={}, skuId={}", userId, skuId, e);
            goblinRedisUtils.incrSkuStock(null, skuId, quantity);
            return ResponseDto.failure("下单失败");
        } finally {
            goblinSqbRedisUtils.releaseOrderLock(userId, skuId);
        }
    }

    /**
     * 构建收钱吧-结算明细条目
     *
     * @param skuVo
     * @param quantity
     * @param sqbSkuId
     * @param sqbSpuId
     * @return
     */
    private SettlementCreateRequest.CheckoutItem buildSqbCheckOutItem(GoblinGoodsSkuInfoVo skuVo,
                                                                      Integer quantity,
                                                                      String sqbSkuId,
                                                                      String sqbSpuId) {
        // 获取商品与收钱吧商品对应的关联的skuId、spuId
        SettlementCreateRequest.CheckoutItem checkoutItem = new SettlementCreateRequest.CheckoutItem();
        checkoutItem.setSpuId(sqbSpuId);
        checkoutItem.setSkuId(sqbSkuId);
        checkoutItem.setPrice(sqbConvertUtils.yuanToFen(skuVo.getPrice()));
        checkoutItem.setQuantity(String.valueOf(quantity));
        checkoutItem.setType((byte) 0);
        checkoutItem.setTitle(skuVo.getName());
        checkoutItem.setImage(skuVo.getSkuPic());
        return checkoutItem;
    }

    // ================================ 查询支付状态 ================================

    @Override
    public ResponseDto<Integer> queryPayStatus(String userId, String orderId) {
        log.info("[收钱吧支付状态] 开始查询 userId={}, orderId={}", userId, orderId);

        GoblinSqbOrderVo orderVo = goblinSqbRedisUtils.getSqbOrder(orderId);
        if (orderVo == null) {
            return ResponseDto.failure("订单不存在");
        }
        if (!userId.equals(orderVo.getUserId())) {
            return ResponseDto.failure("无权限访问该订单");
        }
        return ResponseDto.success(orderVo.getStatus());
    }


    // ================================ 回调处理 ================================

    @Override
    public ResponseDto<String> handlePayCallback(OrderCallbackContent orderCallbackContent) {
        log.info("[收钱吧支付回调] 收到回调参数: {}", orderCallbackContent);
        // TODO 可能需要根据收钱吧的orderSn查询正在的orderId
        String sqbOrderSn = orderCallbackContent.getOrderSn();
        if (sqbOrderSn == null) return ResponseDto.failure("缺少订单标识");

        String orderId = "";

        GoblinSqbOrderVo orderVo = goblinSqbRedisUtils.getSqbOrder(orderId);
        if (orderVo == null) return ResponseDto.failure("订单不存在");
        if (Integer.valueOf(1).equals(orderVo.getStatus())) return ResponseDto.success("success"); // 幂等

        String now = LocalDateTime.now().format(DTF);
        orderVo.setStatus(1);
        orderVo.setUpdatedAt(now);
        goblinSqbRedisUtils.setSqbOrder(orderId, orderVo);
        syncOrderStatus(orderId, 1);
        log.info("[收钱吧支付回调] 更新支付状态成功，orderId={}", orderId);
        return ResponseDto.success("success");
    }

    @Override
    public ResponseDto<String> handleRefundCallback(RefundCallbackContent refundCallbackContent) {
        log.info("[收钱吧退款回调] 收到回调参数: {}", refundCallbackContent);
        // TODO 可能需要根据收钱吧的orderSn查询正在的orderId
        String orderId = refundCallbackContent.getOrderSn();
        if (orderId == null) return ResponseDto.failure("缺少订单标识");

        GoblinSqbOrderVo orderVo = goblinSqbRedisUtils.getSqbOrder(orderId);
        if (orderVo == null) return ResponseDto.failure("订单不存在");
        if (Integer.valueOf(3).equals(orderVo.getStatus())) return ResponseDto.success("success"); // 幂等

        String now = LocalDateTime.now().format(DTF);
        orderVo.setStatus(3);
        orderVo.setUpdatedAt(now);
        goblinSqbRedisUtils.setSqbOrder(orderId, orderVo);
        goblinRedisUtils.incrSkuStock(null, orderVo.getSkuId(), orderVo.getQuantity());
        syncOrderStatus(orderId, 3);
        log.info("[收钱吧退款回调] 更新退款状态成功，orderId={}", orderId);
        return ResponseDto.success("success");
    }

    @Override
    public ResponseDto<String> handleCouponCallback(CouponCallbackContent callbackContent) {
        log.info("[收钱吧券状态回调] 收到回调参数: {}", callbackContent);
        // TODO 可能需要根据收钱吧的orderSn查询正在的orderId
        String orderId = callbackContent.getOrderSn();
        if (orderId == null) return ResponseDto.failure("缺少订单标识");

        GoblinSqbOrderVo orderVo = goblinSqbRedisUtils.getSqbOrder(orderId);
        if (orderVo == null) return ResponseDto.failure("订单不存在");
        if (Integer.valueOf(2).equals(orderVo.getStatus())) return ResponseDto.success("success"); // 幂等

        String now = LocalDateTime.now().format(DTF);
        orderVo.setStatus(2);
        orderVo.setCouponUsedStatus(1);
        orderVo.setUpdatedAt(now);
        goblinSqbRedisUtils.setSqbOrder(orderId, orderVo);
        syncOrderStatus(orderId, 2);
        log.info("[收钱吧券状态回调] 核销状态更新成功，orderId={}", orderId);
        return ResponseDto.success("success");
    }

    // ================================ 再次付款 ================================

    @Override
    public ResponseDto<GoblinSqbOrderCreateVo> repay(String userId, String orderId) {
        log.info("[收钱吧再次付款] userId={}, orderId={}", userId, orderId);

        GoblinSqbOrderVo orderVo = goblinSqbRedisUtils.getSqbOrder(orderId);
        if (orderVo == null) return ResponseDto.failure("订单不存在");
        if (!userId.equals(orderVo.getUserId())) return ResponseDto.failure("无权限访问该订单");
        if (!Integer.valueOf(0).equals(orderVo.getStatus())) {
            return ResponseDto.failure("订单状态不支持再次付款（仅待支付状态可重新拉起）");
        }
        if (orderVo.getSqbAcquiringSn() == null) {
            return ResponseDto.failure("订单数据异常，缺少收单号");
        }

        try {
            // 重新查询收银台，获取新的 selectedSignature + seq
            CashierQueryData cashierData = sqbBiz.queryCashier(orderVo.getSqbAcquiringSn(), orderVo.getSqbOrderSignature(), userId);
            if (cashierData == null) return ResponseDto.failure("查询收银台失败，请稍后重试");

            // 重新创建微信预支付
            CreateWechatPrepayOrderData prepayData = sqbBiz.createWechatPrepayOrder(
                    orderVo.getSqbAcquiringSn(),
                    orderVo.getSqbAcquiringSign(),
                    userId,
                    String.valueOf(cashierData.getAmount()),
                    buildRequestId(IDGenerator.nextSnowId()),
                    cashierData.getPayTools().get(0),
                    new HashMap<String, Object>(), // TODO 需要填写appID
                    cashierData.getSelectedSignature(),
                    cashierData.getSeq()
            );
            if (prepayData == null || prepayData.getPaymentVoucher() == null) {
                return ResponseDto.failure("创建微信预支付失败，请稍后重试");
            }

            CreateWechatPrepayOrderData.PaymentVoucher pv = prepayData.getPaymentVoucher();
            GoblinSqbOrderCreateVo createVo = new GoblinSqbOrderCreateVo();
            createVo.setOrderId(orderId);
            createVo.setAcquiringSn(orderVo.getSqbAcquiringSn());
            createVo.setTimeStamp(pv.getTimeStamp());
            createVo.setPackageStr(pv.getPackageStr());
            createVo.setPaySign(pv.getPaySign());
            createVo.setAppId(pv.getAppId());
            createVo.setSignType(pv.getSignType());
            createVo.setNonceStr(pv.getNonceStr());

            log.info("[收钱吧再次付款] 成功，orderId={}", orderId);
            return ResponseDto.success(createVo);

        } catch (Exception e) {
            log.error("[收钱吧再次付款] 异常，orderId={}", orderId, e);
            return ResponseDto.failure("再次付款失败：" + e.getMessage());
        }
    }

    // ================================ 私有辅助方法 ================================

    private CommonRequest.Seller buildSeller() {
        CommonRequest.Seller seller = new CommonRequest.Seller();
        seller.setMerchantId(sqbBiz.getSqbConfig().getMerchantId());
        seller.setMerchantUserId(sqbBiz.getSqbConfig().getMerchantUserId());
        seller.setRole(sqbBiz.getSqbConfig().getRole());
        return seller;
    }

    private CashierQueryRequest buildCashierQueryRequest(CommonRequest.Seller seller,
                                                         String acquiringSn,
                                                         String acquiringSignature) {
        CashierQueryRequest req = new CashierQueryRequest();
        req.setAppid(sqbBiz.getSqbConfig().getAppId());
        req.setSeller(seller);
        req.setPaymentMode(4); // 4-微信小程序支付

        CashierQueryRequest.PaymentEnv paymentEnv = new CashierQueryRequest.PaymentEnv();
        paymentEnv.setClient("wechat");
        req.setPaymentEnv(paymentEnv);

        CommonRequest.Acquiring acquiring = new CommonRequest.Acquiring();
        acquiring.setAcquiringSn(acquiringSn);
        acquiring.setSignature(acquiringSignature);
        req.setAcquiringInfo(acquiring);
        return req;
    }

    private CreateWechatPrepayOrderRequest buildWechatPrepayRequest(CommonRequest.Seller seller,
                                                                    String acquiringSn,
                                                                    String acquiringSignature,
                                                                    String selectedSignature,
                                                                    String seq,
                                                                    CashierQueryData cashierData) {
        CreateWechatPrepayOrderRequest req = new CreateWechatPrepayOrderRequest();
        req.setAppid(sqbBiz.getSqbConfig().getAppId());
        req.setSeller(seller);
        req.setAcquiringSn(acquiringSn);
        req.setSignature(acquiringSignature);
        req.setSelectedSignature(selectedSignature);
        req.setSeq(seq);

        // 使用收银台返回的第一个可用支付工具
        if (cashierData != null && !CollectionUtils.isEmpty(cashierData.getPayTools())) {
            List<CreateWechatPrepayOrderRequest.UsingPayTool> usingPayTools = new ArrayList<>();
            cashierData.getPayTools().stream()
                    .filter(t -> Boolean.TRUE.equals(t.getSelectable()))
                    .findFirst()
                    .ifPresent(payTool -> {
                        CreateWechatPrepayOrderRequest.UsingPayTool usingTool = new CreateWechatPrepayOrderRequest.UsingPayTool();
                        usingTool.setId(payTool.getId());
                        usingTool.setPayTool(payTool.getType());
                        usingTool.setPayMode(4);
                        usingTool.setAmount(payTool.getShowAmount() != null ? String.valueOf(payTool.getShowAmount()) : "0");
                        usingTool.setIdentity("wzwl");
                        usingTool.setRequestSn(IDGenerator.nextSnowId());
                        usingPayTools.add(usingTool);
                    });
            req.setUsingPayTools(usingPayTools);
        }
        return req;
    }


    /**
     * 构建收钱吧请求唯一ID，规则：AppCode（4位）+ id，总长不超过40位。
     *
     * @param id 业务唯一标识（如雪花ID）
     * @return 不超过40位的请求ID字符串
     */
    private String buildRequestId(String id) {
        String appCode = sqbBiz.getSqbConfig().getAppCode();
        if (appCode == null) appCode = "";
        String raw = appCode + id;
        return raw.length() > 40 ? raw.substring(0, 40) : raw;
    }

    /**
     * 构建收钱吧订单标题，不超过32位。
     *
     * @param name 商品名称
     * @return 不超过32位的标题字符串
     */
    private String buildTitle(String name) {
        if (name == null || name.isEmpty()) return "商品支付";
        return name.length() > 32 ? name.substring(0, 32) : name;
    }


    private void syncOrderStatus(String orderId, int status) {
        final int zhengzaiStatus = sqbOrderStatusConvert(status);

        GoblinStoreOrderVo storeOrderVo = goblinRedisUtils.getGoblinOrder(orderId);
        if (storeOrderVo == null) return;

        String now = LocalDateTime.now().format(DTF);
        storeOrderVo.setStatus(zhengzaiStatus);
        if (zhengzaiStatus == GoblinStatusConst.Status.ORDER_STATUS_2.getValue()) { // 支付成功
            storeOrderVo.setPayTime(now);
        }

        // 1. 同步 Redis
        goblinRedisUtils.setGoblinOrder(orderId, storeOrderVo);

        // 2. 同步 MongoDB
        goblinMongoUtils.updateGoblinStoreOrderVo(orderId, storeOrderVo);

        // 3. 同步 MySQL (复用下单 MQ 发送 Update 语句)
        String sql;
        Object[] data;
        if (zhengzaiStatus == GoblinStatusConst.Status.ORDER_STATUS_2.getValue()) {
            sql = "UPDATE goblin_store_order SET status = ?, pay_time = ?, updated_at = ? WHERE order_id = ?";
            data = new Object[]{zhengzaiStatus, storeOrderVo.getPayTime(), now, orderId};
        } else {
            sql = "UPDATE goblin_store_order SET status = ?, updated_at = ? WHERE order_id = ?";
            data = new Object[]{zhengzaiStatus, now, orderId};
        }

        java.util.LinkedList<String> sqls = new java.util.LinkedList<>();
        sqls.add(sql);
        java.util.LinkedList<Object[]> sqlData = new java.util.LinkedList<>();
        sqlData.add(data);

        if (queueUtils != null) {
            queueUtils.sendMsgByRedis(com.liquidnet.service.base.constant.MQConst.GoblinQueue.GOBLIN_ORDER_CREATE_PAY.getKey(),
                    com.liquidnet.service.base.SqlMapping.gets(sqls, sqlData));
        }
    }


    /**
     * goblin_sqb_order表status 转换成 goblin_store_order表对应status
     *
     * @param sqbOrderStatus
     * @return
     */
    private int sqbOrderStatusConvert(Integer sqbOrderStatus) {
        if (null == sqbOrderStatus) {
            return -1;
        }
        switch (sqbOrderStatus) {
            case 0:
                // 0-待支付 -> 对应枚举 ORDER_STATUS_0
                return GoblinStatusConst.Status.ORDER_STATUS_0.getValue();

            case 1:
                // 1-已支付 -> 对应枚举 ORDER_STATUS_2 (代发货)
                return GoblinStatusConst.Status.ORDER_STATUS_2.getValue();

            case 2:
                // 2-已核销 -> 对应枚举 ORDER_STATUS_4 (已完成)
                return GoblinStatusConst.Status.ORDER_STATUS_4.getValue();

            case 3:
                // 3-已退款 -> 对应枚举 ORDER_STATUS_6 (退款通过)
                return GoblinStatusConst.Status.ORDER_STATUS_6.getValue();

            case 4:
                // 4-退款中 -> 对应枚举 ORDER_STATUS_61 (发起-退款)
                return GoblinStatusConst.Status.ORDER_STATUS_61.getValue();

            case 5:
                // 5-已取消 -> 对应枚举 ORDER_STATUS_5
                return GoblinStatusConst.Status.ORDER_STATUS_5.getValue();

            case 9:
                // 9-失败 -> 这里归类为 ORDER_STATUS_5 (取消/终态)，如有特殊需求可调整
                return sqbOrderStatus;
            default:
                return sqbOrderStatus;
        }
    }
}
