文件

576 行
21 KiB
PHP

此文件含有模棱两可的 Unicode 字符

此文件含有可能会与其他字符混淆的 Unicode 字符。 如果您是想特意这样的,可以安全地忽略该警告。 使用 Escape 按钮显示他们。

<?php
namespace app\api\controller;
use think\Db;
use app\common\library\NationalArea;
/**
* 用户端 · 首页与展示(Module-HOME)
* 路由:
* GET /api/v1/home/banners H1 轮播广告位
* GET /api/v1/home/categories H2 分类导航(含二级分类树与实拍图)
* GET /api/v1/home/search/hot H3 热门搜索
* GET /api/v1/home/feed H4 信息流(支持全国省/市/区县筛选 + 一二级分类筛选 + 距离排序)
* GET /api/v1/home/areas H5 全国服务区域列表(平铺省/市/区县)
* GET /api/v1/home/locate H6 按定位坐标匹配全国当前区县
*/
class Home extends V1
{
/**
* H1 首页轮播广告位接口
* GET /api/v1/home/banners → [{id,title,image,link,color}]
* 规则:仅返回 enabled=1,按 sort asc, id desc 排序;若配置了相对路径图片,则自动使用 cdnurl 拼接完整域名地址
*
* @return void
*/
public function banners()
{
$rows = Db::name('fc_banner')
->where('enabled', 1)
->order('sort asc, id desc')
->select();
$list = [];
foreach ($rows as $row) {
$image = (string)$row['image'];
if ($image !== '' && !preg_match('/^https?:\/\//i', $image)) {
$image = cdnurl($image, true);
}
$list[] = [
'id' => (int)$row['id'],
'title' => (string)$row['title'],
'image' => $image,
'link' => (string)$row['link'],
'color' => (string)$row['color'],
];
}
$this->ok($list);
}
/**
* H2 分类导航(一级分类 + 二级分类树,附带农产品实拍图)
* GET /api/v1/home/categories → [{id,pid,name,iconKey,icon,image,color,count,children:[...]}]
* 规则:仅 enabled=1,按 sort asc;一级分类下挂 children 二级分类列表
*
* @return void
*/
public function categories()
{
$rows = Db::name('fc_category')
->where('enabled', 1)
->order('pid asc, sort asc, id asc')
->select();
$parents = [];
$childrenMap = [];
foreach ($rows as $row) {
$id = (int)$row['id'];
$pid = isset($row['pid']) ? (int)$row['pid'] : 0;
$iconKey = (string)$row['icon_key'];
$rawImage = isset($row['image']) ? (string)$row['image'] : '';
$iconPath = $this->resolveCategoryIconPath($id, $iconKey, $rawImage);
$imagePath = $rawImage !== '' ? $rawImage : $iconPath;
$item = [
'id' => $id,
'pid' => $pid,
'name' => (string)$row['name'],
'iconKey' => $iconKey,
'icon' => $iconPath,
'image' => $imagePath,
'color' => (string)$row['color'],
'kind' => isset($row['kind']) && $row['kind'] === 'farm' ? 'farm' : 'general',
'count' => (int)$row['post_count'],
'isHome' => isset($row['is_home']) ? (int)$row['is_home'] : 0,
];
if ($pid === 0) {
$item['children'] = [];
$parents[$id] = $item;
} else {
if (!isset($childrenMap[$pid])) {
$childrenMap[$pid] = [];
}
$childrenMap[$pid][] = $item;
}
}
$list = [];
foreach ($parents as $pid => $parent) {
$parent['children'] = isset($childrenMap[$pid]) ? $childrenMap[$pid] : [];
$list[] = $parent;
}
// 兜底:若数据库中仅有未挂载父级的孤立分类,直接返回
if (empty($list) && !empty($childrenMap)) {
foreach ($childrenMap as $group) {
foreach ($group as $c) {
$c['children'] = [];
$list[] = $c;
}
}
}
$this->ok($list);
}
/**
* 获取首页金刚区推荐二级分类列表
* GET /api/v1/home/nav-categories → [{id,pid,name,iconKey,icon,image,color,isHome}]
* 规则:优先取后台设置 is_home=1 且 enabled=1 的二级分类,不足8个时智能补充热门果蔬二级分类,输出精准8宫格
*
* @return void
*/
public function navCategories()
{
// 1. 优先获取后台标记为推荐至首页金刚区的二级分类 (is_home=1, pid>0)
$homeRows = \think\Db::name('fc_category')
->where('enabled', 1)
->where('pid', '>', 0)
->where('is_home', 1)
->order('sort asc, id asc')
->limit(8)
->select();
$selectedIds = array_column($homeRows, 'id');
$list = $homeRows;
// 2. 若配置不足8个,则从高频果蔬二级分类中自动补齐至8个
if (count($list) < 8) {
$needed = 8 - count($list);
$query = \think\Db::name('fc_category')
->where('enabled', 1)
->where('pid', 'in', [1, 2]); // 优先从蔬菜(1)和水果(2)中补充
if (!empty($selectedIds)) {
$query->whereNotIn('id', $selectedIds);
}
$moreRows = $query->order('sort asc, post_count desc, id asc')
->limit($needed)
->select();
$list = array_merge($list, $moreRows);
}
$res = [];
foreach ($list as $row) {
$id = (int)$row['id'];
$pid = (int)$row['pid'];
$iconKey = (string)$row['icon_key'];
$rawImage = isset($row['image']) ? (string)$row['image'] : '';
$iconPath = $this->resolveCategoryIconPath($id, $iconKey, $rawImage);
$imagePath = $rawImage !== '' ? $rawImage : $iconPath;
$res[] = [
'id' => $id,
'pid' => $pid,
'name' => (string)$row['name'],
'iconKey' => $iconKey,
'icon' => $iconPath,
'image' => $imagePath,
'color' => (string)$row['color'],
'kind' => isset($row['kind']) && $row['kind'] === 'farm' ? 'farm' : 'general',
'isHome' => isset($row['is_home']) ? (int)$row['is_home'] : 0,
];
}
$this->ok($res);
}
/**
* H3 热门搜索
* GET /api/v1/home/search/hot → [string]
* 规则:读配置 home.hotKeywords,未配置则返回农产品热门搜索词
*
* @return void
*/
public function hotKeywords()
{
$default = ['有机花菜', '高山大白菜', '红富士苹果', '大棚草莓', '修文猕猴桃'];
$keywords = $this->cfg('home.hotKeywords', $default);
if (!is_array($keywords) || !$keywords) {
$keywords = $default;
}
$this->ok(array_values($keywords));
}
/**
* H5 全国服务区域列表(平铺:每条记录自带省 / 市 / 区县)
* GET /api/v1/home/areas → [{id,province,city,district,lat,lng}]
* 规则:默认开放全国所有省市区县,供小程序端省/市/区三级联动选择。
*
* @return void
*/
public function areas()
{
$list = NationalArea::all();
$this->ok($list);
}
/**
* H6 按定位坐标匹配全国当前服务区域(省/市/区县)
* GET /api/v1/home/locate?lat=&lng= → {areaId,province,city,district,distance}
* 规则:在全国区县字典中匹配距离当前坐标最近的区县。
*
* @return void
*/
public function locate()
{
$lat = $this->input('lat', null);
$lng = $this->input('lng', null);
if (!is_numeric($lat) || !is_numeric($lng)) {
$this->ok(null);
}
$lat = (float)$lat;
$lng = (float)$lng;
if ($lat < -90 || $lat > 90 || $lng < -180 || $lng > 180 || ($lat == 0.0 && $lng == 0.0)) {
$this->ok(null);
}
$matched = NationalArea::locate($lat, $lng);
$this->ok($matched);
}
/**
* H4 信息流
* GET /api/v1/home/feed {categoryId?,subCategoryId?,keyword?,province?,city?,areaId?,area?,sort?,lat?,lng?,page,size}
* → {list,page,size,total,hasMore}
* 规则:仅 audit_status=1 AND status=1 AND deletetime IS NULL
*
* @return void
*/
public function feed()
{
list($page, $size) = $this->pager();
$categoryId = (int)$this->input('categoryId', 0);
$subCategoryId = (int)$this->input('subCategoryId', 0);
$keyword = trim((string)$this->input('keyword', ''));
$province = trim((string)$this->input('province', ''));
$city = trim((string)$this->input('city', ''));
$area = trim((string)$this->input('area', ''));
$areaId = (int)$this->input('areaId', 0);
if (!$areaId) {
$areaId = (int)$this->input('districtId', 0);
}
$sort = (string)$this->input('sort', '');
foreach (['province', 'city', 'area', 'keyword', 'sort'] as $strVar) {
if ($$strVar === 'undefined' || $$strVar === 'null') {
$$strVar = '';
}
}
if (in_array($province, ['全部', '全国', '不限'], true)) {
$province = '';
}
if (in_array($city, ['全部', '全市', '全州', '不限'], true)) {
$city = '';
}
if (in_array($area, ['全部', '全区', '全城', '全国', '不限'], true)) {
$area = '';
}
// 若传入的 categoryId 本身是二级分类(pid > 0),自动作为二级分类匹配
$catRow = $categoryId > 0 ? Db::name('fc_category')->where('id', $categoryId)->find() : null;
$isSubCatId = $catRow && !empty($catRow['pid']) && (int)$catRow['pid'] > 0;
$applyCategory = function ($q) use ($categoryId, $subCategoryId, $isSubCatId) {
if ($subCategoryId > 0) {
$q->where(function ($w) use ($subCategoryId) {
$w->where('sub_category_id', $subCategoryId)->whereOr('category_id', $subCategoryId);
});
return;
}
if ($categoryId > 0) {
if ($isSubCatId) {
$q->where(function ($w) use ($categoryId) {
$w->where('sub_category_id', $categoryId)->whereOr('category_id', $categoryId);
});
} else {
$q->where('category_id', $categoryId);
}
}
};
$applyArea = function ($q) use ($province, $city, $area, $areaId) {
if ($areaId > 0) {
$natRow = NationalArea::findById($areaId);
if (!$natRow) {
$natRow = Db::name('fc_area')->where('id', $areaId)->find();
}
if ($natRow) {
$q->where(function ($w) use ($natRow) {
$w->where('district_id', (int)$natRow['id'])->whereOr('area', (string)$natRow['district']);
});
} else {
$q->where('district_id', $areaId);
}
return;
}
if ($area !== '') {
$q->where('area', $area);
return;
}
if ($city !== '') {
$cityDistricts = [];
foreach (NationalArea::all() as $item) {
if ($item['city'] === $city || rtrim($item['city'], '市') === rtrim($city, '市')) {
$cityDistricts[] = $item['district'];
}
}
$q->where(function ($w) use ($city, $cityDistricts) {
$w->where('city', $city);
if (!empty($cityDistricts)) {
$w->whereOr('area', 'in', array_slice(array_unique($cityDistricts), 0, 100));
}
});
return;
}
if ($province !== '') {
$q->where('province', $province);
}
};
$applyPaid = function ($q) {
$q->where(function ($w) {
$w->where('amount', 'null')->whereOr('amount', '<=', 0)->whereOr('is_paid', 1);
});
};
$query = Db::name('fc_post')
->where('audit_status', 1)
->where('status', 1)
->whereNull('deletetime');
$applyCategory($query);
if ($keyword !== '') {
$query->where('title', 'like', '%' . $keyword . '%');
}
$applyArea($query);
$applyPaid($query);
$counter = Db::name('fc_post')
->where('audit_status', 1)
->where('status', 1)
->whereNull('deletetime');
$applyCategory($counter);
if ($keyword !== '') {
$counter->where('title', 'like', '%' . $keyword . '%');
}
$applyArea($counter);
$applyPaid($counter);
$total = $counter->count();
if ($sort === 'nearby') {
$rows = $query->order('createtime desc')->select();
$items = [];
foreach ($rows as $row) {
$items[] = [
'item' => $this->buildPost($row),
'distance' => $this->postDistance($row),
'ct' => (int)$row['createtime'],
];
}
usort($items, function ($a, $b) {
$na = $a['distance'] === null;
$nb = $b['distance'] === null;
if ($na !== $nb) {
return $na ? 1 : -1;
}
if (!$na && $a['distance'] != $b['distance']) {
return $a['distance'] < $b['distance'] ? -1 : 1;
}
return $b['ct'] - $a['ct'];
});
$list = [];
foreach ($items as $it) {
$list[] = $it['item'];
}
$this->ok($this->paginateArray($list, $page, $size));
}
if ($sort === 'price_desc') {
$query->order('is_top desc, price desc');
} elseif ($sort === 'price' || $sort === 'price_asc') {
$query->order('is_top desc, price asc');
} elseif ($sort === 'hot') {
$query->order('is_top desc, views desc');
} else {
$query->order('is_top desc, createtime desc');
}
$rows = $query->page($page, $size)->select();
$list = [];
foreach ($rows as $row) {
$list[] = $this->buildPost($row);
}
$this->ok($this->paginate($list, $total, $page, $size));
}
/**
* Haversine 距离(km,一位小数)
* @return float
*/
protected function haversine($lat1, $lng1, $lat2, $lng2)
{
$earth = 6371.0;
$rad = M_PI / 180;
$dLat = ($lat2 - $lat1) * $rad;
$dLng = ($lng2 - $lng1) * $rad;
$a = sin($dLat / 2) * sin($dLat / 2)
+ cos($lat1 * $rad) * cos($lat2 * $rad) * sin($dLng / 2) * sin($dLng / 2);
$c = 2 * asin(min(1.0, sqrt($a)));
return round($earth * $c, 1);
}
/**
* 列表项距离(km,一位小数;请求未带坐标 / 信息未定位 = null)
* @param array $row fc_post 行
* @return float|null
*/
protected function postDistance($row)
{
$lat = $this->input('lat', null);
$lng = $this->input('lng', null);
if (!is_numeric($lat) || !is_numeric($lng)) {
return null;
}
$lat = (float)$lat;
$lng = (float)$lng;
if ($lat == 0.0 && $lng == 0.0) {
return null;
}
$plat = isset($row['lat']) && $row['lat'] !== null ? (float)$row['lat'] : 0.0;
$plng = isset($row['lng']) && $row['lng'] !== null ? (float)$row['lng'] : 0.0;
if ($plat == 0.0 && $plng == 0.0) {
return null;
}
return $this->haversine($lat, $lng, $plat, $plng);
}
/**
* 组装 Post 结构(含二级分类与农产品属性)
* @param array $row fc_post 行
* @return array
*/
protected function buildPost($row)
{
$categoryName = '';
if (!empty($row['category_id'])) {
$cat = Db::name('fc_category')->where('id', $row['category_id'])->find();
if ($cat) {
$categoryName = (string)$cat['name'];
}
}
$subCategoryId = isset($row['sub_category_id']) ? (int)$row['sub_category_id'] : 0;
$subCategoryName = '';
if ($subCategoryId > 0) {
$subCat = Db::name('fc_category')->where('id', $subCategoryId)->find();
if ($subCat) {
$subCategoryName = (string)$subCat['name'];
}
}
$publisher = ['id' => 0, 'name' => '', 'avatar' => '', 'isMerchant' => false, 'verified' => false];
if (!empty($row['user_id'])) {
$pub = Db::name('user')->where('id', $row['user_id'])->find();
if ($pub) {
$pubExt = Db::name('fc_user_ext')->where('user_id', $pub['id'])->find();
$isMerchant = $pubExt && (int)$pubExt['user_type'] === 2;
$publisher = [
'id' => (int)$pub['id'],
'name' => (string)$pub['nickname'],
'avatar' => (string)$pub['avatar'],
'isMerchant' => (bool)$isMerchant,
'verified' => (bool)$isMerchant,
];
}
}
$tags = [];
if (!empty($row['tags'])) {
foreach (explode(',', (string)$row['tags']) as $tag) {
$tag = trim($tag);
if ($tag !== '') {
$tags[] = $tag;
}
}
}
return [
'id' => (int)$row['id'],
'categoryId' => (int)$row['category_id'],
'categoryName' => $categoryName,
'subCategoryId' => $subCategoryId,
'subCategoryName' => $subCategoryName,
'title' => (string)$row['title'],
'content' => (string)$row['content'],
'cover' => (string)$row['cover'],
'price' => (float)$row['price'],
'priceUnit' => (string)$row['price_unit'],
'province' => isset($row['province']) ? (string)$row['province'] : '',
'city' => isset($row['city']) ? (string)$row['city'] : '',
'area' => (string)$row['area'],
'areaId' => (int)$row['district_id'],
'address' => (string)$row['address'],
'plantArea' => isset($row['plant_area']) ? (string)$row['plant_area'] : '',
'harvestTime' => isset($row['harvest_time']) ? (string)$row['harvest_time'] : '',
'outputRange' => isset($row['output_range']) ? (string)$row['output_range'] : '',
'contact' => $this->maskPhone($row['phone']),
'views' => (int)$row['views'],
'likes' => (int)$row['likes'],
'isPaid' => (int)$row['is_paid'] === 1,
'isTop' => (int)$row['is_top'] === 1,
'auditStatus' => (int)$row['audit_status'],
'createdAt' => $this->iso($row['createtime']),
'tags' => $tags,
'publisher' => $publisher,
'commentCount' => (int)$row['comment_count'],
'distance' => $this->postDistance($row),
];
}
/**
* 全兼容分类图标/实拍图路径解析
* @param int $id 分类ID
* @param string $iconKey 分类图标键名或图片路径
* @param string $image 分类实拍图路径
* @return string
*/
protected function resolveCategoryIconPath($id, $iconKey = '', $image = '')
{
if ($image !== '' && preg_match('/^https?:\/\/|^\/uploads\/|^\/static\//i', $image)) {
return $image;
}
if ($iconKey !== '') {
if (preg_match('/^https?:\/\/|^\/uploads\/|^\/static\//i', $iconKey)) {
return $iconKey;
}
$iconFileName = (strpos($iconKey, '.') !== false) ? $iconKey : $iconKey . '.png';
if (file_exists(ROOT_PATH . 'public/static/categories/' . $iconFileName)) {
return '/static/categories/' . $iconFileName;
}
if (file_exists(ROOT_PATH . 'public/static/icons/' . $iconFileName)) {
return '/static/icons/' . $iconFileName;
}
}
return '/static/categories/' . $this->iconFile($id);
}
/**
* 分类 id → 默认图标文件名
* @param int $id
* @return string
*/
protected function iconFile($id)
{
$map = [
1 => 'cat-veg.png',
2 => 'cat-fruit.png',
];
return isset($map[$id]) ? $map[$id] : 'cat-veg.png';
}
}