Goods.php 10 KB

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