Goods.php 13 KB

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