From f355f9e40ba17e133b20e3a6b90d9847b114363a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E9=9D=99?= Date: Fri, 17 Dec 2021 14:35:12 +0800 Subject: [PATCH] WIP --- app/Services/OrderService.php | 67 +++++++++++++++-------------------- 1 file changed, 28 insertions(+), 39 deletions(-) diff --git a/app/Services/OrderService.php b/app/Services/OrderService.php index 87d6f114..62200231 100644 --- a/app/Services/OrderService.php +++ b/app/Services/OrderService.php @@ -482,49 +482,38 @@ class OrderService throw new BizException('优惠券不满足使用条件'); } - // 商品的券折扣金额 - $discountAmounts = []; - // 优惠券折扣总额 - $discountTotalAmount = 0; - // 未计算优惠金额的商品总数 - $lastCount = count($amounts); - - foreach ($amounts as $skuId => $amount) { + // 优惠券折扣金额 + $couponAmount = value(function ($coupon, $totalAmount) { + // 如果优惠券是折扣券,则需算出优惠总额 if ($coupon->isDiscountCoupon()) { - /* - |---------------------------------------- - | 计算折扣券的折扣金额 - |---------------------------------------- - */ - - $discountAmounts[$skuId] = (int) bcmul($amount, bcdiv(100 - $coupon->coupon_amount, 100, 2)); - } else { - /* - |---------------------------------------- - | 计算抵扣券的抵扣金额 - |---------------------------------------- - */ - - $couponAmount = $coupon->coupon_amount; - - // 如果券的抵用金额大于商品的实际金额,则以商品实际金额作为抵扣金额 - if ($couponAmount > $totalAmount) { - $couponAmount = $totalAmount; - } - - $discountAmounts[$skuId] = (int) ($couponAmount * $amount / $totalAmount); - $discountTotalAmount += $discountAmounts[$skuId]; - - $lastCount--; - - // 将券的剩余抵扣金额给最后一个商品 - if ($lastCount === 0) { - $discountAmounts[$skuId] += $couponAmount - $discountTotalAmount; - } + return (int) bcmul($totalAmount, bcdiv(100 - $coupon->coupon_amount, 100, 2)); } + + // 如果优惠券的折扣金额超过商品总额,则优惠金额为商品总额 + if ($coupon->coupon_amount > $totalAmount) { + return $totalAmount; + } + + return $coupon->coupon_amount; + }, $coupon, $totalAmount); + + // 待计算优惠的商品总数 + $i = count($amounts); + + foreach ($amounts as &$amount) { + $i--; + + if ($i > 0) { + $amount = (int) bcdiv(bcmul($couponAmount, $amount, 0), $totalAmount, 2); + $couponAmount -= $amount; + } else { + $amount = $couponAmount; + } + + unset($amount); } - return $discountAmounts; + return $amounts; } /**