| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298 | <?phpnamespace app\api\controller;use app\common\Enum\GoodsEnum;use app\common\model\Goods as GoodsModel;use app\common\model\Guarantee;use app\common\model\Collect;use app\common\model\Comment;use app\common\model\AttributeValue;// use app\common\model\Coupon;// use app\common\model\CouponCondition;// use app\common\model\UserCoupon;use app\common\Service\Goods\GoodService;use fast\Http;use think\Log;use think\Db;use app\common\Service\SkuSpec as SkuSpecService;use app\common\Service\Goods\CategoryService;/** * 商品接口 */class Goods extends Base{    protected $noNeedLogin = [ 'detail', 'lists', 'getWxCode','getCategoryGoods'];    //详情    public function detail()    {        $id = $this->request->param('id/d');        if (!$id) {            $this->error('参数错误');        }        $row = (new GoodsModel())->with([            'Sku',            'Comment' => function ($query) {                $query->relation([                    'reply' => function ($user) {                        $user->with([                            'manage' => function ($u) {                                $u->field('id,nickname');                            }                        ]);                    }                ])->where('status', 'normal')->where('pid', 0)->field('id,goods_id,content,star,user_id,images,comments,createtime')->with([                    'User' => function ($u) {                        $u->field('id,nickname,avatar');                    }                ])->order('createtime', 'desc')->limit(10);            }        ])->whereIn('status',[GoodsEnum::STATUS_ON_SALE,GoodsEnum::STATUS_SOLD_OUT])->where('id', $id)->find();        if (!$row) {            $this->error('未找到该商品');        }        // 浏览次数        $row->setInc('views');        //收藏        if ($this->auth->isLogin()) {            $row->is_collect = !!(Collect::where('user_id', $this->auth->id)->where('goods_id', $id)->where('status', 1)->find());        } else {            $row->is_collect = false;        }        $row->sku_spec = SkuSpecService::getGoodsSkuSpec($id);        //  要处理规格的图片        // 这个错误是因为 $row->sku_spec 是一个重载属性(通过魔术方法 __get() 获取),不能直接通过引用修改。我们需要先将其转换为普通数组,处理后再赋值回去。        if (!empty($row->sku_spec)) {            $skuSpecData = $row->sku_spec;  // 先转换为普通数组            foreach ($skuSpecData as $key => &$item) {                if (!empty($item['sku_value'])) {                    foreach ($item['sku_value'] as $k => &$v) {                          $v['image'] = empty($v['image']) ? '' : cdnurl($v['image'], true);                    }                }            }            $row->sku_spec = $skuSpecData;  // 处理完后重新赋值        }        //         //服务保障        $row->guarantee = $row->guarantee_ids ? Guarantee::field('id,name,intro')->where('id', 'IN', $row->guarantee_ids)->where('status', 'normal')->select() : [];        //属性        $row->attributes = AttributeValue::getAttributeList($row->attribute_ids);        //好评度        $row->favor_rate = Comment::degree($id);        //评论        $comment = collection($row->comment)->toArray();        foreach ($comment as &$item) {            if ($item['user']) {                $item['user']['avatar'] = cdnurl($item['user']['avatar'], true);            }        }        $row->setRelation('comment', $comment);        unset($item);        //优惠券        // $conditions = CouponCondition::getGoodsCondition($id, $row->category_id, $row->brand_id);        // $sql = "condition_ids IS NULL OR condition_ids=''";        // foreach ($conditions as $key => $item) {        //     $sql .= " OR FIND_IN_SET('{$item['id']}',condition_ids)";        // }        // $couponList = Coupon::field('id,name,result,result_data,allow_num,begintime,endtime,use_times,received_num,give_num,mode,createtime')        //     ->where($sql)        //     ->where('is_open', 1)        //     ->where('is_private', 'no')        //     ->where('endtime', '>', time())        //     ->select();        // //已经登录,渲染已领的优惠券        // $coupon_ids = [];        // if ($this->auth->isLogin()) {        //     $coupon_ids = UserCoupon::where('user_id', $this->auth->id)->column('coupon_id');        // }        // foreach ($couponList as $key => &$item) {        //     Coupon::render($item, $coupon_ids);        //     $item->hidden(['received_num', 'give_num', 'condition_ids']);        // }        // $row->coupon = $couponList;        $row->visible(explode(',', 'id,title,type,spec_type,sub_title,category_ids,price,lineation_price,sales,views,is_hot,        image,content,images,sku_spec,sku,comment,is_collect,guarantee,attributes,favor_rate,coupon'));        $row = $row->toArray();        $row['content'] = \app\common\library\Service::formatTplToUniapp($row['content']);        $this->success('获取成功', $row);    }    //列表    public function lists()    {        $param = $this->request->param();        // 增加验证器处理        $validate = new \app\api\validate\Goods();        if (!$validate->scene('lists')->check($param)) {            $this->error($validate->getError());        }        $pageSize  = $param['pageSize'] ?? 10;        $orderby   = $param['orderby'] ?? 'weigh';        $orderway  = $param['orderway'] ?? 'desc';        $query = GoodsModel::where(function ($query) use ($param) {            $query->where('status',GoodsEnum::STATUS_ON_SALE);            //关键词            if (isset($param['keywords']) && !empty($param['keywords'])) {                $query->where('title|keywords', 'like', '%' . $param['keywords'] . '%');                $log = \app\common\model\SearchLog::getByKeywords($param['keywords']);                if ($log) {                    $log->setInc("nums");                } else {                    \app\common\model\SearchLog::create(['keywords' => $param['keyword'], 'nums' => 1, 'status' => 'hidden']);                }            }            //分类            if (isset($param['category_id']) && !empty($param['category_id'])) {                $categoryIds = [];                // 获取子集                $categoryChildIds = \app\common\model\Category::getCategoryChildrenIds($param['category_id']);                $categoryIds = array_merge($categoryChildIds, [$param['category_id']]);                $query->where(function ($query) use ($categoryIds) {                    // 所有子分类使用 find_in_set or 匹配,亲测速度并不慢                    foreach ($categoryIds as $key => $category_id) {                        $query->whereOrRaw("find_in_set($category_id, category_ids)");                    }                });                            }             //属性            if (isset($param['attributes']) && !empty($param['attributes'])) {                $query->where('id', 'IN', \app\common\model\GoodsAttr::getGoodsIds($param['attributes']));            }            //品牌            if (isset($param['brand_id']) && !empty($param['brand_id'])) {                $query->where('brand_id', 'IN', $param['brand_id']);            }            //价格            if (isset($param['price']) && !empty($param['price'])) {                $priceArr = explode('-', $param['price']);                if (count($priceArr) == 2) {                    if (isset($priceArr[0])) {                        $priceArr[0] = (float)$priceArr[0];                    }                    if (isset($priceArr[1])) {                        $priceArr[1] = (float)$priceArr[1];                    }                    $query->where('price', 'BETWEEN', $priceArr);                }            }        });        if (!empty($orderby) && !empty($orderway)) {            $query = $query->order("{$orderby} {$orderway}");        }        $list = $query->paginate($pageSize);        foreach ($list as $item) {            $item->visible(explode(',', 'id,title,image,price,sales,views,description,lineation_price,is_hot,createtime'));        }        $this->success('', $list);    }    //  根据分类顶级ID 查询子集 和对应的商品    public function getCategoryGoods()    {        $param = $this->request->param();        $categoryId = $param['category_id'] ?? 0;        // 验证器         $validate = new \app\api\validate\Goods();        if (!$validate->scene('getCategoryGoods')->check($param)) {            $this->error($validate->getError());        }        // 查询子集分类信息        $categoryChildIds = CategoryService::getCategoryChildrenIds($categoryId);        // 查询所有直接子分类        $children = [];        foreach (CategoryService::getCategoryByIds($categoryChildIds) as $cat) {            if (isset($cat['pid']) && $cat['pid'] == $categoryId) {                $children[] = $cat;            }        }        // 获取所有直接子分类ID        $childrenIds = array_column($children, 'id');        // 一次性查出所有相关分类下的所有商品(不分页)        $allGoods = GoodService::getCategoryGoods($childrenIds); // 不分页查全部        // 按分类分组,每组只保留4个        $goodsByCategory = [];        foreach ($allGoods as $goods) {            if (empty($goods['category_ids'])) continue;            $goodsCatIds = explode(',', $goods['category_ids']);            foreach ($goodsCatIds as $catId) {                $catId = intval($catId);                if (in_array($catId, $childrenIds)) {                    if (!isset($goodsByCategory[$catId])) $goodsByCategory[$catId] = [];                    if (count($goodsByCategory[$catId]) < 4) {                        $goodsByCategory[$catId][] = $goods;                    }                }            }        }        // 组装返回        $arrReturn = [];        foreach ($children as $item) {            $item['goods'] = $goodsByCategory[$item['id']] ?? [];            $arrReturn[] = $item;        }        $this->success('', $arrReturn);    }    //获取小程序码    public function getWxCode()    {        $goods_id = $this->request->post('goods_id');        $version = $this->request->post('version', 'release');        if (empty($goods_id)) {            $this->error('参数错误');        }        $user_id = '';        if ($this->auth->isLogin()) {            $user_id = $this->auth->id;        }        $resource = '';        $fileStream = (new \app\common\library\message\Mini)->getWxCodeUnlimited([            'scene'       => "invite_id={$user_id}&goods_id={$goods_id}",            'env_version' => $version, //要打开的小程序版本。正式版为 release,体验版为 trial,开发版为 develop            'page'        => 'pages/goods/detail',            'check_path'  => false        ]);        if (is_null(json_decode($fileStream))) {            try {                $img = imagecreatefromstring($fileStream);                ob_start();                imagepng($img);                $resource = ob_get_clean();            } catch (\Exception $e) {                \think\Log::write($e->getMessage());                $this->error("获取微信二维码失败!");            }        } else {            $config = get_addon_config('shop');            if ($config['wxapp']) {                $localFile = ROOT_PATH . 'public' . $config['wxapp'];                if (is_file($localFile)) {                    $resource = file_get_contents($localFile);                } else {                    $resource = Http::get(cdnurl($config['wxapp'], true));                }            }            if (config('app_debug')) {                Log::write($fileStream);            }        }        if (!$resource) {            Log::write($fileStream);            $this->error("获取二维码失败!");        }        $base64_data = base64_encode($resource);        $base64_file = 'data:image/jpg;base64,' . $base64_data;        $this->success('获取成功', $base64_file);    }}
 |