GoodsDeduct.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. namespace app\api\service\coupon;
  3. use app\common\library\helper;
  4. class GoodsDeduct
  5. {
  6. private $actualReducedMoney;
  7. public function setGoodsCouponMoney($goodsList, $reducedMoney)
  8. {
  9. // 统计订单商品总金额,(单位分)
  10. $orderTotalPrice = 0;
  11. foreach ($goodsList as &$goods) {
  12. $goods['total_price'] *= 100;
  13. $orderTotalPrice += $goods['total_price'];
  14. }
  15. // 计算实际抵扣金额
  16. $this->setActualReducedMoney($reducedMoney, $orderTotalPrice);
  17. // 实际抵扣金额为0,
  18. if ($this->actualReducedMoney > 0) {
  19. // 计算商品的价格权重
  20. $goodsList = $this->getGoodsListWeight($goodsList, $orderTotalPrice);
  21. // 计算商品优惠券抵扣金额
  22. $this->setGoodsListCouponMoney($goodsList);
  23. // 总抵扣金额
  24. $totalCouponMoney = helper::getArrayColumnSum($goodsList, 'coupon_money');
  25. $this->setGoodsListCouponMoneyFill($goodsList, $totalCouponMoney);
  26. $this->setGoodsListCouponMoneyDiff($goodsList, $totalCouponMoney);
  27. }
  28. return $goodsList;
  29. }
  30. public function getActualReducedMoney()
  31. {
  32. return $this->actualReducedMoney;
  33. }
  34. private function setActualReducedMoney($reducedMoney, $orderTotalPrice)
  35. {
  36. $reducedMoney *= 100;
  37. $this->actualReducedMoney = ($reducedMoney >= $orderTotalPrice) ? $orderTotalPrice - 1 : $reducedMoney;
  38. }
  39. private function arraySortByWeight($goodsList)
  40. {
  41. return array_sort($goodsList, 'weight', true);
  42. }
  43. private function getGoodsListWeight($goodsList, $orderTotalPrice)
  44. {
  45. foreach ($goodsList as &$goods) {
  46. $goods['weight'] = $goods['total_price'] / $orderTotalPrice;
  47. }
  48. return $this->arraySortByWeight($goodsList);
  49. }
  50. private function setGoodsListCouponMoney(&$goodsList)
  51. {
  52. foreach ($goodsList as &$goods) {
  53. $goods['coupon_money'] = helper::bcmul($this->actualReducedMoney, $goods['weight'], 0);
  54. }
  55. return true;
  56. }
  57. private function setGoodsListCouponMoneyFill(&$goodsList, $totalCouponMoney)
  58. {
  59. if ($totalCouponMoney === 0) {
  60. $temReducedMoney = $this->actualReducedMoney;
  61. foreach ($goodsList as &$goods) {
  62. if ($temReducedMoney === 0) break;
  63. $goods['coupon_money'] = 1;
  64. $temReducedMoney--;
  65. }
  66. }
  67. return true;
  68. }
  69. private function setGoodsListCouponMoneyDiff(&$goodsList, $totalCouponMoney)
  70. {
  71. $tempDiff = $this->actualReducedMoney - $totalCouponMoney;
  72. foreach ($goodsList as &$goods) {
  73. if ($tempDiff < 1) break;
  74. $goods['coupon_money']++ && $tempDiff--;
  75. }
  76. return true;
  77. }
  78. }