| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382 | <?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;use app\common\Service\DiscountService;use app\common\Service\Goods\CommentService;use app\common\facade\Wechat;use app\common\library\easywechatPlus\WechatService;/** * 商品接口 */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;  // 处理完后重新赋值        }        //         unset($item);        //服务保障        $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);        //好评度        $commentInfo = CommentService::getCommentCountAndFirstComment($id);        $comment_count = $commentInfo['total'] ?? 0;        $row->comment    = $commentInfo['comment'] ?? null;        $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']);        //查询折扣信息   以及倒计时        $row['discount_info'] = DiscountService::getGoodsDiscountDetail($row['id']);                // 处理SKU的折扣价格        $this->processSkuDiscountPrices($row);                $row['comment_total'] = $comment_count;        // 查询是否有定制规格        $goodsCustomizedSpec = GoodService::getGoodsCustomizedSpec($id, 2);        $row['is_customized_spec'] = !empty($goodsCustomizedSpec) ? 1: 0;        $this->success('获取成功', $row);    }    public function getGoodsCustomizedSpec()    {        $id = $this->request->param('id/d');        if (!$id) {            $this->error('参数错误');        }        $row = (new GoodsModel())        ->field('id,title,sub_title,type,category_ids,price,lineation_price,image')        ->whereIn('status',[GoodsEnum::STATUS_ON_SALE,GoodsEnum::STATUS_SOLD_OUT])        ->where('id', $id)->find();        if (!$row) {            $this->error('未找到该商品');        }        $row->sku_spec = SkuSpecService::getGoodsSkuSpec($id,2);        //  要处理规格的图片        // 这个错误是因为 $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;  // 处理完后重新赋值        }               $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';        // 映射字段 $orderby  weigh,sales,price,views,comments,created_at        $orderbyMap = [            'weigh' => 'weigh',            'sales' => 'sales',            'views' => 'views',            'comments' => 'comments',            'created_at' => 'createtime',        ];        $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)) {            $orderby = $orderbyMap[$orderby] ?? 'weigh';            $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', 'trial');        if (empty($goods_id)) {            $this->error('参数错误');        }        $user_id = '';        if ($this->auth->isLogin()) {            $user_id = $this->auth->id;        }                $result = (new WechatService(Wechat::miniProgram()))->getWxCodeUnlimited([            'scene'       => "id={$goods_id}&invite_id={$user_id}",            'env_version' => $version, //要打开的小程序版本。正式版为 release,体验版为 trial,开发版为 develop            'page'        => 'pages/pro/detail',            'check_path'  => false        ]);                // 检查返回结果是否为错误信息(数组格式)        if (is_array($result)) {            Log::write('微信小程序码获取失败: ' . json_encode($result));            $this->error("获取微信二维码失败!" . ($result['errmsg'] ?? ''));        }                // 成功时,$result 就是图片的二进制buffer数据,直接进行base64编码        if (empty($result) || !is_string($result)) {            Log::write('微信小程序码返回数据无效');            $this->error("获取微信二维码失败!");        }                $base64_data = base64_encode($result);        $base64_file = 'data:image/png;base64,' . $base64_data;        $this->success('获取成功', $base64_file);    }    /**     * 处理SKU的折扣价格     * 将活动折扣价格应用到对应的SKU中     * @param array $goodsData 商品数据(引用传递)     */    private function processSkuDiscountPrices(&$goodsData)    {        // 如果没有折扣信息,直接返回        if (empty($goodsData['discount_info']) || empty($goodsData['discount_info']['discount_info'])) {            return;        }        // 如果没有SKU数据,直接返回        if (empty($goodsData['sku'])) {            return;        }        // 构建折扣SKU映射表:sku_id => 折扣信息        $discountSkuMap = [];        foreach ($goodsData['discount_info']['discount_info'] as $discountItem) {            $skuId = $discountItem['sku_id'];            $discountSkuMap[$skuId] = $discountItem;        }        // 处理商品的SKU数据        foreach ($goodsData['sku'] as &$sku) {            $skuId = $sku['id'];                        // 如果该SKU参与了折扣活动            if (isset($discountSkuMap[$skuId])) {                $discountInfo = $discountSkuMap[$skuId];                                // 保存原价到新字段                $sku['original_price'] = $sku['price'];                                // 将折扣价格设置为SKU价格                $sku['price'] = $discountInfo['discount_price'];                                // 添加折扣相关信息                $sku['has_discount'] = true;                $sku['discount'] = $discountInfo['discount'];                $sku['discount_price'] = $discountInfo['discount_price'];                $sku['discount_stocks'] = $discountInfo['discount_stocks'];                // 计算优惠金额:原价 - 折扣价 = 用户节省的金额                $sku['discount_amount'] =$discountInfo['discount_price'];            } else {                // 没有参与折扣活动的SKU                $sku['has_discount'] = false;                $sku['original_price'] = $sku['price'];                $sku['discount'] = null;                $sku['discount_price'] = null;                $sku['discount_stocks'] = null;                $sku['discount_amount'] = 0;            }        }        // 处理单规格商品的主价格        if ($goodsData['spec_type'] == 0 && !empty($goodsData['sku'])) {            $firstSku = $goodsData['sku'][0];            if ($firstSku['has_discount']) {                // 保存商品原价                $goodsData['original_price'] = $goodsData['price'];                // 将商品价格设置为折扣价格                $goodsData['price'] = $firstSku['discount_price'];            }        }    }}
 |