Goods.php 12 KB

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