Goods.php 13 KB

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