package com.gxwebsoft.shop.service;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.gxwebsoft.common.core.exception.BusinessException;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.shop.config.OrderConfigProperties;
import com.gxwebsoft.shop.dto.OrderCreateRequest;
import com.gxwebsoft.shop.entity.*;
import com.gxwebsoft.shop.service.ShopStoreFenceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 订单业务服务类
 * 处理订单创建的核心业务逻辑
 *
 * @author 科技小王子
 * @since 2025-01-26
 */
@Slf4j
@Service
public class OrderBusinessService {
    private static final int DEDUCT_STOCK_TYPE_ORDER = 10; // 下单减库存
    private static final int DEDUCT_STOCK_TYPE_PAY = 20;   // 付款减库存

    @Resource
    private ShopOrderService shopOrderService;

    @Resource
    private ShopOrderGoodsService shopOrderGoodsService;

    @Resource
    private ShopGoodsService shopGoodsService;

    @Resource
    private ShopGoodsSkuService shopGoodsSkuService;

    @Resource
    private OrderConfigProperties orderConfig;

    @Resource
    private ShopUserAddressService shopUserAddressService;
    @Resource
    private ShopUserCouponService shopUserCouponService;
    @Resource
    private ShopStoreFenceService shopStoreFenceService;
    @Resource
    private WxSubscribeMessageService wxSubscribeMessageService;

    /**
     * 创建订单
     *
     * @param request   订单创建请求
     * @param loginUser 当前登录用户
     * @return 微信支付订单信息
     */
    @Transactional(rollbackFor = Exception.class)
    public Map<String, String> createOrder(OrderCreateRequest request, User loginUser) {

        // 1. 参数校验
        validateOrderRequest(request, loginUser);

        // 2. 构建订单对象
        ShopOrder shopOrder = buildShopOrder(request, loginUser);

        // 3. 处理收货地址信息
        processDeliveryAddress(shopOrder, request, loginUser);

        // 3.1 下单时校验配送范围（电子围栏）
        validateDeliveryFenceIfNeeded(shopOrder, loginUser);

        // 4. 应用业务规则
        applyBusinessRules(shopOrder, loginUser);

        // 如果商品仅有一个则更新formId
        if (request.getGoodsItems().size() == 1) {
            shopOrder.setFormId(request.getGoodsItems().get(0).getGoodsId());
        }

        // 5. 保存订单
        boolean saved = shopOrderService.save(shopOrder);
        if (!saved) {
            throw new BusinessException("订单保存失败");
        }

        // 6. 保存订单商品
        saveOrderGoods(request, shopOrder);

        // 7. 标记优惠券为已使用
        if (shopOrder.getCouponId() != null && shopOrder.getCouponId() > 0) {
            markCouponAsUsed(shopOrder.getCouponId(), shopOrder.getOrderId());
        }

        // 7.1 推送新订单通知给门店店员（异步发送，失败不影响主流程）
        try {
            wxSubscribeMessageService.sendNewOrderNotification(shopOrder);
        } catch (Exception e) {
            log.warn("发送新订单订阅消息异常，订单号：{}", shopOrder.getOrderNo(), e);
        }

        // 8. 创建微信支付订单
        try {
            return shopOrderService.createWxOrder(shopOrder);
        } catch (Exception e) {
            log.error("创建微信支付订单失败，订单号：{}", shopOrder.getOrderNo(), e);
            throw new BusinessException("创建支付订单失败：" + e.getMessage());
        }
    }

    /**
     * 校验订单请求参数
     */
    private void validateOrderRequest(OrderCreateRequest request, User loginUser) {
        if (loginUser == null) {
            throw new BusinessException("用户未登录");
        }

        // 检查是否为测试账号
        boolean isTestAccount = orderConfig.isTestAccount(loginUser.getPhone());

        if (isTestAccount) {
            // 测试账号：直接使用测试金额，跳过金额验证
            BigDecimal testAmount = orderConfig.getTestAccount().getTestPayAmount();
            request.setTotalPrice(testAmount);
            log.info("测试账号订单，用户：{}，使用测试金额：{}", loginUser.getPhone(), testAmount);
            return; // 测试账号跳过后续验证
        }

        // 非测试账号：正常验证流程
        // 验证商品信息并计算总金额
        BigDecimal calculatedTotal = validateAndCalculateTotal(request);

        if (calculatedTotal.compareTo(BigDecimal.ZERO) <= 0) {
            throw new BusinessException("商品金额不能为0");
        }

        // 检查前端传入的总金额是否正确（允许小的误差，比如0.01）
        if (request.getTotalPrice() != null &&
                request.getTotalPrice().subtract(calculatedTotal).abs().compareTo(new BigDecimal("0.01")) > 0) {
            log.warn("订单金额计算不一致，前端传入：{}，后台计算：{}", request.getTotalPrice(), calculatedTotal);
//            throw new BusinessException("订单金额计算错误，请刷新重试");
        }

        // 使用后台计算的金额
        request.setTotalPrice(calculatedTotal);

        // 检查租户特殊规则
        OrderConfigProperties.TenantRule tenantRule = orderConfig.getTenantRule(request.getTenantId());
        if (tenantRule != null && tenantRule.getMinAmount() != null) {
            if (calculatedTotal.compareTo(tenantRule.getMinAmount()) < 0) {
                throw new BusinessException(tenantRule.getMinAmountMessage());
            }
        }
    }

    /**
     * 验证商品信息并计算总金额
     */
    private BigDecimal validateAndCalculateTotal(OrderCreateRequest request) {
        if (CollectionUtils.isEmpty(request.getGoodsItems())) {
            throw new BusinessException("订单商品列表不能为空");
        }

        BigDecimal total = BigDecimal.ZERO;

        for (OrderCreateRequest.OrderGoodsItem item : request.getGoodsItems()) {
            // 验证商品ID
            if (item.getGoodsId() == null) {
                throw new BusinessException("商品ID不能为空");
            }

            // 验证购买数量
            if (item.getQuantity() == null || item.getQuantity() <= 0) {
                throw new BusinessException("商品购买数量必须大于0");
            }

            // 获取商品信息
            ShopGoods goods = shopGoodsService.getById(item.getGoodsId());
            if (goods == null) {
                throw new BusinessException("商品不存在，商品ID：" + item.getGoodsId());
            }

            // 验证商品状态
            if (goods.getStatus() == null || goods.getStatus() != 0) {
                throw new BusinessException("商品已下架：" + goods.getName());
            }

            // 处理多规格商品价格和库存验证
            BigDecimal actualPrice = goods.getPrice(); // 默认使用商品价格
            Integer actualStock = goods.getStock(); // 默认使用商品库存
            String productName = goods.getName();

            if (item.getSkuId() != null) {
                // 多规格商品，获取SKU信息
                ShopGoodsSku sku = shopGoodsSkuService.getById(item.getSkuId());
                if (sku == null) {
                    throw new BusinessException("商品规格不存在，SKU ID：" + item.getSkuId());
                }

                // 验证SKU是否属于该商品
                if (!sku.getGoodsId().equals(item.getGoodsId())) {
                    throw new BusinessException("商品规格不匹配");
                }

                // 验证SKU状态
                if (sku.getStatus() == null || sku.getStatus() != 0) {
                    throw new BusinessException("商品规格已下架");
                }

                // 使用SKU的价格和库存
                actualPrice = sku.getPrice();
                actualStock = sku.getStock();
                productName = goods.getName() + "(" + (item.getSpecInfo() != null ? item.getSpecInfo() : sku.getSku()) + ")";
            }

            // 验证实际价格
            if (actualPrice == null || actualPrice.compareTo(BigDecimal.ZERO) <= 0) {
                throw new BusinessException("商品价格异常：" + productName);
            }

            // 验证库存
            if (actualStock != null && actualStock < item.getQuantity()) {
                throw new BusinessException("商品库存不足：" + productName + "，当前库存：" + actualStock);
            }

            // 验证购买数量限制（使用商品级别的限制）
            if (goods.getCanBuyNumber() != null && goods.getCanBuyNumber() > 0 &&
                    item.getQuantity() > goods.getCanBuyNumber()) {
                throw new BusinessException("商品购买数量超过限制：" + productName + "，最大购买数量：" + goods.getCanBuyNumber());
            }

            // 计算商品小计（使用实际价格）
            BigDecimal itemTotal = actualPrice.multiply(new BigDecimal(item.getQuantity()));
            total = total.add(itemTotal);

            log.debug("商品验证通过 - ID：{}，SKU ID：{}，名称：{}，单价：{}，数量：{}，小计：{}",
                    goods.getGoodsId(), item.getSkuId(), productName, actualPrice, item.getQuantity(), itemTotal);
        }

        log.info("订单商品验证完成，总金额：{}", total);
        return total;
    }

    /**
     * 构建订单对象
     */
    private ShopOrder buildShopOrder(OrderCreateRequest request, User loginUser) {
        ShopOrder shopOrder = new ShopOrder();

        // 复制请求参数到订单对象
        BeanUtils.copyProperties(request, shopOrder);

        // 下单时间 & 订单过期时间：默认下单后10分钟过期（用于发起支付等场景校验）
        LocalDateTime now = LocalDateTime.now();
        if (shopOrder.getCreateTime() == null) {
            shopOrder.setCreateTime(now);
        }
        if (shopOrder.getUpdateTime() == null) {
            shopOrder.setUpdateTime(now);
        }
        shopOrder.setExpirationTime(shopOrder.getCreateTime().plusMinutes(10));

        // 确保租户ID正确设置（关键字段，影响微信支付证书路径）
        shopOrder.setTenantId(loginUser.getTenantId());

        // 验证关键字段
        if (shopOrder.getTenantId() == null) {
            throw new BusinessException("租户ID不能为空，这会导致微信支付证书路径错误");
        }

        // 设置用户相关信息
        shopOrder.setUserId(loginUser.getUserId());
        shopOrder.setOpenid(loginUser.getOpenid());
        shopOrder.setPayUserId(loginUser.getUserId());

        log.debug("构建订单对象 - 租户ID：{}，用户ID：{}", shopOrder.getTenantId(), shopOrder.getUserId());

        // 生成订单号（如果请求中没有提供）
        if (shopOrder.getOrderNo() == null || shopOrder.getOrderNo().trim().isEmpty()) {
            String generatedOrderNo = Long.toString(IdUtil.getSnowflakeNextId());
            shopOrder.setOrderNo(generatedOrderNo);
            log.info("生成新订单号: {}", generatedOrderNo);
        } else {
            log.info("使用请求中的订单号: {}", shopOrder.getOrderNo());
        }

        // 设置默认备注
        if (shopOrder.getComments() == null) {
            shopOrder.setComments(orderConfig.getDefaultConfig().getDefaultComments());
        }

        // 设置价格相关字段（解决数据库字段没有默认值的问题）
        if (shopOrder.getPayPrice() == null) {
            shopOrder.setPayPrice(shopOrder.getTotalPrice()); // 实际付款默认等于订单总额
        }

        if (shopOrder.getPrice() == null) {
            shopOrder.setPrice(shopOrder.getTotalPrice()); // 用于统计的价格默认等于订单总额
        }

        if (shopOrder.getReducePrice() == null) {
            shopOrder.setReducePrice(BigDecimal.ZERO); // 减少金额默认为0
        }

        if (shopOrder.getMoney() == null) {
            shopOrder.setMoney(shopOrder.getTotalPrice()); // 用于积分赠送的价格默认等于订单总额
        }

        // 设置默认状态
        shopOrder.setPayStatus(false); // 未付款
        shopOrder.setOrderStatus(0); // 未使用
        shopOrder.setDeliveryStatus(10); // 未发货
        shopOrder.setIsInvoice(0); // 未开发票
        shopOrder.setIsSettled(0); // 未结算
        shopOrder.setCheckBill(0); // 未对账
        shopOrder.setVersion(0); // 当前版本

        // 设置默认支付类型（如果没有指定）
        if (shopOrder.getPayType() == null) {
            shopOrder.setPayType(1); // 默认微信支付
        }

        // 优惠券处理
        if (shopOrder.getCouponId() != null && shopOrder.getCouponId() > 0) {
            processCoupon(shopOrder, loginUser);
        }

        return shopOrder;
    }

    /**
     * 处理优惠券
     */
    private void processCoupon(ShopOrder shopOrder, User loginUser) {
        ShopUserCoupon coupon = shopUserCouponService.getById(shopOrder.getCouponId());
        if (coupon == null) {
            throw new BusinessException("优惠券不存在");
        }

        // 验证优惠券是否属于当前用户
        if (!coupon.getUserId().equals(loginUser.getUserId())) {
            throw new BusinessException("优惠券不属于当前用户");
        }

        // 验证优惠券是否已使用
        if (coupon.getIsUse() != null && coupon.getIsUse().equals(1)) {
            throw new BusinessException("优惠券已使用");
        }

        // 验证优惠券是否过期
        if (coupon.getIsExpire() != null && coupon.getIsExpire().equals(1)) {
            throw new BusinessException("优惠券已过期");
        }

        // 计算优惠金额
        BigDecimal reducePrice = BigDecimal.ZERO;
        boolean canUse = true;

        if (coupon.getType().equals(10)) {
            // 满减券
            reducePrice = coupon.getReducePrice() != null ? coupon.getReducePrice() : BigDecimal.ZERO;
            BigDecimal minPrice = coupon.getMinPrice() != null ? coupon.getMinPrice() : BigDecimal.ZERO;
            if (shopOrder.getTotalPrice().compareTo(minPrice) < 0) {
                canUse = false;
                throw new BusinessException("订单金额不满足优惠券使用条件，最低消费：" + minPrice + "元");
            }
        } else if (coupon.getType().equals(20)) {
            // 折扣券 - 计算减免金额（不是折扣后金额）
            Integer discount = coupon.getDiscount() != null ? coupon.getDiscount() : 100;
            if (discount < 0 || discount > 100) {
                throw new BusinessException("优惠券折扣率异常");
            }
            // 减免金额 = 原价 * (100 - 折扣率) / 100
            reducePrice = shopOrder.getTotalPrice()
                    .multiply(new BigDecimal(100 - discount))
                    .divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);
        } else if (coupon.getType().equals(30)) {
            // 免费券
            reducePrice = shopOrder.getTotalPrice();
        } else {
            throw new BusinessException("不支持的优惠券类型");
        }

        if (canUse && reducePrice.compareTo(BigDecimal.ZERO) > 0) {
            // 确保减免金额不超过订单总额
            if (reducePrice.compareTo(shopOrder.getTotalPrice()) > 0) {
                reducePrice = shopOrder.getTotalPrice();
            }

            // 应用优惠
            shopOrder.setReducePrice(shopOrder.getReducePrice().add(reducePrice));
            shopOrder.setPayPrice(shopOrder.getPayPrice().subtract(reducePrice));

            // 确保实付金额不为负数
            if (shopOrder.getPayPrice().compareTo(BigDecimal.ZERO) < 0) {
                shopOrder.setPayPrice(BigDecimal.ZERO);
            }

            log.info("应用优惠券成功 - 优惠券ID：{}，类型：{}，减免金额：{}，实付金额：{}",
                    coupon.getId(), coupon.getType(), reducePrice, shopOrder.getPayPrice());
        }
    }

    /**
     * 处理收货地址信息
     * 优先级：前端传入地址 > 指定地址ID > 用户默认地址
     */
    private void processDeliveryAddress(ShopOrder shopOrder, OrderCreateRequest request, User loginUser) {
        try {
            // 前端可能会传 addressLat/addressLng，但不可信；这里一律以地址表中的坐标为准（需 addressId）。

            // 1. 如果指定了地址ID，优先使用该地址
            if (request.getAddressId() != null) {
                ShopUserAddress userAddress = shopUserAddressService.getById(request.getAddressId());
                if (userAddress != null && userAddress.getUserId().equals(loginUser.getUserId())) {
                    copyAddressToOrder(userAddress, shopOrder, request);
                    log.info("使用指定地址ID：{}，用户ID：{}", request.getAddressId(), loginUser.getUserId());
                    return;
                }
                log.warn("指定的地址ID不存在或不属于当前用户，地址ID：{}，用户ID：{}",
                        request.getAddressId(), loginUser.getUserId());
            }

            // 2. 若前端已传完整地址快照但没传 addressId：保持快照，不在这里“猜测”绑定地址。
            //    围栏校验会根据是否配置围栏决定是否强制要求 addressId。
            if (isAddressInfoComplete(request)) {
                log.warn("前端传入了收货地址快照字段，但未传 addressId，用户ID：{}", loginUser.getUserId());
                return;
            }

            // 3. 获取用户默认收货地址
            ShopUserAddress defaultAddress = shopUserAddressService.getDefaultAddress(loginUser.getUserId());
            if (defaultAddress != null) {
                copyAddressToOrder(defaultAddress, shopOrder, request);
                log.info("使用用户默认收货地址，地址ID：{}，用户ID：{}", defaultAddress.getId(), loginUser.getUserId());
                return;
            }

            // 4. 如果没有默认地址，获取用户的第一个地址
            List<ShopUserAddress> userAddresses = shopUserAddressService.getUserAddresses(loginUser.getUserId());
            if (!userAddresses.isEmpty()) {
                ShopUserAddress firstAddress = userAddresses.get(0);
                copyAddressToOrder(firstAddress, shopOrder, request);
                log.info("使用用户第一个收货地址，地址ID：{}，用户ID：{}", firstAddress.getId(), loginUser.getUserId());
                return;
            }
            // 5. 如果用户没有任何收货地址，抛出异常
            throw new BusinessException("请先添加收货地址");

        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            log.error("处理收货地址信息失败，用户ID：{}", loginUser.getUserId(), e);
            throw new BusinessException("处理收货地址信息失败：" + e.getMessage());
        }
    }

    /**
     * 检查前端传入的地址信息是否完整
     */
    private boolean isAddressInfoComplete(OrderCreateRequest request) {
        return request.getAddress() != null && !request.getAddress().trim().isEmpty() &&
                request.getRealName() != null && !request.getRealName().trim().isEmpty();
    }

    /**
     * 将用户地址信息复制到订单中（创建快照）
     */
    private void copyAddressToOrder(ShopUserAddress userAddress, ShopOrder shopOrder, OrderCreateRequest request) {
        // 保存地址ID引用关系
        shopOrder.setAddressId(userAddress.getId());
        request.setAddressId(userAddress.getId());

        // 创建地址信息快照
        if (request.getAddress() == null || request.getAddress().trim().isEmpty()) {
            // 构建完整地址
            StringBuilder fullAddress = new StringBuilder();
            if (userAddress.getProvince() != null) fullAddress.append(userAddress.getProvince());
            if (userAddress.getCity() != null) fullAddress.append(userAddress.getCity());
            if (userAddress.getRegion() != null) fullAddress.append(userAddress.getRegion());
            if (userAddress.getAddress() != null) fullAddress.append(userAddress.getAddress());

            shopOrder.setAddress(fullAddress.toString());
            request.setAddress(fullAddress.toString());
        }

        // 复制收货人信息
        if (request.getRealName() == null || request.getRealName().trim().isEmpty()) {
            shopOrder.setRealName(userAddress.getName());
            request.setRealName(userAddress.getName());
        }

        // 复制经纬度信息（不信任前端传入坐标，一律以地址表为准）
        if (userAddress.getLat() != null && !userAddress.getLat().trim().isEmpty()) {
            shopOrder.setAddressLat(userAddress.getLat());
            request.setAddressLat(userAddress.getLat());
        }
        if (userAddress.getLng() != null && !userAddress.getLng().trim().isEmpty()) {
            shopOrder.setAddressLng(userAddress.getLng());
            request.setAddressLng(userAddress.getLng());
        }

        log.debug("地址信息快照创建完成 - 地址ID：{}，收货人：{}，地址：{}",
                userAddress.getId(), userAddress.getName(), shopOrder.getAddress());
    }

    /**
     * 下单时校验配送范围（电子围栏）。
     * <p>
     * 规则：
     * - 仅对需要配送到地址的订单做校验；自提/无需物流跳过；
     * - 不信任前端传经纬度：用 addressId 反查地址表中的 lat/lng；
     * - 无围栏配置默认放行；围栏配置异常则拒单（避免误送）。
     */
    private void validateDeliveryFenceIfNeeded(ShopOrder shopOrder, User loginUser) {
        if (shopOrder == null || loginUser == null) {
            return;
        }

        // 自提/无需物流：不校验配送围栏
        if (shopOrder.getSelfTakeMerchantId() != null && shopOrder.getSelfTakeMerchantId() > 0) {
            return;
        }
        if (shopOrder.getDeliveryType() != null && shopOrder.getDeliveryType().equals(1)) {
            return;
        }

        // 若已配置围栏，则必须有 addressId 才能从地址表取坐标进行校验
        if (shopOrder.getAddressId() == null) {
            if (shopStoreFenceService.hasEnabledFences(shopOrder.getTenantId())) {
                throw new BusinessException("请先选择收货地址");
            }
            return;
        }

        ShopUserAddress address = shopUserAddressService.getById(shopOrder.getAddressId());
        if (address == null || address.getUserId() == null || !address.getUserId().equals(loginUser.getUserId())) {
            throw new BusinessException("收货地址不存在");
        }
        if (address.getTenantId() != null && shopOrder.getTenantId() != null && !address.getTenantId().equals(shopOrder.getTenantId())) {
            throw new BusinessException("收货地址不存在");
        }

        String latStr = address.getLat();
        String lngStr = address.getLng();
        if (latStr == null || latStr.trim().isEmpty() || lngStr == null || lngStr.trim().isEmpty()) {
            throw new BusinessException("收货地址坐标缺失，请重新选择收货地址");
        }
        double lat;
        double lng;
        try {
            lat = Double.parseDouble(latStr.trim());
            lng = Double.parseDouble(lngStr.trim());
        } catch (Exception e) {
            throw new BusinessException("收货地址坐标异常，请重新选择收货地址");
        }

        // 只做校验；具体围栏列表/points 异常处理由围栏服务统一处理
        shopStoreFenceService.validatePointInEnabledFences(shopOrder.getTenantId(), lng, lat);
    }

    /**
     * 应用业务规则
     */
    private void applyBusinessRules(ShopOrder shopOrder, User loginUser) {
        // 测试账号处理
        if (orderConfig.isTestAccount(loginUser.getPhone())) {
            BigDecimal testAmount = orderConfig.getTestAccount().getTestPayAmount();
            shopOrder.setPrice(testAmount);
            shopOrder.setTotalPrice(testAmount);
            shopOrder.setPayPrice(testAmount); // 确保实际付款也设置为测试金额
            shopOrder.setMoney(testAmount); // 确保积分计算金额也设置为测试金额
            log.info("应用测试账号规则，用户：{}，测试金额：{}", loginUser.getPhone(), testAmount);
        }

        // 其他业务规则可以在这里添加
        // 例如：VIP折扣、优惠券处理等
    }

    /**
     * 校验订单金额
     */
    public void validateOrderAmount(BigDecimal amount, Integer tenantId) {
        if (amount == null || amount.compareTo(BigDecimal.ZERO) <= 0) {
            throw new BusinessException("订单金额必须大于0");
        }

        OrderConfigProperties.TenantRule tenantRule = orderConfig.getTenantRule(tenantId);
        if (tenantRule != null && tenantRule.getMinAmount() != null) {
            if (amount.compareTo(tenantRule.getMinAmount()) < 0) {
                throw new BusinessException(tenantRule.getMinAmountMessage());
            }
        }
    }

    /**
     * 保存订单商品
     */
    private void saveOrderGoods(OrderCreateRequest request, ShopOrder shopOrder) {
        if (CollectionUtils.isEmpty(request.getGoodsItems())) {
            log.warn("订单商品列表为空，订单号：{}", shopOrder.getOrderNo());
            return;
        }

        List<ShopOrderGoods> orderGoodsList = new ArrayList<>();
        for (OrderCreateRequest.OrderGoodsItem item : request.getGoodsItems()) {
            // 重新获取商品信息（确保数据一致性）
            ShopGoods goods = shopGoodsService.getById(item.getGoodsId());
            if (goods == null) {
                throw new BusinessException("商品不存在，商品ID：" + item.getGoodsId());
            }

            // 再次验证商品状态（防止并发问题）
            if (goods.getStatus() == null || goods.getStatus() != 0) {
                throw new BusinessException("商品已下架：" + goods.getName());
            }

            // 处理多规格商品
            ShopGoodsSku sku = null;
            BigDecimal actualPrice = goods.getPrice(); // 默认使用商品价格
            Integer actualStock = goods.getStock(); // 默认使用商品库存
            String specInfo = item.getSpecInfo(); // 规格信息

            if (item.getSkuId() != null) {
                // 多规格商品，获取SKU信息
                sku = shopGoodsSkuService.getById(item.getSkuId());
                if (sku == null) {
                    throw new BusinessException("商品规格不存在，SKU ID：" + item.getSkuId());
                }

                // 验证SKU是否属于该商品
                if (!sku.getGoodsId().equals(item.getGoodsId())) {
                    throw new BusinessException("商品规格不匹配");
                }

                // 验证SKU状态
                if (sku.getStatus() == null || sku.getStatus() != 0) {
                    throw new BusinessException("商品规格已下架");
                }

                // 使用SKU的价格和库存
                actualPrice = sku.getPrice();
                actualStock = sku.getStock();

                // 如果前端没有传规格信息，使用SKU的规格信息
                if (specInfo == null || specInfo.trim().isEmpty()) {
                    specInfo = sku.getSku(); // 使用SKU的规格描述
                }
            }

            // 验证库存
            if (actualStock == null || actualStock < item.getQuantity()) {
                String stockMsg = sku != null ? "商品规格库存不足" : "商品库存不足";
                throw new BusinessException(stockMsg + "，当前库存：" + (actualStock != null ? actualStock : 0));
            }

            ShopOrderGoods orderGoods = new ShopOrderGoods();

            // 设置订单关联信息
            orderGoods.setOrderId(shopOrder.getOrderId());
            orderGoods.setOrderCode(shopOrder.getOrderNo());

            // 设置商户信息
            orderGoods.setMerchantId(shopOrder.getMerchantId());
            orderGoods.setMerchantName(shopOrder.getMerchantName());

            // 设置商品信息（使用后台查询的真实数据）
            orderGoods.setGoodsId(item.getGoodsId());
            orderGoods.setSkuId(item.getSkuId()); // 设置SKU ID
            orderGoods.setGoodsName(goods.getName());
            orderGoods.setImage(sku != null && sku.getImage() != null ? sku.getImage() : goods.getImage()); // 优先使用SKU图片
            orderGoods.setPrice(actualPrice); // 使用实际价格（SKU价格或商品价格）
            orderGoods.setTotalNum(item.getQuantity());

            // 计算商品小计（用于日志记录）
            BigDecimal itemTotal = actualPrice.multiply(new BigDecimal(item.getQuantity()));

            // 设置商品规格信息
            orderGoods.setSpec(specInfo);

            // 设置支付相关信息
            orderGoods.setPayStatus(0); // 0 未付款
            orderGoods.setOrderStatus(0); // 0 未使用
            orderGoods.setIsFree(false); // 默认收费
            orderGoods.setVersion(0); // 当前版本

            // 设置其他信息
            orderGoods.setComments(request.getComments());
            orderGoods.setUserId(shopOrder.getUserId());
            orderGoods.setTenantId(shopOrder.getTenantId());

            orderGoodsList.add(orderGoods);

            log.debug("准备保存订单商品 - 商品ID：{}，名称：{}，单价：{}，数量：{}，小计：{}",
                    goods.getGoodsId(), goods.getName(), goods.getPrice(), item.getQuantity(), itemTotal);
        }

        // 批量保存订单商品
        boolean saved = shopOrderGoodsService.saveBatch(orderGoodsList);
        if (!saved) {
            throw new BusinessException("保存订单商品失败");
        }

        // 扣减库存
        deductStock(request);

        log.info("成功保存订单商品，订单号：{}，商品数量：{}", shopOrder.getOrderNo(), orderGoodsList.size());
    }

    /**
     * 扣减库存
     */
    private void deductStock(OrderCreateRequest request) {
        for (OrderCreateRequest.OrderGoodsItem item : request.getGoodsItems()) {
            // 付款减库存的商品：创建订单时不扣库存
            ShopGoods goodsForType = shopGoodsService.getById(item.getGoodsId());
            Integer deductStockType = goodsForType != null ? goodsForType.getDeductStockType() : null;
            if (deductStockType != null && deductStockType == DEDUCT_STOCK_TYPE_PAY) {
                log.debug("跳过下单扣库存(付款减库存) - goodsId={}, skuId={}, qty={}",
                        item.getGoodsId(), item.getSkuId(), item.getQuantity());
                continue;
            }

            if (item.getSkuId() != null) {
                // 多规格商品，扣减SKU库存
                ShopGoodsSku sku = shopGoodsSkuService.getById(item.getSkuId());
                if (sku != null && sku.getStock() != null) {
                    int newStock = sku.getStock() - item.getQuantity();
                    if (newStock < 0) {
                        throw new BusinessException("SKU库存不足，无法完成扣减");
                    }
                    sku.setStock(newStock);
                    shopGoodsSkuService.updateById(sku);
                    log.debug("扣减SKU库存 - SKU ID：{}，扣减数量：{}，剩余库存：{}",
                            item.getSkuId(), item.getQuantity(), newStock);
                }
            } else {
                // 单规格商品，扣减商品库存
                ShopGoods goods = shopGoodsService.getById(item.getGoodsId());
                if (goods != null && goods.getStock() != null) {
                    int newStock = goods.getStock() - item.getQuantity();
                    if (newStock < 0) {
                        throw new BusinessException("商品库存不足，无法完成扣减");
                    }
                    goods.setStock(newStock);
                    shopGoodsService.updateById(goods);
                    log.debug("扣减商品库存 - 商品ID：{}，扣减数量：{}，剩余库存：{}",
                            item.getGoodsId(), item.getQuantity(), newStock);
                }
            }
        }
        log.info("库存扣减完成");
    }

    /**
     * 标记优惠券为已使用
     */
    private void markCouponAsUsed(Integer couponId, Integer orderId) {
        try {
            ShopUserCoupon coupon = shopUserCouponService.getById(couponId);
            if (coupon != null) {
                // 使用实体类提供的方法标记为已使用
                coupon.markAsUsed(orderId, null); // orderNo 在这里可以为null，因为已经有orderId了
                shopUserCouponService.updateById(coupon);
                log.info("优惠券标记为已使用 - 优惠券ID：{}，订单ID：{}", couponId, orderId);
            }
        } catch (Exception e) {
            log.error("标记优惠券为已使用失败 - 优惠券ID：{}，订单ID：{}", couponId, orderId, e);
            // 不抛出异常，避免影响订单创建流程
        }
    }

    /**
     * 检查是否为测试账号11
     */
    public boolean isTestAccount(String phone) {
        return orderConfig.isTestAccount(phone);
    }
}
