GoodsDeduct.php 3.0 KB

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