Goods.php 14 KB

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