海南旅游SAAS
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

379 lines
12 KiB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. <?php
  2. namespace App\Http\Controllers\Api;
  3. use App\Common\ProductStatus;
  4. use App\Http\Controllers\Controller;
  5. use App\Models\Advertising;
  6. use App\Models\AgentProduct;
  7. use App\Models\AgentProductSpec;
  8. use App\Models\Category;
  9. use App\Models\DiyForm;
  10. use App\Models\UserFav;
  11. use App\Models\Views\AgentProduct as AgentProductView;
  12. use Illuminate\Support\Facades\DB;
  13. use Illuminate\Support\Facades\Storage;
  14. /**
  15. * 代理商产品
  16. * Class AgentProductController
  17. * @package App\Http\Controllers\Api
  18. */
  19. class AgentProductController extends Controller
  20. {
  21. // 代理商产品列表
  22. public function index()
  23. {
  24. $formData = request()->only(['category_id', 'type', 'by', 'lat', 'lng']);
  25. $category_id = $formData['category_id'] ?? 0;
  26. $type = $formData['type'] ?? 0;
  27. $by = $formData['by'] ?? 0;
  28. $lat = $formData['lat'] ?? 0;
  29. $lng = $formData['lng'] ?? 0;
  30. $list = AgentProductView::list($this->agent_id);
  31. if ($category_id) {
  32. $list = $list->whereIn('category_id', [$category_id, ...$this->get_category_child_ids($category_id)]);
  33. }
  34. // 距离排序
  35. if ($lat && $lng) {
  36. $list = $list->addSelect('latitude', 'longitude', 'address', DB::raw(<<<SQL
  37. round(
  38. (((6371.393 * 2) * asin(
  39. sqrt((
  40. pow( sin((((( {$lat} * 3.1415926 ) / 180 ) - (( `latitude` * pi()) / 180 )) / 2 )), 2 )
  41. +
  42. (
  43. (cos((({$lat} * 3.1415926) / 180)) * cos(((`latitude` * pi()) / 180)))
  44. *
  45. pow( sin((((( {$lng} * 3.1415926 ) / 180 ) - (( `longitude` * pi()) / 180 )) / 2 )), 2 ))))
  46. )) * 1000),0) AS `distance_m`
  47. SQL
  48. ));
  49. $by = 1; //距离排序默认升序
  50. }
  51. $fields = ['id', 'sale', 'updated_at', 'price', 'distance_m']; //排序字段
  52. $field = $fields[$type] ?? $fields[0];
  53. $by = $by == 0 ? 'desc' : 'asc';
  54. $list = $list->orderBy($field, $by)->simplePaginate();
  55. $list = $this->paginatePicAddHost($list);
  56. $list = $this->insertAd($list);
  57. return $this->success($list);
  58. }
  59. //递归获取指定分类下的所有子分类
  60. private function get_category_child_ids($category_id): array
  61. {
  62. static $category = null;
  63. if ($category === null) {
  64. $category = Category::where('agent_id', $this->agent_id)->get()->toArray();
  65. }
  66. $child = [];
  67. foreach ($category as $cat) {
  68. if ($cat['pid'] == $category_id) {
  69. $child[] = $cat['id'];
  70. $child = array_merge($child, $this->get_category_child_ids($cat['id']));
  71. }
  72. }
  73. return $child;
  74. }
  75. //首页搜索框
  76. public function search()
  77. {
  78. $category_id = request()->input('category_id');
  79. $keywords = request()->input('keywords');
  80. $type = request()->input('type', 0);
  81. $by = request()->input('by', 0);
  82. $list = AgentProduct::list($this->agent_id);
  83. if ($category_id) {
  84. $list = $list->whereIn('category_id', [$category_id, ...$this->get_category_child_ids($category_id)]);
  85. }
  86. if ($keywords) {
  87. $list = $list->where('title', 'like', "%$keywords%");
  88. }
  89. $fields = ['id', 'sale', 'updated_at', 'price']; //排序字段
  90. $field = $fields[$type] ?? $fields[0];
  91. $by = $by == 0 ? 'desc' : 'asc';
  92. $list = $list->orderBy($field, $by)->simplePaginate();
  93. $list = $this->paginatePicAddHost($list);
  94. return $this->success($list);
  95. }
  96. //旅游线路搜索
  97. public function travel_search()
  98. {
  99. $formData = request()->only(['departure_place', 'destination', 'type', 'by']);
  100. $type = $formData['type'] ?? 0;
  101. $by = $formData['by'] ?? 0;
  102. if (empty($formData['departure_place']) && empty($formData['destination'])) {
  103. return $this->error('请输入出发地和目的地');
  104. }
  105. $fields = ['id', 'sale', 'updated_at', 'price']; //排序字段
  106. $field = $fields[$type] ?? $fields[0];
  107. $by = $by == 0 ? 'desc' : 'asc';
  108. $list = AgentProduct::list($this->agent_id)->whereHas('product', function($query) use ($formData) {
  109. //出发地
  110. if (!empty($formData['departure_place'])) {
  111. $query->whereRaw("extends->'$.field_0_departure_place' LIKE ?", ["%{$formData['departure_place']}%"]);
  112. }
  113. //目的地
  114. if (!empty($formData['destination'])) {
  115. $query->whereRaw("extends->'$.field_0_destination' LIKE ?", ["%{$formData['destination']}%"]);
  116. }
  117. })->orderBy($field, $by)->simplePaginate();
  118. $list = $this->paginatePicAddHost($list);
  119. return $this->success($list);
  120. }
  121. // 产品详情
  122. public function show()
  123. {
  124. $id = (int)request()->input('id');
  125. if (AgentProduct::where('agent_id', $this->agent_id)->withTrashed()->count() === 0) { //演示产品用
  126. $where = ['id' => $id, 'status' => ProductStatus::ON_SALE];
  127. } else {
  128. $where = ['id' => $id, 'agent_id' => $this->agent_id, 'status' => ProductStatus::ON_SALE];
  129. }
  130. $agent_product = AgentProduct::with([
  131. 'diyForm.fields',
  132. 'coupon:tag,agent_product_id',
  133. 'product' => function ($query) {
  134. $query->select(['id', 'type', 'extends', 'diy_form_id', 'longitude', 'latitude', 'address'])
  135. ->with('diyForm', function ($query) {
  136. $query->select(['id', 'name'])->with('fields');
  137. });
  138. },
  139. 'spec' => function($query) {
  140. return $query->has('productSpec')->with('productSpec', function ($query) {
  141. $query->select(['id', 'name', 'date'])->where('date', '>=', date('Y-m-d'))->orderBy('date', 'asc');
  142. });
  143. }
  144. ])
  145. ->where(function ($query) {
  146. $query->whereHas('product', function ($query) {
  147. return $query->where([['stock', '>', 0], ['status', '=', ProductStatus::ON_SALE]]);
  148. })->orWhere('product_id', 0);
  149. })
  150. ->where('stock', '>', 0)
  151. ->firstWhere($where);
  152. if (!$agent_product) {
  153. return $this->error('产品已下架或库存不足');
  154. }
  155. $prefix = Storage::disk('public')->url('');
  156. $agent_product->pictures = array_map(fn($item) => ($prefix . $item), $agent_product->pictures);
  157. if ($this->user_id) {
  158. $agent_product->is_collect = UserFav::query()->where(['user_id' => $this->user_id, 'agent_product_id' => $id])->exists() ? 1 : 0; //判断是否收藏
  159. } else {
  160. $agent_product->is_collect = 0;
  161. }
  162. //计算折扣
  163. if ($agent_product->price < $agent_product->original_price) {
  164. $agent_product->cost = round($agent_product->price / $agent_product->original_price * 10, 1);
  165. } else {
  166. $agent_product->cost = '';
  167. }
  168. //处理自定义字段
  169. if (!empty($agent_product->product->diyForm->fields) && !$agent_product->product->diyForm->fields->isEmpty()) {
  170. foreach ($agent_product->product->diyForm->fields as &$v) {
  171. if ($v['type'] == 'checkbox' && is_array($v['options'])) {
  172. $v['options'] = array_map(function ($v2) {
  173. $arr['checked'] = false;
  174. $arr['disabled'] = false;
  175. $arr['name'] = $v2;
  176. return $arr;
  177. }, $v['options']);
  178. }
  179. }
  180. }
  181. //处理规格
  182. if (!$agent_product->spec->isEmpty()) {
  183. $specs = $agent_product->spec->toArray();
  184. //二维数组转一维
  185. $specs = array_map(function ($v) {
  186. if (is_array($v['product_spec'])) {
  187. unset($v['product_spec']['id']);
  188. $v = array_merge($v, $v['product_spec']);
  189. }
  190. unset($v['agent_product_id'], $v['product_spec_id'], $v['product_spec'], $v['deleted_at']);
  191. return $v;
  192. }, $specs);
  193. unset($agent_product->spec, $agent_product->product->longitude, $agent_product->product->latitude, $agent_product->product->address); //unset后才能重新赋值
  194. $agent_product->spec = $this->spec_format($specs);
  195. //位置信息
  196. $agent_product->longitude = $agent_product->product->longitude ?? 0;
  197. $agent_product->latitude = $agent_product->product->latitude ?? 0;
  198. $agent_product->address = $agent_product->product->address ?? '';
  199. }
  200. //自营产品
  201. if ($agent_product->product_id == 0) {
  202. //自营产品规格
  203. $specs = AgentProductSpec::orderBy('date', 'asc')
  204. ->where([
  205. ['agent_product_id', '=', $agent_product->id],
  206. ['date', '>=', date('Y-m-d')],
  207. ])
  208. ->get(['id', 'name', 'date', 'stock', 'original_price', 'price'])->toArray();
  209. unset($agent_product->spec); //unset后才能重新赋值
  210. $agent_product->spec = $this->spec_format($specs);
  211. //自营产品product
  212. $product = [
  213. 'product_id' => 0,
  214. 'type' => $agent_product->tpl_type,
  215. 'extends' => $agent_product->extends,
  216. 'diy_form' => $agent_product->diyForm ? [
  217. 'id' => $agent_product->diyForm->id ?? 0,
  218. 'name' => $agent_product->diyForm->name ?? '',
  219. 'fields' => $agent_product->diyForm->fields ?? null,
  220. ] : null,
  221. ];
  222. unset($agent_product->product, $agent_product->tpl_type, $agent_product->extends, $agent_product->diyForm);
  223. $agent_product->product = $product;
  224. }
  225. unset($agent_product->agent_id, $agent_product->status, $agent_product->deleted_at);
  226. return $this->success($agent_product);
  227. }
  228. private function spec_format(array $specs)
  229. {
  230. //去掉name和date为空的数组
  231. $specs = array_filter($specs, fn($v) => isset($v['name'], $v['date']));
  232. $names = array_column($specs, 'name');
  233. $names = array_values(array_unique($names));
  234. $result = [];
  235. foreach ($names as $name) {
  236. $list = array_filter($specs, fn($v) => $v['name'] == $name);
  237. $result[] = [
  238. 'name' => $name,
  239. 'date_start' => min(array_column($list, 'date')),
  240. 'date_end' => max(array_column($list, 'date')),
  241. 'original_price' => min(array_column($list, 'original_price')),
  242. 'price' => min(array_column($list, 'price')),
  243. 'list' => array_values($list),
  244. ];
  245. }
  246. return $result;
  247. }
  248. // 猜你喜欢
  249. public function guessLike()
  250. {
  251. $list = AgentProduct::list($this->agent_id)->orderBy('id', 'DESC')->simplePaginate();
  252. $list = $this->paginatePicAddHost($list);
  253. $list = $list->toArray();
  254. if (!empty($list['data']) && is_array($list['data'])) {
  255. shuffle($list['data']); //随机乱序
  256. }
  257. $list = $this->insertAd($list);
  258. return $this->success($list);
  259. }
  260. //【我的】页面下方推荐
  261. public function recommendList()
  262. {
  263. $list = AgentProduct::list($this->agent_id)->where(['is_rec' => 1])
  264. ->orderBy('id', 'DESC')->simplePaginate();
  265. $list = $this->paginatePicAddHost($list);
  266. $list = $this->insertAd($list);
  267. return $this->success($list);
  268. }
  269. //人气爆款列表,销量排序
  270. public function hotList()
  271. {
  272. $list = AgentProduct::list($this->agent_id)
  273. ->orderBy('sale', 'DESC')->orderBy('id', 'DESC')->simplePaginate();
  274. $list = $this->paginatePicAddHost($list);
  275. $list = $this->insertAd($list);
  276. return $this->success($list);
  277. }
  278. //分页列表产品图片加域名
  279. private function paginatePicAddHost($list)
  280. {
  281. //如果是新入驻代理商没有数据,且没有删除过的数据,则显示最早的几条
  282. if ($list->isEmpty()) {
  283. if (AgentProduct::where('agent_id', $this->agent_id)->withTrashed()->count() === 0 && request('page', 1) <= 2) { //只获取2页数据
  284. $list = AgentProduct::list($this->agent_id)->orWhere([['status', '=', ProductStatus::ON_SALE], ['price', '>', 500]])->orderBy('id')->simplePaginate();
  285. } else {
  286. return $list; //因为只获取2页数据,不return可能会导入下面的代码出错
  287. }
  288. }
  289. $prefix = Storage::disk('public')->url('');
  290. foreach ($list->items() as $k=>&$v) {
  291. $v->pictures = array_map(function($item) use ($prefix) {
  292. return strpos($item, $prefix) === false ? $prefix . $item : $item;
  293. }, $v->pictures);
  294. }
  295. return $list;
  296. }
  297. //插入瀑布流广告
  298. private function insertAd($list)
  299. {
  300. //插入瀑布流广告,分别在第8个和第16个插入,同时需要考虑到分页。当所有瀑布流广告插入完之后,再次循环插入
  301. if (is_object($list) && method_exists($list, 'toArray')) {
  302. $list = $list->toArray();
  303. }
  304. $ad_total = Advertising::where(['agent_id' => $this->agent_id, 'status' => 1, 'display' => 2])->count();
  305. if ($list['data'] && $ad_total > 0) {
  306. $page = (int)request()->input('page');
  307. $start = ($page ? $page - 1 : 0) * 2 % $ad_total;
  308. $ad = Advertising::where(['agent_id' => $this->agent_id, 'status' => 1, 'display' => 2])
  309. ->orderBy('sort')->orderBy('id', 'DESC')
  310. ->offset($start)->limit(2)->get(['title', 'picture', 'type', 'url'])->toArray();
  311. $prefix = Storage::disk('public')->url('');
  312. foreach ($ad as $k => &$v) {
  313. $v['is_ad'] = true;
  314. $v['picture'] = $prefix . $v['picture'];
  315. //每隔8个插入广告
  316. $temp = 8 * ($k+1);
  317. if (!empty($list['data'][$temp - 1]) && !empty($ad[$k])) {
  318. array_splice($list['data'], $temp + $k, 0, [$ad[$k]]);
  319. }
  320. }
  321. }
  322. return $list;
  323. }
  324. }