Goods.php 12 KB

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