| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- <?php
- namespace app\api\service;
- use app\BaseService;
- use app\common\model\ActivityProductModel;
- use app\common\model\ConfigModel;
- use app\common\model\ProductModel;
- use app\common\model\StoreProductModel;
- class ProductService extends BaseService
- {
- private $productModel;
- private $storeProductModel;
- private $activityProductModel;
- private $configModel;
- public function __construct()
- {
- $this->productModel = new ProductModel();
- $this->configModel = new ConfigModel();
- $this->storeProductModel = new StoreProductModel();
- $this->activityProductModel = new ActivityProductModel();
- }
- public function search($store_id,$bar_code = null, $product_name = null, $page = 1, $size = 10) {
- $storeProducts = $this->storeProductModel->search([
- 'store_id' => $store_id,
- 'bar_code' => $bar_code,
- 'product_name' => $product_name,
- 'page' => $page,
- "size" => $size
- ]);
- $items = $storeProducts->items();
- $config = $this->configModel->findConfig();
- $productIds = array_map(function ($data) {
- return $data['product_id'];
- }, $items);
- $activityProducts = $this->activityProductModel->fetchByProductIds($productIds)->toArray();
- foreach ($items as &$item) {
- $aProducts = array_filter($activityProducts, function ($aProduct) use ($item) {
- return $aProduct['product_id'] == $item['product_id'];
- });
- $res = $this->compare($item['product']['real_price'] ?? 0, $aProducts);
- $item['product']['real_price'] = fixed2Float($res['min_num']);
- $item['activity'] = $res['item'];
- $item['product']['tax_rate'] = $item['product']['tax_rate'] > 0 ? $item['product']['tax_rate'] : $config->tax_rate;
- }
- return [$items, $storeProducts->total()];
- }
- private function compare($num, $array) {
- $min_num = $num;
- $index = null;
- if($num > 0) {
- foreach ($array as $key => $el) {
- $now_price = $num;
- if($el['type'] == 1) {
- $now_price = $num - $el['reduced_price'];
- } else {
- if($el['discount'] > 0) {
- $now_price = $num - ($num * ($el['discount'] / 100));
- }
- }
- if($min_num == null) {
- $min_num = $now_price;
- } else {
- if($now_price < $min_num) {
- $min_num = $now_price;
- $index = $key;
- }
- }
- }
- }
- return ['min_num' => $min_num, 'item' => $index == null ? null : $array[$index]];
- }
- }
|