Goods.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. <?php
  2. namespace app\api\controller;
  3. use app\common\Enum\GoodsEnum;
  4. use app\common\model\Goods as GoodsModel;
  5. use app\common\model\Guarantee;
  6. use app\common\model\Collect;
  7. use app\common\model\Comment;
  8. use app\common\model\AttributeValue;
  9. // use app\common\model\Coupon;
  10. // use app\common\model\CouponCondition;
  11. // use app\common\model\UserCoupon;
  12. use app\common\Service\Goods\GoodService;
  13. use fast\Http;
  14. use think\Log;
  15. use think\Db;
  16. use app\common\Service\SkuSpec as SkuSpecService;
  17. use app\common\Service\Goods\CategoryService;
  18. use app\common\Service\DiscountService;
  19. use app\common\Service\Goods\CommentService;
  20. /**
  21. * 商品接口
  22. */
  23. class Goods extends Base
  24. {
  25. protected $noNeedLogin = [ 'detail', 'lists', 'getWxCode','getCategoryGoods'];
  26. //详情
  27. public function detail()
  28. {
  29. $id = $this->request->param('id/d');
  30. if (!$id) {
  31. $this->error('参数错误');
  32. }
  33. $row = (new GoodsModel())->with([
  34. 'Sku',
  35. 'Comment' => function ($query) {
  36. $query->relation([
  37. 'reply' => function ($user) {
  38. $user->with([
  39. 'manage' => function ($u) {
  40. $u->field('id,nickname');
  41. }
  42. ]);
  43. }
  44. ])->where('status', 'normal')->where('pid', 0)->field('id,goods_id,content,star,user_id,images,
  45. comments,createtime')->with([
  46. 'User' => function ($u) {
  47. $u->field('id,nickname,avatar');
  48. }
  49. ])->order('createtime', 'desc')->limit(10);
  50. }
  51. ])->whereIn('status',[GoodsEnum::STATUS_ON_SALE,GoodsEnum::STATUS_SOLD_OUT])->where('id', $id)->find();
  52. if (!$row) {
  53. $this->error('未找到该商品');
  54. }
  55. // 浏览次数
  56. $row->setInc('views');
  57. //收藏
  58. if ($this->auth->isLogin()) {
  59. $row->is_collect = !!(Collect::where('user_id', $this->auth->id)->where('goods_id', $id)->where('status', 1)->find());
  60. } else {
  61. $row->is_collect = false;
  62. }
  63. $row->sku_spec = SkuSpecService::getGoodsSkuSpec($id);
  64. // 要处理规格的图片
  65. // 这个错误是因为 $row->sku_spec 是一个重载属性(通过魔术方法 __get() 获取),不能直接通过引用修改。我们需要先将其转换为普通数组,处理后再赋值回去。
  66. if (!empty($row->sku_spec)) {
  67. $skuSpecData = $row->sku_spec; // 先转换为普通数组
  68. foreach ($skuSpecData as $key => &$item) {
  69. if (!empty($item['sku_value'])) {
  70. foreach ($item['sku_value'] as $k => &$v) {
  71. $v['image'] = empty($v['image']) ? '' : cdnurl($v['image'], true);
  72. }
  73. }
  74. }
  75. $row->sku_spec = $skuSpecData; // 处理完后重新赋值
  76. }
  77. //
  78. unset($item);
  79. //服务保障
  80. $row->guarantee = $row->guarantee_ids ? Guarantee::field('id,name,intro')->where('id', 'IN', $row->guarantee_ids)
  81. ->where('status', 'normal')->select() : [];
  82. //属性
  83. $row->attributes = AttributeValue::getAttributeList($row->attribute_ids);
  84. //好评度
  85. $commentInfo = CommentService::getCommentCountAndFirstComment($id);
  86. $comment_count = $commentInfo['total'] ?? 0;
  87. $row->comment = $commentInfo['comment'] ?? null;
  88. $row->visible(explode(',', 'id,title,type,spec_type,sub_title,category_ids,price,lineation_price,sales,views,is_hot,
  89. image,content,images,sku_spec,sku,comment,is_collect,guarantee,attributes,favor_rate,coupon,scheduled_online_time,is_auto_offline,scheduled_offline_time'));
  90. $row = $row->toArray();
  91. $row['content'] = \app\common\library\Service::formatTplToUniapp($row['content']);
  92. $row['comment_total'] = $comment_count;
  93. $this->success('获取成功', $row);
  94. }
  95. public function getGoodsCustomizedSpec()
  96. {
  97. $id = $this->request->param('id/d');
  98. if (!$id) {
  99. $this->error('参数错误');
  100. }
  101. $row = (new GoodsModel())
  102. ->field('id,title,sub_title,type,category_ids,price,lineation_price,image')
  103. ->whereIn('status',[GoodsEnum::STATUS_ON_SALE,GoodsEnum::STATUS_SOLD_OUT])
  104. ->where('id', $id)->find();
  105. if (!$row) {
  106. $this->error('未找到该商品');
  107. }
  108. $row->sku_spec = SkuSpecService::getGoodsSkuSpec($id,2);
  109. // 要处理规格的图片
  110. // 这个错误是因为 $row->sku_spec 是一个重载属性(通过魔术方法 __get() 获取),不能直接通过引用修改。我们需要先将其转换为普通数组,处理后再赋值回去。
  111. if (!empty($row->sku_spec)) {
  112. $skuSpecData = $row->sku_spec; // 先转换为普通数组
  113. foreach ($skuSpecData as $key => &$item) {
  114. if (!empty($item['sku_value'])) {
  115. foreach ($item['sku_value'] as $k => &$v) {
  116. $v['image'] = empty($v['image']) ? '' : cdnurl($v['image'], true);
  117. }
  118. }
  119. }
  120. $row->sku_spec = $skuSpecData; // 处理完后重新赋值
  121. }
  122. $this->success('获取成功', $row);
  123. }
  124. //列表
  125. public function lists()
  126. {
  127. $param = $this->request->param();
  128. // 增加验证器处理
  129. $validate = new \app\api\validate\Goods();
  130. if (!$validate->scene('lists')->check($param)) {
  131. $this->error($validate->getError());
  132. }
  133. $pageSize = $param['pageSize'] ?? 10;
  134. $orderby = $param['orderby'] ?? 'weigh';
  135. $orderway = $param['orderway'] ?? 'desc';
  136. // 映射字段 $orderby weigh,sales,price,views,comments,created_at
  137. $orderbyMap = [
  138. 'weigh' => 'weigh',
  139. 'sales' => 'sales',
  140. 'views' => 'views',
  141. 'comments' => 'comments',
  142. 'created_at' => 'createtime',
  143. ];
  144. $query = GoodsModel::where(function ($query) use ($param) {
  145. $query->where('status',GoodsEnum::STATUS_ON_SALE);
  146. //关键词
  147. if (isset($param['keywords']) && !empty($param['keywords'])) {
  148. $query->where('title|keywords', 'like', '%' . $param['keywords'] . '%');
  149. $log = \app\common\model\SearchLog::getByKeywords($param['keywords']);
  150. if ($log) {
  151. $log->setInc("nums");
  152. } else {
  153. \app\common\model\SearchLog::create(['keywords' => $param['keyword'], 'nums' => 1, 'status' => 'hidden']);
  154. }
  155. }
  156. //分类
  157. if (isset($param['category_id']) && !empty($param['category_id'])) {
  158. $categoryIds = [];
  159. // 获取子集
  160. $categoryChildIds = \app\common\model\Category::getCategoryChildrenIds($param['category_id']);
  161. $categoryIds = array_merge($categoryChildIds, [$param['category_id']]);
  162. $query->where(function ($query) use ($categoryIds) {
  163. // 所有子分类使用 find_in_set or 匹配,亲测速度并不慢
  164. foreach ($categoryIds as $key => $category_id) {
  165. $query->whereOrRaw("find_in_set($category_id, category_ids)");
  166. }
  167. });
  168. }
  169. //属性
  170. if (isset($param['attributes']) && !empty($param['attributes'])) {
  171. $query->where('id', 'IN', \app\common\model\GoodsAttr::getGoodsIds($param['attributes']));
  172. }
  173. //品牌
  174. if (isset($param['brand_id']) && !empty($param['brand_id'])) {
  175. $query->where('brand_id', 'IN', $param['brand_id']);
  176. }
  177. //价格
  178. if (isset($param['price']) && !empty($param['price'])) {
  179. $priceArr = explode('-', $param['price']);
  180. if (count($priceArr) == 2) {
  181. if (isset($priceArr[0])) {
  182. $priceArr[0] = (float)$priceArr[0];
  183. }
  184. if (isset($priceArr[1])) {
  185. $priceArr[1] = (float)$priceArr[1];
  186. }
  187. $query->where('price', 'BETWEEN', $priceArr);
  188. }
  189. }
  190. });
  191. if (!empty($orderby) && !empty($orderway)) {
  192. $orderby = $orderbyMap[$orderby] ?? 'weigh';
  193. $query = $query->order("{$orderby} {$orderway}");
  194. }
  195. $list = $query->paginate($pageSize);
  196. foreach ($list as $item) {
  197. $item->visible(explode(',', 'id,title,image,price,sales,views,description,lineation_price,is_hot,createtime'));
  198. }
  199. $this->success('', $list);
  200. }
  201. // 根据分类顶级ID 查询子集 和对应的商品
  202. public function getCategoryGoods()
  203. {
  204. $param = $this->request->param();
  205. $categoryId = $param['category_id'] ?? 0;
  206. // 验证器
  207. $validate = new \app\api\validate\Goods();
  208. if (!$validate->scene('getCategoryGoods')->check($param)) {
  209. $this->error($validate->getError());
  210. }
  211. // 查询子集分类信息
  212. $categoryChildIds = CategoryService::getCategoryChildrenIds($categoryId);
  213. // 查询所有直接子分类
  214. $children = [];
  215. foreach (CategoryService::getCategoryByIds($categoryChildIds) as $cat) {
  216. if (isset($cat['pid']) && $cat['pid'] == $categoryId) {
  217. $children[] = $cat;
  218. }
  219. }
  220. // 获取所有直接子分类ID
  221. $childrenIds = array_column($children, 'id');
  222. // 一次性查出所有相关分类下的所有商品(不分页)
  223. $allGoods = GoodService::getCategoryGoods($childrenIds); // 不分页查全部
  224. // 按分类分组,每组只保留4个
  225. $goodsByCategory = [];
  226. foreach ($allGoods as $goods) {
  227. if (empty($goods['category_ids'])) continue;
  228. $goodsCatIds = explode(',', $goods['category_ids']);
  229. foreach ($goodsCatIds as $catId) {
  230. $catId = intval($catId);
  231. if (in_array($catId, $childrenIds)) {
  232. if (!isset($goodsByCategory[$catId])) $goodsByCategory[$catId] = [];
  233. if (count($goodsByCategory[$catId]) < 4) {
  234. $goodsByCategory[$catId][] = $goods;
  235. }
  236. }
  237. }
  238. }
  239. // 组装返回
  240. $arrReturn = [];
  241. foreach ($children as $item) {
  242. $item['goods'] = $goodsByCategory[$item['id']] ?? [];
  243. $arrReturn[] = $item;
  244. }
  245. $this->success('', $arrReturn);
  246. }
  247. //获取小程序码
  248. public function getWxCode()
  249. {
  250. $goods_id = $this->request->post('goods_id');
  251. $version = $this->request->post('version', 'release');
  252. if (empty($goods_id)) {
  253. $this->error('参数错误');
  254. }
  255. $user_id = '';
  256. if ($this->auth->isLogin()) {
  257. $user_id = $this->auth->id;
  258. }
  259. $resource = '';
  260. $fileStream = (new \app\common\library\message\Mini)->getWxCodeUnlimited([
  261. 'scene' => "invite_id={$user_id}&goods_id={$goods_id}",
  262. 'env_version' => $version, //要打开的小程序版本。正式版为 release,体验版为 trial,开发版为 develop
  263. 'page' => 'pages/goods/detail',
  264. 'check_path' => false
  265. ]);
  266. if (is_null(json_decode($fileStream))) {
  267. try {
  268. $img = imagecreatefromstring($fileStream);
  269. ob_start();
  270. imagepng($img);
  271. $resource = ob_get_clean();
  272. } catch (\Exception $e) {
  273. \think\Log::write($e->getMessage());
  274. $this->error("获取微信二维码失败!");
  275. }
  276. } else {
  277. $config = get_addon_config('shop');
  278. if ($config['wxapp']) {
  279. $localFile = ROOT_PATH . 'public' . $config['wxapp'];
  280. if (is_file($localFile)) {
  281. $resource = file_get_contents($localFile);
  282. } else {
  283. $resource = Http::get(cdnurl($config['wxapp'], true));
  284. }
  285. }
  286. if (config('app_debug')) {
  287. Log::write($fileStream);
  288. }
  289. }
  290. if (!$resource) {
  291. Log::write($fileStream);
  292. $this->error("获取二维码失败!");
  293. }
  294. $base64_data = base64_encode($resource);
  295. $base64_file = 'data:image/jpg;base64,' . $base64_data;
  296. $this->success('获取成功', $base64_file);
  297. }
  298. }