Goods.php 10 KB

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