Goods.php 14 KB

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