Goods.php 13 KB

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