Goods.php 15 KB

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