ProductService.php 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. namespace app\api\service;
  3. use app\BaseService;
  4. use app\common\model\ActivityProductModel;
  5. use app\common\model\ConfigModel;
  6. use app\common\model\ProductModel;
  7. use app\common\model\StoreProductModel;
  8. class ProductService extends BaseService
  9. {
  10. private $productModel;
  11. private $storeProductModel;
  12. private $activityProductModel;
  13. private $configModel;
  14. public function __construct()
  15. {
  16. $this->productModel = new ProductModel();
  17. $this->configModel = new ConfigModel();
  18. $this->storeProductModel = new StoreProductModel();
  19. $this->activityProductModel = new ActivityProductModel();
  20. }
  21. public function search($store_id,$bar_code = null, $product_name = null, $page = 1, $size = 10) {
  22. $storeProducts = $this->storeProductModel->search([
  23. 'store_id' => $store_id,
  24. 'bar_code' => $bar_code,
  25. 'product_name' => $product_name,
  26. 'page' => $page,
  27. "size" => $size
  28. ]);
  29. $items = $storeProducts->items();
  30. $config = $this->configModel->findConfig();
  31. $productIds = array_map(function ($data) {
  32. return $data['product_id'];
  33. }, $items);
  34. $activityProducts = $this->activityProductModel->fetchByProductIds($productIds)->toArray();
  35. foreach ($items as &$item) {
  36. $aProducts = array_filter($activityProducts, function ($aProduct) use ($item) {
  37. return $aProduct['product_id'] == $item['product_id'];
  38. });
  39. $res = $this->compare($item['product']['real_price'] ?? 0, $aProducts);
  40. $item['product']['real_price'] = fixed2Float($res['min_num']);
  41. $item['activity'] = $res['item'];
  42. $item['product']['tax_rate'] = $item['product']['tax_rate'] > 0 ? $item['product']['tax_rate'] : $config->tax_rate;
  43. }
  44. return [$items, $storeProducts->total()];
  45. }
  46. private function compare($num, $array) {
  47. $min_num = $num;
  48. $index = null;
  49. if($num > 0) {
  50. foreach ($array as $key => $el) {
  51. $now_price = $num;
  52. if($el['type'] == 1) {
  53. $now_price = $num - $el['reduced_price'];
  54. } else {
  55. if($el['discount'] > 0) {
  56. $now_price = $num - ($num * ($el['discount'] / 100));
  57. }
  58. }
  59. if($min_num == null) {
  60. $min_num = $now_price;
  61. } else {
  62. if($now_price < $min_num) {
  63. $min_num = $now_price;
  64. $index = $key;
  65. }
  66. }
  67. }
  68. }
  69. return ['min_num' => $min_num, 'item' => $index == null ? null : $array[$index]];
  70. }
  71. }