Goods.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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. // 处理SKU的折扣价格
  96. $this->processSkuDiscountPrices($row);
  97. $row['comment_total'] = $comment_count;
  98. // 查询是否有定制规格
  99. $goodsCustomizedSpec = GoodService::getGoodsCustomizedSpec($id, 2);
  100. $row['is_customized_spec'] = !empty($goodsCustomizedSpec) ? 1: 0;
  101. $this->success('获取成功', $row);
  102. }
  103. public function getGoodsCustomizedSpec()
  104. {
  105. $id = $this->request->param('id/d');
  106. if (!$id) {
  107. $this->error('参数错误');
  108. }
  109. $row = (new GoodsModel())
  110. ->field('id,title,sub_title,type,category_ids,price,lineation_price,image')
  111. ->whereIn('status',[GoodsEnum::STATUS_ON_SALE,GoodsEnum::STATUS_SOLD_OUT])
  112. ->where('id', $id)->find();
  113. if (!$row) {
  114. $this->error('未找到该商品');
  115. }
  116. $row->sku_spec = SkuSpecService::getGoodsSkuSpec($id,2);
  117. // 要处理规格的图片
  118. // 这个错误是因为 $row->sku_spec 是一个重载属性(通过魔术方法 __get() 获取),不能直接通过引用修改。我们需要先将其转换为普通数组,处理后再赋值回去。
  119. if (!empty($row->sku_spec)) {
  120. $skuSpecData = $row->sku_spec; // 先转换为普通数组
  121. foreach ($skuSpecData as $key => &$item) {
  122. if (!empty($item['sku_value'])) {
  123. foreach ($item['sku_value'] as $k => &$v) {
  124. $v['image'] = empty($v['image']) ? '' : cdnurl($v['image'], true);
  125. }
  126. }
  127. }
  128. $row->sku_spec = $skuSpecData; // 处理完后重新赋值
  129. }
  130. $this->success('获取成功', $row);
  131. }
  132. //列表
  133. public function lists()
  134. {
  135. $param = $this->request->param();
  136. // 增加验证器处理
  137. $validate = new \app\api\validate\Goods();
  138. if (!$validate->scene('lists')->check($param)) {
  139. $this->error($validate->getError());
  140. }
  141. $pageSize = $param['pageSize'] ?? 10;
  142. $orderby = $param['orderby'] ?? 'weigh';
  143. $orderway = $param['orderway'] ?? 'desc';
  144. // 映射字段 $orderby weigh,sales,price,views,comments,created_at
  145. $orderbyMap = [
  146. 'weigh' => 'weigh',
  147. 'sales' => 'sales',
  148. 'views' => 'views',
  149. 'comments' => 'comments',
  150. 'created_at' => 'createtime',
  151. ];
  152. $query = GoodsModel::where(function ($query) use ($param) {
  153. $query->where('status',GoodsEnum::STATUS_ON_SALE);
  154. //关键词
  155. if (isset($param['keywords']) && !empty($param['keywords'])) {
  156. $query->where('title|keywords', 'like', '%' . $param['keywords'] . '%');
  157. $log = \app\common\model\SearchLog::getByKeywords($param['keywords']);
  158. if ($log) {
  159. $log->setInc("nums");
  160. } else {
  161. \app\common\model\SearchLog::create(['keywords' => $param['keyword'], 'nums' => 1, 'status' => 'hidden']);
  162. }
  163. }
  164. //分类
  165. if (isset($param['category_id']) && !empty($param['category_id'])) {
  166. $categoryIds = [];
  167. // 获取子集
  168. $categoryChildIds = \app\common\model\Category::getCategoryChildrenIds($param['category_id']);
  169. $categoryIds = array_merge($categoryChildIds, [$param['category_id']]);
  170. $query->where(function ($query) use ($categoryIds) {
  171. // 所有子分类使用 find_in_set or 匹配,亲测速度并不慢
  172. foreach ($categoryIds as $key => $category_id) {
  173. $query->whereOrRaw("find_in_set($category_id, category_ids)");
  174. }
  175. });
  176. }
  177. //属性
  178. if (isset($param['attributes']) && !empty($param['attributes'])) {
  179. $query->where('id', 'IN', \app\common\model\GoodsAttr::getGoodsIds($param['attributes']));
  180. }
  181. //品牌
  182. if (isset($param['brand_id']) && !empty($param['brand_id'])) {
  183. $query->where('brand_id', 'IN', $param['brand_id']);
  184. }
  185. //价格
  186. if (isset($param['price']) && !empty($param['price'])) {
  187. $priceArr = explode('-', $param['price']);
  188. if (count($priceArr) == 2) {
  189. if (isset($priceArr[0])) {
  190. $priceArr[0] = (float)$priceArr[0];
  191. }
  192. if (isset($priceArr[1])) {
  193. $priceArr[1] = (float)$priceArr[1];
  194. }
  195. $query->where('price', 'BETWEEN', $priceArr);
  196. }
  197. }
  198. });
  199. if (!empty($orderby) && !empty($orderway)) {
  200. $orderby = $orderbyMap[$orderby] ?? 'weigh';
  201. $query = $query->order("{$orderby} {$orderway}");
  202. }
  203. $list = $query->paginate($pageSize);
  204. foreach ($list as $item) {
  205. $item->visible(explode(',', 'id,title,image,price,sales,views,description,lineation_price,is_hot,createtime'));
  206. }
  207. $this->success('', $list);
  208. }
  209. // 根据分类顶级ID 查询子集 和对应的商品
  210. public function getCategoryGoods()
  211. {
  212. $param = $this->request->param();
  213. $categoryId = $param['category_id'] ?? 0;
  214. // 验证器
  215. $validate = new \app\api\validate\Goods();
  216. if (!$validate->scene('getCategoryGoods')->check($param)) {
  217. $this->error($validate->getError());
  218. }
  219. // 查询子集分类信息
  220. $categoryChildIds = CategoryService::getCategoryChildrenIds($categoryId);
  221. // 查询所有直接子分类
  222. $children = [];
  223. foreach (CategoryService::getCategoryByIds($categoryChildIds) as $cat) {
  224. if (isset($cat['pid']) && $cat['pid'] == $categoryId) {
  225. $children[] = $cat;
  226. }
  227. }
  228. // 获取所有直接子分类ID
  229. $childrenIds = array_column($children, 'id');
  230. // 一次性查出所有相关分类下的所有商品(不分页)
  231. $allGoods = GoodService::getCategoryGoods($childrenIds); // 不分页查全部
  232. // 按分类分组,每组只保留4个
  233. $goodsByCategory = [];
  234. foreach ($allGoods as $goods) {
  235. if (empty($goods['category_ids'])) continue;
  236. $goodsCatIds = explode(',', $goods['category_ids']);
  237. foreach ($goodsCatIds as $catId) {
  238. $catId = intval($catId);
  239. if (in_array($catId, $childrenIds)) {
  240. if (!isset($goodsByCategory[$catId])) $goodsByCategory[$catId] = [];
  241. if (count($goodsByCategory[$catId]) < 4) {
  242. $goodsByCategory[$catId][] = $goods;
  243. }
  244. }
  245. }
  246. }
  247. // 组装返回
  248. $arrReturn = [];
  249. foreach ($children as $item) {
  250. $item['goods'] = $goodsByCategory[$item['id']] ?? [];
  251. $arrReturn[] = $item;
  252. }
  253. $this->success('', $arrReturn);
  254. }
  255. //获取小程序码
  256. public function getWxCode()
  257. {
  258. $goods_id = $this->request->post('goods_id');
  259. $version = $this->request->post('version', 'trial');
  260. if (empty($goods_id)) {
  261. $this->error('参数错误');
  262. }
  263. $user_id = '';
  264. if ($this->auth->isLogin()) {
  265. $user_id = $this->auth->id;
  266. }
  267. $result = (new WechatService(Wechat::miniProgram()))->getWxCodeUnlimited([
  268. 'scene' => "id={$goods_id}&invite_id={$user_id}",
  269. 'env_version' => $version, //要打开的小程序版本。正式版为 release,体验版为 trial,开发版为 develop
  270. 'page' => 'pages/pro/detail',
  271. 'check_path' => false
  272. ]);
  273. // 检查返回结果是否为错误信息(数组格式)
  274. if (is_array($result)) {
  275. Log::write('微信小程序码获取失败: ' . json_encode($result));
  276. $this->error("获取微信二维码失败!" . ($result['errmsg'] ?? ''));
  277. }
  278. // 成功时,$result 就是图片的二进制buffer数据,直接进行base64编码
  279. if (empty($result) || !is_string($result)) {
  280. Log::write('微信小程序码返回数据无效');
  281. $this->error("获取微信二维码失败!");
  282. }
  283. $base64_data = base64_encode($result);
  284. $base64_file = 'data:image/png;base64,' . $base64_data;
  285. $this->success('获取成功', $base64_file);
  286. }
  287. /**
  288. * 处理SKU的折扣价格
  289. * 将活动折扣价格应用到对应的SKU中
  290. * @param array $goodsData 商品数据(引用传递)
  291. */
  292. private function processSkuDiscountPrices(&$goodsData)
  293. {
  294. // 如果没有折扣信息,直接返回
  295. if (empty($goodsData['discount_info']) || empty($goodsData['discount_info']['discount_info'])) {
  296. return;
  297. }
  298. // 如果没有SKU数据,直接返回
  299. if (empty($goodsData['sku'])) {
  300. return;
  301. }
  302. // 构建折扣SKU映射表:sku_id => 折扣信息
  303. $discountSkuMap = [];
  304. foreach ($goodsData['discount_info']['discount_info'] as $discountItem) {
  305. $skuId = $discountItem['sku_id'];
  306. $discountSkuMap[$skuId] = $discountItem;
  307. }
  308. // 处理商品的SKU数据
  309. foreach ($goodsData['sku'] as &$sku) {
  310. $skuId = $sku['id'];
  311. // 如果该SKU参与了折扣活动
  312. if (isset($discountSkuMap[$skuId])) {
  313. $discountInfo = $discountSkuMap[$skuId];
  314. // 保存原价到新字段
  315. $sku['original_price'] = $sku['price'];
  316. // 将折扣价格设置为SKU价格
  317. $sku['price'] = $discountInfo['discount_price'];
  318. // 添加折扣相关信息
  319. $sku['has_discount'] = true;
  320. $sku['discount'] = $discountInfo['discount'];
  321. $sku['discount_price'] = $discountInfo['discount_price'];
  322. $sku['discount_stocks'] = $discountInfo['discount_stocks'];
  323. // 计算优惠金额:原价 - 折扣价 = 用户节省的金额
  324. $sku['discount_amount'] =$discountInfo['discount_price'];
  325. } else {
  326. // 没有参与折扣活动的SKU
  327. $sku['has_discount'] = false;
  328. $sku['original_price'] = $sku['price'];
  329. $sku['discount'] = null;
  330. $sku['discount_price'] = null;
  331. $sku['discount_stocks'] = null;
  332. $sku['discount_amount'] = 0;
  333. }
  334. }
  335. // 处理单规格商品的主价格
  336. if ($goodsData['spec_type'] == 0 && !empty($goodsData['sku'])) {
  337. $firstSku = $goodsData['sku'][0];
  338. if ($firstSku['has_discount']) {
  339. // 保存商品原价
  340. $goodsData['original_price'] = $goodsData['price'];
  341. // 将商品价格设置为折扣价格
  342. $goodsData['price'] = $firstSku['discount_price'];
  343. }
  344. }
  345. }
  346. }