海南旅游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.

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