Goods.php 13 KB

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