Goods.php 14 KB

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