文件
yjyf/server/application/api/controller/Home.php

1678 行
66 KiB
PHP

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

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

<?php
namespace app\api\controller;
use think\Db;
/**
* 首页 / 服务类目 / 服务项目 / 费用试算
*/
class Home extends Base
{
protected $noNeedLogin = ['index', 'feed', 'cats', 'services', 'detail', 'calc', 'specs', 'masterCount', 'orderCase'];
/**
* 首页聚合:类目 + 热门服务 + 我的角标
*/
public function index()
{
$rawCats = Db::name('service_cat')
->field('id,name,icon')
->where('status', 'normal')
->order('weigh desc,id asc')
->select();
$cats = $this->formatCats($rawCats);
// 热门服务多维推荐计算:
// 维度1: 真实完工订单量 (fa_order status=8)
// 维度2: 基础销量 sales
// 维度3: 明码标价一口价优先 (fixed)
// 维度4: 品类均衡覆盖 (避免单一类目倾斜,各高频类目精选优质项目)
// 维度5: 后台置顶权重 weigh
$orderCounts = Db::name('order')
->where('status', 8)
->group('service_id')
->column('count(*)', 'service_id');
$candidateServices = Db::name('service')
->alias('s')
->join('service_cat c', 's.cat_id = c.id', 'LEFT')
->field('s.id,s.cat_id,s.name,s.price_type,s.base_price,s.max_price,s.unit,s.image,s.sales,s.weigh,c.name as cat_name,c.icon as cat_icon')
->where('s.status', 'normal')
->where('s.cat_id', '<>', 15) // 排除“其它”类目
->select();
// 综合打分
foreach ($candidateServices as &$cs) {
$sid = (int)$cs['id'];
$realOrders = isset($orderCounts[$sid]) ? (int)$orderCounts[$sid] : 0;
$cs['real_orders'] = $realOrders;
$cs['score'] = ($realOrders * 15) + ((int)$cs['sales'] * 2) + ($cs['price_type'] === 'fixed' ? 25 : 0) + (int)$cs['weigh'];
// 推荐标签
if ($realOrders > 0) {
$cs['tag'] = '热销爆款';
} elseif ($cs['price_type'] === 'fixed') {
$cs['tag'] = '明码标价';
} else {
$cs['tag'] = '好评优选';
}
}
unset($cs);
// 按得分降序排列
usort($candidateServices, function($a, $b) {
return $b['score'] <=> $a['score'];
});
// 品类均衡采样:每个类目优先入选 1 个,最多 2 个,输出 6~8 项
$hotList = [];
$catSeen = [];
// 第一轮:每个类目选最热 1 项
foreach ($candidateServices as $cs) {
$cid = (int)$cs['cat_id'];
if (!isset($catSeen[$cid])) {
$hotList[] = $cs;
$catSeen[$cid] = 1;
}
if (count($hotList) >= 6) break;
}
// 若不足 6 项,允许热门类目补充第 2 项
if (count($hotList) < 6) {
foreach ($candidateServices as $cs) {
if (!in_array($cs['id'], array_column($hotList, 'id'), true)) {
$hotList[] = $cs;
}
if (count($hotList) >= 6) break;
}
}
// 组装大类 -> 具体服务项目二级联动映射表
$catServices = [];
foreach ($candidateServices as $csItem) {
$cidKey = (int)$csItem['cat_id'];
if (!isset($catServices[$cidKey])) {
$catServices[$cidKey] = [];
}
$catServices[$cidKey][] = [
'id' => (int)$csItem['id'],
'cat_id' => $cidKey,
'name' => (string)$csItem['name'],
'base_price' => (float)$csItem['base_price'],
'unit' => (string)($csItem['unit'] ?: '件'),
];
}
// 提取真实晒单覆盖区域(直接取自 fa_showcase 表,确保每个区域筛选均有真实晒单数据)
$showcaseRegions = Db::name('showcase')
->where('status', 'normal')
->where('region', '<>', '')
->group('region')
->column('region');
$regions = array_values(array_unique(array_filter($showcaseRegions ?: [])));
// 提取晒单表真实覆盖的服务项目(用于【服务动态】下“项目 ▼”联动过滤)
$showcaseServiceRows = Db::name('showcase')
->field('service_id,service_name,cat_id,cat_name')
->where('status', 'normal')
->where('service_id', '>', 0)
->group('service_id,service_name,cat_id,cat_name')
->select();
$showcaseServices = [];
foreach ($showcaseServiceRows as $ssr) {
$showcaseServices[] = [
'id' => (int)$ssr['service_id'],
'cat_id' => (int)$ssr['cat_id'],
'name' => (string)$ssr['service_name'],
'cat_name' => (string)$ssr['cat_name'],
];
}
// 提取工项字典表 fa_service_type 真实启用工项(用于【热门推荐】下“工项 ▼”过滤)
$rawTypeDict = Db::name('service_type')
->field('code,name')
->where('status', 'normal')
->where('code', '<>', 'other')
->order('weigh desc, id asc')
->select();
$serviceTypesDict = [];
foreach ($rawTypeDict as $rtd) {
$code = (string)$rtd['code'];
if ($code === 'deliver_downstairs') {
continue;
}
$label = (string)$rtd['name'];
if ($code === 'deliver_install') {
$label = '送货并安装';
}
$serviceTypesDict[] = [
'code' => $code,
'name' => $label,
];
}
$data = [
'cats' => $cats,
'cat_services' => $catServices,
'showcase_services' => $showcaseServices,
'service_types_dict' => $serviceTypesDict,
'regions' => $regions,
'hot' => $this->formatServices($hotList),
'banners' => $this->banners(),
'assures' => $this->configList('home_assure', '平台认证,先行赔付,极速上门,售后无忧'),
'tutorial' => $this->tutorial(),
'badge' => ['coupon' => 0, 'unread' => 0],
];
if ($this->auth->isLogin()) {
$uid = $this->uid();
$data['badge']['coupon'] = (int)Db::name('user_coupon')->where('user_id', $uid)->where('status', 'unused')->count();
$data['badge']['unread'] = (int)Db::name('message')->where('receive_type', 'user')->where('receive_id', $uid)->where('is_read', 0)->count();
}
// 全平台用户主动晒单动态流(直接查询独立晒单表 fa_showcase,物理隔离订单隐私数据)
$showcaseRows = Db::name('showcase')
->field('id,cat_id,cat_name,service_id,service_name,region,cover_image,user_name,score,tags,content,createtime')
->where('status', 'normal')
->order('createtime desc, id desc')
->limit(10)
->select();
$recentOrders = [];
foreach ($showcaseRows as $sc) {
$revTags = [];
if (!empty($sc['tags'])) {
$decTags = json_decode((string)$sc['tags'], true);
$revTags = is_array($decTags) ? $decTags : array_values(array_filter(explode(',', (string)$sc['tags'])));
}
$recentOrders[] = [
'id' => (int)$sc['id'],
'service_id' => (int)$sc['service_id'],
'service_name' => $sc['service_name'] ?: '上门服务',
'cat_name' => $sc['cat_name'] ?: '服务',
'cat_id' => (int)$sc['cat_id'],
'image_url' => $sc['cover_image'] ? cdnurl($sc['cover_image'], true) : '',
'status_text' => '业主晒单',
'location' => $sc['region'] ?: '同城服务',
'time_ago' => $this->timeAgo((int)$sc['createtime']),
'user_name' => $sc['user_name'] ?: '匿名业主',
'review_score' => (int)$sc['score'] ?: 5,
'review_content' => $sc['content'] ?: '师傅准时上门,施工专业细致,安装效果很满意!',
'review_tags' => array_slice($revTags, 0, 2),
];
}
$data['recent_orders'] = $recentOrders;
$this->success('', $data);
}
/**
* 首页下方列表区域:分页、二级项目筛选、区域过滤与多维排序接口(支持【热门推荐】与【服务动态】双 Tab)
*/
public function feed()
{
$tab = trim((string)$this->request->param('tab', 'hot'));
$catId = (int)$this->request->param('cat_id', 0);
$serviceId = (int)$this->request->param('service_id', 0);
$serviceType = trim((string)$this->request->param('service_type', ''));
$region = trim((string)$this->request->param('region', ''));
$sort = trim((string)$this->request->param('sort', 'default'));
$priceRange = trim((string)$this->request->param('price_range', 'all'));
$minPrice = $this->request->param('min_price', '');
$maxPrice = $this->request->param('max_price', '');
$unitFilter = trim((string)$this->request->param('unit', ''));
$priceTypeFilter = trim((string)$this->request->param('price_type', ''));
$tag = trim((string)$this->request->param('tag', ''));
$onlyFixed = (int)$this->request->param('only_fixed', 0);
$hasImage = (int)$this->request->param('has_image', 0);
$page = max(1, (int)$this->request->param('page', 1));
$limit = min(20, max(1, (int)$this->request->param('limit', 6)));
if ($tab === 'cases') {
$buildQuery = function () use ($catId, $serviceId, $region, $tag, $hasImage, $priceRange, $minPrice, $maxPrice) {
$q = Db::name('showcase')
->alias('sc')
->join('service s', 'sc.service_id = s.id', 'LEFT')
->field('sc.id,sc.cat_id,sc.cat_name,sc.service_id,sc.service_name,sc.region,sc.cover_image,sc.images,sc.user_name,sc.score,sc.tags,sc.content,sc.master_score,sc.createtime,s.base_price,s.sales')
->where('sc.status', 'normal');
if ($catId > 0) {
$q->where('sc.cat_id', $catId);
}
if ($serviceId > 0) {
$q->where('sc.service_id', $serviceId);
}
if ($region !== '' && $region !== 'all') {
$q->where('sc.region', $region);
}
if ($tag !== '' && $tag !== 'all') {
$q->where('sc.tags', 'like', '%' . $tag . '%');
}
if ($hasImage === 1) {
$q->where('sc.images', '<>', '')->where('sc.images', '<>', '[]');
}
if ($minPrice !== '' && is_numeric($minPrice)) {
$q->where('s.base_price', '>=', (float)$minPrice);
}
if ($maxPrice !== '' && is_numeric($maxPrice)) {
$q->where('s.base_price', '<=', (float)$maxPrice);
}
if ($priceRange === 'under_80') {
$q->where('s.base_price', '<', 80);
} elseif ($priceRange === '80_120') {
$q->where('s.base_price', '>=', 80)->where('s.base_price', '<=', 120);
} elseif ($priceRange === '120_up') {
$q->where('s.base_price', '>', 120);
} elseif ($priceRange === '0_80') {
$q->where('s.base_price', '<=', 80);
} elseif ($priceRange === '80_150') {
$q->where('s.base_price', '>', 80)->where('s.base_price', '<=', 150);
} elseif ($priceRange === '150_up') {
$q->where('s.base_price', '>', 150);
}
return $q;
};
$total = (int)$buildQuery()->count();
$q = $buildQuery();
if ($sort === 'sales') {
$q->order('s.sales desc, sc.createtime desc, sc.id desc');
} elseif ($sort === 'price_asc') {
$q->order('s.base_price asc, sc.createtime desc, sc.id desc');
} elseif ($sort === 'price_desc') {
$q->order('s.base_price desc, sc.createtime desc, sc.id desc');
} elseif ($sort === 'score') {
$q->order('sc.score desc, sc.master_score desc, sc.createtime desc, sc.id desc');
} else {
$q->order('sc.createtime desc, sc.id desc');
}
$rows = $q->page($page, $limit)->select();
$list = [];
foreach ($rows as $sc) {
$revTags = [];
if (!empty($sc['tags'])) {
$decTags = json_decode((string)$sc['tags'], true);
$revTags = is_array($decTags) ? $decTags : array_values(array_filter(explode(',', (string)$sc['tags'])));
}
$list[] = [
'id' => (int)$sc['id'],
'service_id' => (int)$sc['service_id'],
'service_name' => $sc['service_name'] ?: '上门服务',
'cat_name' => $sc['cat_name'] ?: '服务',
'cat_id' => (int)$sc['cat_id'],
'image_url' => $sc['cover_image'] ? cdnurl($sc['cover_image'], true) : '',
'status_text' => '业主晒单',
'location' => $sc['region'] ?: '同城服务',
'time_ago' => $this->timeAgo((int)$sc['createtime']),
'user_name' => $sc['user_name'] ?: '匿名业主',
'review_score' => (int)$sc['score'] ?: 5,
'review_content' => $sc['content'] ?: '师傅准时上门,施工专业细致,安装效果很满意!',
'review_tags' => array_slice($revTags, 0, 3),
];
}
$this->success('', [
'list' => $list,
'total' => $total,
'page' => $page,
'limit' => $limit,
'has_more' => ($page * $limit) < $total,
]);
}
// tab === 'hot'(热门服务推荐分页 + 二级项目筛选 + 区域热度加权 + 排序)
$orderQuery = Db::name('order')->where('status', 8);
if ($region !== '' && $region !== 'all') {
$orderQuery->where('district', $region);
}
$orderCounts = $orderQuery
->group('service_id')
->column('count(*)', 'service_id');
$query = Db::name('service')
->alias('s')
->join('service_cat c', 's.cat_id = c.id', 'LEFT')
->field('s.id,s.cat_id,s.name,s.price_type,s.service_types,s.base_price,s.max_price,s.unit,s.image,s.sales,s.weigh,c.name as cat_name,c.icon as cat_icon')
->where('s.status', 'normal')
->where('s.cat_id', '<>', 15);
$candidateServices = $query->select();
// 计算真实订单与综合得分
foreach ($candidateServices as &$cs) {
$sid = (int)$cs['id'];
$realOrders = isset($orderCounts[$sid]) ? (int)$orderCounts[$sid] : 0;
$cs['real_orders'] = $realOrders;
$cs['total_sales'] = ($realOrders * 5) + (int)$cs['sales'];
$cs['score'] = ($realOrders * 15) + ((int)$cs['sales'] * 2) + ($cs['price_type'] === 'fixed' ? 25 : 0) + (int)$cs['weigh'];
if ($realOrders > 0) {
$cs['tag'] = '热销爆款';
} elseif ($cs['price_type'] === 'fixed') {
$cs['tag'] = '明码标价';
} else {
$cs['tag'] = '好评优选';
}
}
unset($cs);
// 首页【热门推荐】核心定位:精选各品类 Top 高频爆款(每类精选 Top 1~2 项,剔除低频长尾项,保证热门池精炼且筛选子集严格收敛)
usort($candidateServices, function ($a, $b) {
return $b['score'] <=> $a['score'];
});
$curatedPool = [];
$catQuota = [];
foreach ($candidateServices as $csItem) {
$cid = (int)$csItem['cat_id'];
$salesVal = (int)$csItem['sales'];
if ($salesVal < 145 && (int)$csItem['real_orders'] === 0) {
continue;
}
$curCount = isset($catQuota[$cid]) ? $catQuota[$cid] : 0;
if ($curCount < 2) {
$curatedPool[] = $csItem;
$catQuota[$cid] = $curCount + 1;
}
}
$candidateServices = $curatedPool;
// 1. 类目与指定商品过滤
if ($catId > 0) {
$candidateServices = array_values(array_filter($candidateServices, function ($r) use ($catId) {
return (int)$r['cat_id'] === $catId;
}));
}
if ($serviceId > 0) {
$candidateServices = array_values(array_filter($candidateServices, function ($r) use ($serviceId) {
return (int)$r['id'] === $serviceId;
}));
}
// 2. 计价单位与计价类型过滤
if ($unitFilter !== '' && $unitFilter !== 'all') {
$candidateServices = array_values(array_filter($candidateServices, function ($r) use ($unitFilter) {
return (string)$r['unit'] === $unitFilter;
}));
}
if ($priceTypeFilter !== '' && $priceTypeFilter !== 'all') {
$candidateServices = array_values(array_filter($candidateServices, function ($r) use ($priceTypeFilter) {
return (string)$r['price_type'] === $priceTypeFilter;
}));
}
if ($onlyFixed === 1) {
$candidateServices = array_values(array_filter($candidateServices, function ($r) {
return (string)$r['price_type'] === 'fixed';
}));
}
// 工项筛选与工项真实价格/名称联动
if ($serviceType !== '' && $serviceType !== 'all') {
$matchedServices = [];
foreach ($candidateServices as $csRow) {
$types = [];
if (!empty($csRow['service_types'])) {
$dec = is_array($csRow['service_types']) ? $csRow['service_types'] : json_decode((string)$csRow['service_types'], true);
if (is_array($dec)) {
$types = $dec;
}
}
if (empty($types)) {
$types = $this->resolveServiceTypes($csRow);
}
foreach ($types as $st) {
$code = isset($st['code']) ? (string)$st['code'] : '';
if ($code === $serviceType) {
if (!empty($st['price']) && (float)$st['price'] > 0) {
$csRow['base_price'] = (float)$st['price'];
}
if ($code !== 'install' && !empty($st['name'])) {
$shortTypeName = (string)$st['name'];
if ($code === 'deliver_install') {
$shortTypeName = '送装';
} elseif ($code === 'clean') {
$shortTypeName = '保洁';
}
$csRow['name'] = $csRow['name'] . ' · ' . $shortTypeName;
$csRow['tag'] = $shortTypeName . '专项';
}
$matchedServices[] = $csRow;
break;
}
}
}
$candidateServices = $matchedServices;
}
// 价格区间过滤(基于当前生效的 base_price 精准过滤)
if ($minPrice !== '' && is_numeric($minPrice)) {
$minVal = (float)$minPrice;
$candidateServices = array_values(array_filter($candidateServices, function ($r) use ($minVal) {
return (float)$r['base_price'] >= $minVal;
}));
}
if ($maxPrice !== '' && is_numeric($maxPrice)) {
$maxVal = (float)$maxPrice;
$candidateServices = array_values(array_filter($candidateServices, function ($r) use ($maxVal) {
return (float)$r['base_price'] <= $maxVal;
}));
}
if ($priceRange !== '' && $priceRange !== 'all') {
$candidateServices = array_values(array_filter($candidateServices, function ($r) use ($priceRange) {
$bp = (float)$r['base_price'];
if ($priceRange === 'under_80') return $bp < 80;
if ($priceRange === '80_120') return $bp >= 80 && $bp <= 120;
if ($priceRange === '120_up') return $bp > 120;
if ($priceRange === '0_80') return $bp <= 80;
if ($priceRange === '80_150') return $bp > 80 && $bp <= 150;
if ($priceRange === '150_up') return $bp > 150;
if ($priceRange === '0_50') return $bp <= 50;
if ($priceRange === '50_100') return $bp > 50 && $bp <= 100;
if ($priceRange === '100_up') return $bp > 100;
return true;
}));
}
if ($sort === 'sales') {
usort($candidateServices, function ($a, $b) {
if ($b['total_sales'] !== $a['total_sales']) {
return $b['total_sales'] <=> $a['total_sales'];
}
return $b['score'] <=> $a['score'];
});
} elseif ($sort === 'price_asc') {
usort($candidateServices, function ($a, $b) {
if ((float)$a['base_price'] != (float)$b['base_price']) {
return (float)$a['base_price'] <=> (float)$b['base_price'];
}
return $b['score'] <=> $a['score'];
});
} elseif ($sort === 'price_desc') {
usort($candidateServices, function ($a, $b) {
if ((float)$b['base_price'] != (float)$a['base_price']) {
return (float)$b['base_price'] <=> (float)$a['base_price'];
}
return $b['score'] <=> $a['score'];
});
} else {
// 默认综合推荐:先按得分排序,若为全部分类则优先保证首屏品类均衡
usort($candidateServices, function ($a, $b) {
return $b['score'] <=> $a['score'];
});
if ($catId === 0) {
$balanced = [];
$catSeen = [];
$usedIds = [];
foreach ($candidateServices as $cs) {
$cid = (int)$cs['cat_id'];
if (!isset($catSeen[$cid])) {
$balanced[] = $cs;
$catSeen[$cid] = 1;
$usedIds[$cs['id']] = true;
}
}
foreach ($candidateServices as $cs) {
if (!isset($usedIds[$cs['id']])) {
$balanced[] = $cs;
}
}
$candidateServices = $balanced;
}
}
$total = count($candidateServices);
$offset = ($page - 1) * $limit;
$pagedSlice = array_slice($candidateServices, $offset, $limit);
$this->success('', [
'list' => $this->formatServices($pagedSlice),
'total' => $total,
'page' => $page,
'limit' => $limit,
'has_more' => ($page * $limit) < $total,
]);
}
/**
* 全部类目
*/
public function cats()
{
$rawCats = Db::name('service_cat')
->field('id,name,icon')
->where('status', 'normal')
->order('weigh desc,id asc')
->select();
$cats = $this->formatCats($rawCats);
foreach ($cats as &$c) {
$icon = (string)$c['icon'];
if ($icon !== '') {
if (strpos($icon, 'http') === 0) {
$c['icon_url'] = $icon;
} elseif (strpos($icon, '/') !== false || strpos($icon, '.') !== false) {
$c['icon_url'] = cdnurl($icon, true);
} else {
$c['icon_url'] = '';
}
} else {
$c['icon_url'] = '';
}
}
unset($c);
$this->success('', ['list' => $cats]);
}
/**
* 类目下的服务列表
*/
public function services()
{
$catId = (int)$this->request->param('cat_id');
$keyword = trim((string)$this->request->param('keyword'));
if ($catId <= 0 && $keyword === '') {
$this->error('请选择服务类目');
}
$query = Db::name('service')->where('status', 'normal');
if ($catId > 0) {
$query->where('cat_id', $catId);
}
if ($keyword !== '') {
$specMatchingIds = Db::name('service_spec')
->where('status', 'normal')
->where('name|description', 'like', '%' . $keyword . '%')
->column('service_id');
$query->where(function($q) use ($keyword, $specMatchingIds) {
$q->where('name', 'like', '%' . $keyword . '%');
if (!empty($specMatchingIds)) {
$q->whereOr('id', 'in', $specMatchingIds);
}
});
}
$list = $query->order('weigh desc,sales desc,id asc')->select();
$this->success('', ['list' => $this->formatServices($list)]);
}
/**
* 服务商品规格列表
*/
public function specs()
{
$serviceId = (int)$this->request->param('service_id');
if ($serviceId <= 0) {
$this->error('请指定服务商品');
}
$specs = Db::name('service_spec')
->where('service_id', $serviceId)
->where('status', 'normal')
->order('weigh desc, id asc')
->select();
$ret = [];
foreach ($specs as $sp) {
$ret[] = [
'id' => (int)$sp['id'],
'service_id' => (int)$sp['service_id'],
'name' => $sp['name'],
'description' => (string)$sp['description'],
'base_price' => (float)$sp['base_price'],
];
}
$this->success('', ['list' => $ret]);
}
/**
* 服务详情
*/
public function detail()
{
$id = (int)$this->request->param('id');
$service = Db::name('service')->where('id', $id)->where('status', 'normal')->find();
if (!$service) {
$this->error('服务不存在');
}
$cat = Db::name('service_cat')->where('id', $service['cat_id'])->find();
$service['cat_name'] = $cat ? $cat['name'] : '';
$this->success('', ['detail' => $this->formatService($service)]);
}
/**
* 区域师傅运力统计
*/
public function masterCount()
{
$province = trim((string)$this->request->param('province', ''));
$city = trim((string)$this->request->param('city', ''));
$district = trim((string)$this->request->param('district', ''));
$catId = (int)$this->request->param('cat_id', 0);
$query = Db::name('master')->where('verify_status', 'pass');
if ($city !== '') {
$query->where('city', 'like', '%' . $city . '%');
}
$realCount = $query->count();
// 商业化基础运力感知(基于城市区县散列生成可信且稳定的运力规模,例如 150~1800+)
$hashSeed = sprintf('%u', crc32($province . $city . $district));
$virtualBase = 150 + ($hashSeed % 1700);
$total = max($realCount, $virtualBase);
$this->success('', [
'count' => (int)$total,
'region' => trim($city . ' ' . $district),
'tip' => "该地区可提供服务的师傅共 {$total} 位",
]);
}
/**
* 费用试算(基础价 + 楼层费 + 加急费 - 优惠)
* 支持下单页实时切换:一口价 / 师傅报价 / 用户自主定价
*/
public function calc()
{
$serviceId = (int)$this->request->param('service_id');
$goodsListRaw = $this->request->param('goods_list', '', null);
$goodsList = [];
if (!empty($goodsListRaw)) {
if (is_string($goodsListRaw)) {
$rawStr = htmlspecialchars_decode($goodsListRaw);
$decoded = json_decode($rawStr, true);
if (is_array($decoded)) {
$goodsList = $decoded;
}
} elseif (is_array($goodsListRaw)) {
if (isset($goodsListRaw[0]) && is_string($goodsListRaw[0])) {
$rawStr = htmlspecialchars_decode($goodsListRaw[0]);
$decoded = json_decode($rawStr, true);
$goodsList = is_array($decoded) ? $decoded : $goodsListRaw;
} else {
$goodsList = $goodsListRaw;
}
}
}
if ($serviceId <= 0 && !empty($goodsList) && is_array($goodsList)) {
$first = reset($goodsList);
if (is_array($first) && !empty($first['service_id'])) {
$serviceId = (int)$first['service_id'];
}
}
$service = null;
if ($serviceId > 0) {
$service = Db::name('service')->where('id', $serviceId)->where('status', 'normal')->find();
}
$result = self::calcAmount($service, [
'floor' => (int)$this->request->param('floor', 1),
'has_elevator' => (int)$this->request->param('has_elevator', 1),
'urgent' => (int)$this->request->param('urgent', 0),
], (int)$this->request->param('coupon_id', 0), $this->uid(),
(string)$this->request->param('price_type', ''),
(float)$this->request->param('user_price', 0),
$goodsList);
$this->success('', $result);
}
/**
* 金额计算(下单与试算共用,保证前后端口径一致)
*
* @param array $service 服务行(可选)
* @param array $params floor / has_elevator / urgent
* @param int $couponId 用户优惠券 id
* @param int $uid 用户 id
* @param string $priceType 计价方式:fixed 一口价 / quote 师傅报价 / custom 用户自主定价
* @param float $userPrice 用户自主定价金额(总价,含楼层/加急)
* @param array $goodsList 多组商品组合(含商品规格与增项拆旧等)
*/
public static function calcAmount($service, $params, $couponId = 0, $uid = 0, $priceType = '', $userPrice = 0, $goodsList = [])
{
$allowTypes = ['fixed', 'quote', 'range', 'custom'];
$type = in_array($priceType, $allowTypes, true) ? $priceType : ($service ? $service['price_type'] : 'fixed');
// 支持多商品组合与增项计算
$base = 0;
if (!empty($goodsList) && is_array($goodsList)) {
foreach ($goodsList as $g) {
if (is_string($g)) {
$rawG = htmlspecialchars_decode($g);
$decoded = json_decode($rawG, true);
if (is_array($decoded)) {
$g = $decoded;
}
}
if (!is_array($g)) {
continue;
}
$itemPrice = isset($g['base_price']) ? (float)$g['base_price'] : 0;
if ($itemPrice <= 0 && !empty($g['service_id'])) {
$itemPrice = (float)Db::name('service')->where('id', (int)$g['service_id'])->value('base_price');
}
$itemNum = isset($g['num']) ? max(1, (int)$g['num']) : 1;
$base += $itemPrice * $itemNum;
if (!empty($g['extras']) && is_array($g['extras'])) {
foreach ($g['extras'] as $ex) {
$exPrice = isset($ex['price']) ? (float)$ex['price'] : 0;
$exNum = isset($ex['num']) ? max(0, (int)$ex['num']) : 0;
$base += $exPrice * $exNum;
}
}
}
} elseif ($service) {
$base = (float)$service['base_price'];
}
$floorAmount = 0;
$urgentAmount = 0;
if ($type === 'custom') {
// 用户自主定价:出价即订单总价,已包含楼层费/加急费,师傅按此价接单
$base = max(0, round((float)$userPrice, 2));
$total = $base;
} elseif ($type === 'quote') {
// 师傅报价模式:金额由师傅后续竞价给出,下单时总价与应付为 0
$total = 0;
$floorAmount = 0;
$urgentAmount = 0;
} else {
$floor = max(0, (int)$params['floor']);
$freeFloor = $service ? (int)$service['free_floor'] : 2;
$floorFee = $service ? (float)$service['floor_fee'] : 10.0;
if ((int)$params['has_elevator'] === 0 && $floor > $freeFloor) {
$floorAmount = ($floor - $freeFloor) * $floorFee;
}
$urgentAmount = (int)$params['urgent'] === 1 ? round($base * 0.2, 2) : 0;
$total = round($base + $floorAmount + $urgentAmount, 2);
}
$discount = 0;
$couponInfo = null;
if ($couponId > 0 && $uid > 0) {
$uc = Db::name('user_coupon')->where('id', $couponId)->where('user_id', $uid)->where('status', 'unused')->find();
if ($uc) {
$coupon = Db::name('coupon')->where('id', $uc['coupon_id'])->where('status', 'normal')->find();
$notExpired = $coupon && (int)$coupon['end_time'] === 0 ? true : ($coupon && $coupon['end_time'] > time());
if ($notExpired && $total >= (float)$coupon['min_amount']) {
$discount = $coupon['type'] === 'cash'
? (float)$coupon['amount']
: round($total * (1 - (float)$coupon['discount']), 2);
$discount = min($discount, $total);
$couponInfo = ['id' => (int)$uc['id'], 'name' => $coupon['name']];
}
}
}
return [
'price_type' => $type,
'user_price' => $type === 'custom' ? round($base, 2) : 0,
'base_amount' => $type === 'quote' ? 0 : round($base, 2),
'floor_amount' => round($floorAmount, 2),
'urgent_amount' => round($urgentAmount, 2),
'total_amount' => $total,
'discount_amount' => round($discount, 2),
'pay_amount' => max(0, round($total - $discount, 2)),
'coupon' => $couponInfo,
'free_floor' => $type === 'custom' ? 0 : ($service ? (int)$service['free_floor'] : 2),
'floor_fee' => $type === 'custom' ? 0 : round($service ? (float)$service['floor_fee'] : 10.0, 2),
];
}
/**
* 首页轮播(后台 fa_banner 可管,支持活动 / 平台实力 / 服务主题)
*/
protected function banners()
{
$rows = Db::name('banner')
->field('id,badge,title,subtitle,date_text,theme,action_text,stats,image,link,weigh')
->where('status', 'normal')
->order('weigh desc,id desc')
->limit(8)
->select();
if (!$rows) {
return [];
}
$themeText = [
'promo' => '活动促销',
'brand' => '平台实力',
'service' => '服务主题',
];
$ret = [];
foreach ($rows as $r) {
$theme = isset($themeText[$r['theme']]) ? $r['theme'] : 'promo';
$stats = $this->parseBannerStats(isset($r['stats']) ? $r['stats'] : '');
if ($theme === 'brand' && empty($stats)) {
$stats = $this->defaultBrandStats();
}
$actionText = trim((string)$r['action_text']);
if ($actionText === '' && $theme !== 'brand') {
$actionText = '立即查看';
}
$ret[] = [
'id' => (int)$r['id'],
'badge' => $r['badge'],
'title' => $r['title'],
'subtitle' => $r['subtitle'],
'date_text' => $r['date_text'],
'theme' => $theme,
'theme_text' => $themeText[$theme],
'action_text' => $actionText,
'stats' => $stats,
'image' => $r['image'],
'link' => $r['link'],
];
}
return $ret;
}
/**
* 解析平台实力主题的统计 JSON
*/
protected function parseBannerStats($raw)
{
$raw = trim((string)$raw);
if ($raw === '') {
return [];
}
$decoded = json_decode($raw, true);
if (!is_array($decoded)) {
return [];
}
$out = [];
foreach ($decoded as $item) {
if (!is_array($item) || !isset($item['value']) || !isset($item['label'])) {
continue;
}
$out[] = [
'value' => (string)$item['value'],
'label' => (string)$item['label'],
];
}
return $out;
}
/**
* 平台实力默认指标
*/
protected function defaultBrandStats()
{
return [
['value' => '460万+', 'label' => '专业师傅'],
['value' => '99.9%', 'label' => '区域覆盖到村镇'],
['value' => '1762万', 'label' => '成功订单'],
];
}
/**
* 无后台数据时的兜底轮播
*/
protected function defaultBanners()
{
return [
[
'id' => 0, 'badge' => '家装季', 'title' => '双11 狂欢大促',
'subtitle' => '下单立减 · 满额再返券', 'date_text' => '10.23 - 11.15',
'theme' => 'promo', 'theme_text' => '活动促销', 'action_text' => '立即抢购',
'stats' => [], 'image' => '',
'link' => '/pages/service/list?cat_id=1&cat_name=%E5%AE%B6%E5%85%B7',
],
[
'id' => -1, 'badge' => '平台实力', 'title' => '平台实力',
'subtitle' => '已有 176276994 个订单找到师傅', 'date_text' => '下单越多 · 越优惠',
'theme' => 'brand', 'theme_text' => '平台实力', 'action_text' => '',
'stats' => $this->defaultBrandStats(), 'image' => '', 'link' => '',
],
[
'id' => -2, 'badge' => '服务主题', 'title' => '家电清洗季',
'subtitle' => '空调 / 洗衣机 / 油烟机深度清洗', 'date_text' => '9.9 折起',
'theme' => 'service', 'theme_text' => '服务主题', 'action_text' => '立即预约',
'stats' => [], 'image' => '',
'link' => '/pages/service/list?cat_id=10&cat_name=%E5%AE%B6%E7%94%B5',
],
];
}
/**
* 读取 fa_config 中的逗号分隔列表
*/
protected function configList($name, $default = '')
{
$v = Db::name('config')->where('name', $name)->value('value');
if (!$v) {
$v = $default;
}
return array_values(array_filter(array_map('trim', explode(',', (string)$v))));
}
/**
* 首页教程卡(fa_config: 标题|副标题)
*/
protected function tutorial()
{
$v = Db::name('config')->where('name', 'home_tutorial')->value('value');
if (!$v) {
return ['title' => '下单找师傅教程', 'sub' => '3 分钟看懂,下单不踩坑'];
}
$parts = explode('|', (string)$v);
return [
'title' => trim($parts[0]),
'sub' => isset($parts[1]) ? trim($parts[1]) : '',
];
}
/**
* 列表格式化
*/
public function formatServices($list)
{
if (empty($list)) {
return [];
}
$serviceIds = array_column($list, 'id');
$specsMap = [];
if (!empty($serviceIds)) {
$specs = Db::name('service_spec')
->where('service_id', 'in', $serviceIds)
->where('status', 'normal')
->order('weigh desc, id asc')
->select();
foreach ($specs as $sp) {
$sid = (int)$sp['service_id'];
if (!isset($specsMap[$sid])) {
$specsMap[$sid] = [];
}
$specsMap[$sid][] = [
'id' => (int)$sp['id'],
'service_id' => $sid,
'name' => $sp['name'],
'description' => (string)$sp['description'],
'base_price' => (float)$sp['base_price'],
];
}
}
$ret = [];
foreach ($list as $row) {
$formatted = $this->formatService($row);
$formatted['specs'] = isset($specsMap[$row['id']]) ? $specsMap[$row['id']] : [];
$ret[] = $formatted;
}
return $ret;
}
/**
* 格式化类目列表(统一网络图片 URL)
*/
protected function formatCats($cats)
{
if (empty($cats)) return [];
foreach ($cats as &$c) {
$icon = (string)$c['icon'];
if ($icon !== '') {
if (strpos($icon, 'http') === 0) {
$c['icon_url'] = $icon;
} elseif (strpos($icon, '/') !== false || strpos($icon, '.') !== false) {
$c['icon_url'] = cdnurl($icon, true);
} else {
$c['icon_url'] = '';
}
} else {
$c['icon_url'] = '';
}
}
unset($c);
return $cats;
}
/**
* 单项格式化(价格文案统一由此输出)
*/
public function formatService($row)
{
$type = $row['price_type'];
$priceText = '¥' . (float)$row['base_price'];
if ($type === 'range') {
$priceText = '¥' . (float)$row['base_price'] . '-' . (float)$row['max_price'] . '/' . $row['unit'];
} elseif ($type === 'quote') {
$priceText = '¥' . (float)$row['base_price'] . ' · 师傅报价';
}
// 解析主服务项目与增项服务(均与统一服务表 fa_service_type 实时联动校验)
static $typeDictCache = null;
if ($typeDictCache === null) {
$typeDictCache = Db::name('service_type')
->where('status', 'normal')
->order('weigh desc, id asc')
->select();
}
$activeTypeCodes = [];
$activeTypeNames = [];
foreach ($typeDictCache as $td) {
$activeTypeCodes[$td['code']] = $td;
$activeTypeNames[$td['name']] = $td;
}
$serviceTypes = [];
if (!empty($row['service_types'])) {
$serviceTypes = is_array($row['service_types']) ? $row['service_types'] : json_decode($row['service_types'], true);
}
if (empty($serviceTypes)) {
$serviceTypes = $this->resolveServiceTypes($row);
}
$FixedCodes = ['install', 'repair', 'remove'];
if (!empty($activeTypeCodes)) {
$filteredTypes = [];
foreach ($serviceTypes as $st) {
$c = isset($st['code']) ? $st['code'] : '';
if ($c !== '' && isset($activeTypeCodes[$c])) {
if (!isset($st['support_fixed'])) {
$st['support_fixed'] = in_array($c, $FixedCodes, true) ? 1 : 0;
}
$filteredTypes[] = $st;
}
}
if (!empty($filteredTypes)) {
$serviceTypes = $filteredTypes;
}
} else {
foreach ($serviceTypes as &$stItem) {
$c = isset($stItem['code']) ? $stItem['code'] : '';
if (!isset($stItem['support_fixed'])) {
$stItem['support_fixed'] = in_array($c, $FixedCodes, true) ? 1 : 0;
}
}
unset($stItem);
}
// 解析增项服务(优先读取商品绑定的 addons JSON,并与统一服务表 fa_service_type 联动过滤)
$addons = [];
if (!empty($row['addons'])) {
$addons = is_array($row['addons']) ? $row['addons'] : json_decode($row['addons'], true);
}
if (empty($addons)) {
$addons = $this->resolveServiceAddons($row);
} elseif (!empty($activeTypeCodes)) {
$addons = array_values(array_filter($addons, function ($ad) use ($activeTypeCodes, $activeTypeNames) {
$code = isset($ad['code']) ? $ad['code'] : '';
$name = isset($ad['name']) ? $ad['name'] : '';
return ($code !== '' && isset($activeTypeCodes[$code])) || ($name !== '' && isset($activeTypeNames[$name]));
}));
}
$catIcon = isset($row['cat_icon']) && $row['cat_icon'] ? $row['cat_icon'] : '';
$img = $row['image'] ? $row['image'] : $catIcon;
return [
'id' => (int)$row['id'],
'cat_id' => (int)$row['cat_id'],
'name' => $row['name'],
'cat_name' => isset($row['cat_name']) ? $row['cat_name'] : '',
'image' => $row['image'],
'image_url' => $img ? cdnurl($img, true) : '',
'price_type' => $type,
'price_type_text' => $type === 'fixed' ? '一口价' : ($type === 'quote' ? '师傅报价' : '按面积计价'),
'base_price' => (float)$row['base_price'],
'max_price' => (float)$row['max_price'],
'unit' => $row['unit'],
'price_text' => $priceText,
'sales' => (int)$row['sales'],
'floor_fee' => isset($row['floor_fee']) ? (float)$row['floor_fee'] : 0,
'free_floor' => isset($row['free_floor']) ? (int)$row['free_floor'] : 0,
'need_model' => isset($row['need_model']) ? (int)$row['need_model'] : 1,
'description' => isset($row['description']) ? $row['description'] : '',
'tag' => isset($row['tag']) && $row['tag'] ? $row['tag'] : '明码标价',
'service_types' => $serviceTypes,
'addons' => $addons,
];
}
/**
* 根据具体商品名称与所属类目返回精准匹配的服务项目列表(1:1 对标奇兵到家图2 & 图3)
*/
protected function resolveServiceTypes($row)
{
$catId = (int)$row['cat_id'];
$name = (string)$row['name'];
$bp = max(30, (float)$row['base_price']);
$make = function ($items) use ($bp) {
$res = [];
$fixedCodes = ['install', 'repair', 'remove'];
foreach ($items as $idx => $it) {
$ratio = isset($it[2]) ? (float)$it[2] : 1.0;
$fixed = isset($it[3]) && $it[3] !== null ? (float)$it[3] : round($bp * $ratio, 2);
$supportFixed = isset($it[4]) ? (int)$it[4] : (in_array($it[0], $fixedCodes, true) ? 1 : 0);
$res[] = [
'code' => $it[0],
'name' => $it[1],
'price' => $fixed,
'is_default' => $idx === 0 ? 1 : 0,
'support_fixed' => $supportFixed,
];
}
return $res;
};
// 类目 15:其它(1:1 复刻图3)
if ($catId === 15) {
return $make([
['install', '安装', 1.0, null, 0],
['repair', '维修', 0.8, null, 0],
['grout', '美缝', 1.0, null, 0],
['glue', '打胶', 0.6, null, 0],
['remove', '拆旧', 0.5, null, 0],
['deliver', '送货到家', 0.7, 50, 0],
['deliver_install', '送货到家并安装', 1.3, null, 0],
['deliver_downstairs', '送货到楼下(不含上楼)', 0.5, 35, 0],
['clean', '保洁', 1.0, null, 0],
['drill', '打孔', 0.5, 30, 0],
['film', '贴膜', 0.8, null, 0],
['move', '移机', 1.1, null, 0],
['other', '其他', 1.0, null, 0],
]);
}
// 类目 6:墙纸/壁画(1:1 复刻图2)
if ($catId === 6) {
if (strpos($name, '画') !== false && strpos($name, '壁画') === false) {
return $make([
['install', '安装', 1.0],
['repair', '维修', 1.15],
['remove', '拆旧', 0.5, 30],
['drill', '打孔', 0.6, 30, 0],
['deliver_install', '送货到家并安装', 1.3, null, 0],
]);
}
return $make([
['install', '安装', 1.0],
['repair', '维修', 1.15],
['deliver', '送货到家', 0.7, 50, 0],
['deliver_install', '送货到家并安装', 1.3, null, 0],
['deliver_downstairs', '送货到楼下(不含上楼)', 0.5, 35, 0],
]);
}
// 类目 1:家具(1:1 复刻视频 00:02 的 11 项服务项目,且安装/维修/拆旧支持一口价,其余自动转报价)
if ($catId === 1) {
$repairPrice = round($bp + 10, 2);
return $make([
['install', '安装', 1.0, $bp, 1],
['repair', '维修', 1.18, $repairPrice, 1],
['remove', '拆旧', 0.9, 50, 1],
['paint_repair', '补漆修复', 1.0, 80, 0],
['measure', '测量', 0.8, 50, 0],
['deliver', '送货到家', 0.7, 60, 0],
['deliver_install', '送货到家并安装', 1.35, round($bp * 1.35, 2), 0],
['deliver_downstairs', '送货到楼下(不含上楼)', 0.5, 40, 0],
['return_goods', '返货', 0.8, 50, 0],
['maintain', '保养', 0.8, 60, 0],
['open_hole', '开孔', 0.5, 30, 0],
]);
}
// 类目 2:卫浴(区分马桶、花洒龙头、浴室柜/浴缸、浴霸)
if ($catId === 2) {
if (preg_match('/(马桶|便器)/u', $name)) {
return $make([
['install', '安装', 1.0],
['repair', '维修', 0.7],
['remove', '拆旧', 0.5],
['glue', '打胶', 0.4, 30],
['grout', '美缝', 0.6, 50],
['deliver_install', '送货到家并安装', 1.3],
]);
}
if (preg_match('/(花洒|龙头|扶手|镜)/u', $name)) {
return $make([
['install', '安装', 1.0],
['repair', '维修', 0.7],
['remove', '拆旧', 0.4],
['drill', '打孔', 0.4, 25],
]);
}
if (preg_match('/(浴霸|水泵)/u', $name)) {
return $make([
['install', '安装', 1.0],
['repair', '维修', 0.75],
['remove', '拆旧', 0.45],
['deliver_install', '送货到家并安装', 1.25],
]);
}
return $make([
['install', '安装', 1.0],
['repair', '维修', 0.7],
['remove', '拆旧', 0.5],
['glue', '打胶', 0.4, 30],
['deliver', '送货到家', 0.6, 50],
['deliver_install', '送货到家并安装', 1.3],
]);
}
// 类目 3:灯具
if ($catId === 3) {
return $make([
['install', '安装', 1.0],
['repair', '维修', 0.7],
['remove', '拆旧', 0.4],
['deliver_install', '送货到家并安装', 1.25],
]);
}
// 类目 4:锁具
if ($catId === 4) {
return $make([
['install', '安装', 1.0],
['repair', '维修', 0.7],
['remove', '拆旧', 0.4],
['drill', '打孔', 0.5, 40],
]);
}
// 类目 5:窗帘
if ($catId === 5) {
return $make([
['install', '安装', 1.0],
['repair', '维修', 0.7],
['measure', '测量', 0.5, 40],
['remove', '拆旧', 0.4],
['deliver_install', '送货到家并安装', 1.25],
]);
}
// 类目 7:净水器
if ($catId === 7) {
return $make([
['install', '安装', 1.0],
['repair', '维修', 0.7],
['filter', '换滤芯', 0.5, 40],
['remove', '拆旧', 0.4],
['move', '移机', 1.1],
]);
}
// 类目 8:晾衣架(区分电动、手摇、户外推拉/落地)
if ($catId === 8) {
if (strpos($name, '电动') !== false) {
return $make([
['install', '安装', 1.0],
['repair', '维修', 0.7],
['remove', '拆旧', 0.4],
['deliver', '送货到家', 0.6, 45],
['deliver_install', '送货到家并安装', 1.25],
['move', '移机', 1.1],
]);
}
if (strpos($name, '户外') !== false || strpos($name, '推拉') !== false) {
return $make([
['install', '安装', 1.0],
['repair', '维修', 0.7],
['remove', '拆旧', 0.4],
['drill', '打孔', 0.5, 30],
]);
}
return $make([
['install', '安装', 1.0],
['repair', '维修', 0.7],
['remove', '拆旧', 0.4],
['deliver', '送货到家', 0.6, 45],
['deliver_install', '送货到家并安装', 1.25],
]);
}
// 类目 9:门窗
if ($catId === 9) {
return $make([
['install', '安装', 1.0],
['repair', '维修', 0.7],
['measure', '测量', 0.4, 50],
['remove', '拆旧', 0.5],
['glue', '打胶', 0.4, 40],
['deliver_install', '送货到家并安装', 1.3],
]);
}
// 类目 10:家电(区分空调、厨电、洗衣机冰箱)
if ($catId === 10) {
if (strpos($name, '空调') !== false) {
return $make([
['install', '安装', 1.0],
['repair', '维修', 0.7],
['move', '移机', 1.2],
['remove', '拆旧', 0.5],
['clean', '保洁清洗', 0.6, 80],
['deliver_install', '送货到家并安装', 1.3],
]);
}
return $make([
['install', '安装', 1.0],
['repair', '维修', 0.7],
['remove', '拆旧', 0.45],
['clean', '保洁清洗', 0.6, 70],
['drill', '打孔', 0.4, 40],
['deliver_install', '送货到家并安装', 1.25],
]);
}
// 类目 11:电视/投影
if ($catId === 11) {
return $make([
['install', '安装', 1.0],
['repair', '维修', 0.7],
['move', '移机', 1.0],
['remove', '拆旧', 0.4],
['deliver_install', '送货到家并安装', 1.25],
]);
}
// 类目 12:淋浴房
if ($catId === 12) {
return $make([
['install', '安装', 1.0],
['repair', '维修', 0.7],
['measure', '测量', 0.3, 50],
['remove', '拆旧', 0.45],
['glue', '打胶', 0.3, 40],
['film', '贴膜', 0.4, 80],
['deliver_install', '送货到家并安装', 1.3],
]);
}
// 类目 13:商用厨电
if ($catId === 13) {
return $make([
['install', '安装', 1.0],
['repair', '维修', 0.7],
['clean', '保洁', 0.8],
['remove', '拆旧', 0.5],
['deliver_install', '送货到家并安装', 1.25],
]);
}
// 类目 14:健身器材
if ($catId === 14) {
return $make([
['install', '安装', 1.0],
['repair', '维修', 0.7],
['move', '移机', 1.1],
['remove', '拆旧', 0.5],
['deliver', '送货到家', 0.6, 60],
['deliver_install', '送货到家并安装', 1.3],
]);
}
return $make([
['install', '安装', 1.0],
['repair', '维修', 0.7],
['remove', '拆旧', 0.5],
['deliver', '送货到家', 0.6, 50],
['deliver_install', '送货到家并安装', 1.3],
]);
}
/**
* 根据具体商品名称与所属类目返回极简增值服务(增项)列表(1:1 对标奇兵到家:仅保留“拆旧”、“切割”等 1~2 项极简短词)
*/
protected function resolveServiceAddons($row)
{
$catId = (int)$row['cat_id'];
$name = (string)$row['name'];
$codeMap = [
'拆旧' => 'remove',
'切割' => 'cut',
'打孔' => 'drill',
'开孔' => 'open_hole',
];
$build = function ($items) use ($codeMap) {
$res = [];
foreach ($items as $idx => $it) {
$res[] = [
'id' => $idx + 1,
'code' => isset($codeMap[$it[0]]) ? $codeMap[$it[0]] : ('addon_' . ($idx + 1)),
'name' => $it[0],
'unit' => $it[1],
'price' => (float)$it[2],
];
}
return $res;
};
// 类目 1:家具(对标视频 00:06 / 00:17:电脑桌仅“拆旧 50元/份”,柜类多一项“切割 20元/份”)
if ($catId === 1) {
if (preg_match('/(柜)/u', $name)) {
return $build([
['拆旧', '份', 50],
['切割', '份', 20],
]);
}
return $build([
['拆旧', '份', 50],
]);
}
// 类目 2:卫浴(对标奇兵到家截图 frame_010:洗衣柜/浴室柜为“拆旧 50元/份”、“切割 20元/份”,马桶/花洒为“拆旧”)
if ($catId === 2) {
if (preg_match('/(浴室柜|洗衣柜|面盆|洗面盆|水槽|拖把池)/u', $name)) {
return $build([
['拆旧', '份', 50],
['切割', '份', 20],
]);
}
if (preg_match('/(马桶|便器)/u', $name)) {
return $build([
['拆旧', '份', 50],
]);
}
if (preg_match('/(浴缸)/u', $name)) {
return $build([
['拆旧', '份', 80],
]);
}
return $build([
['拆旧', '份', 30],
]);
}
// 类目 3:灯具
if ($catId === 3) {
return $build([
['拆旧', '份', 20],
]);
}
// 类目 4:锁具
if ($catId === 4) {
return $build([
['拆旧', '份', 30],
['开孔', '份', 30],
]);
}
// 类目 5:窗帘
if ($catId === 5) {
return $build([
['拆旧', '份', 30],
]);
}
// 类目 6:墙纸/壁画
if ($catId === 6) {
return $build([
['拆旧', '份', 30],
]);
}
// 类目 7:净水器
if ($catId === 7) {
return $build([
['拆旧', '份', 30],
['打孔', '份', 30],
]);
}
// 类目 8:晾衣架
if ($catId === 8) {
return $build([
['拆旧', '份', 30],
]);
}
// 类目 9:门窗
if ($catId === 9) {
return $build([
['拆旧', '份', 50],
]);
}
// 类目 10:家电
if ($catId === 10) {
if (strpos($name, '空调') !== false) {
return $build([
['拆旧', '份', 80],
['打孔', '份', 50],
]);
}
return $build([
['拆旧', '份', 40],
]);
}
// 类目 11:电视/投影
if ($catId === 11) {
return $build([
['拆旧', '份', 30],
]);
}
// 类目 12:淋浴房
if ($catId === 12) {
return $build([
['拆旧', '份', 80],
]);
}
// 类目 13:商用厨电
if ($catId === 13) {
return $build([
['拆旧', '份', 80],
]);
}
// 类目 14:健身器材
if ($catId === 14) {
return $build([
['拆旧', '份', 60],
]);
}
return $build([
['拆旧', '份', 30],
]);
}
/**
* 相对时间计算(更具真实动态感)
*/
protected function timeAgo($time)
{
if ($time <= 0) return '';
$diff = time() - $time;
if ($diff < 60) return '刚刚';
if ($diff < 3600) return floor($diff / 60) . '分钟前';
if ($diff < 86400) return floor($diff / 3600) . '小时前';
if ($diff < 86400 * 3) return floor($diff / 86400) . '天前';
return date('m-d', $time);
}
/**
* 公开业主晒单详情(直接读取独立晒单表 fa_showcase,仅返回必要脱敏晒单信息)
*/
public function orderCase()
{
$id = (int)$this->request->param('id');
if ($id <= 0) {
$this->error('晒单参数错误');
}
// 优先按晒单主键 id 查询,兼容从本人订单详情跳转时传入的 order_id
$sc = Db::name('showcase')->where('id', $id)->where('status', 'normal')->find();
if (!$sc) {
$sc = Db::name('showcase')->where('order_id', $id)->where('status', 'normal')->find();
}
if (!$sc) {
$this->error('该晒单不存在或已取消公开');
}
$service = Db::name('service')->where('id', (int)$sc['service_id'])->find();
$basePrice = ($service && (float)$service['base_price'] > 0) ? (float)$service['base_price'] : 50.00;
$imageUrl = $sc['cover_image'] ? cdnurl($sc['cover_image'], true) : '';
$tags = [];
if (!empty($sc['tags'])) {
$dec = json_decode((string)$sc['tags'], true);
$tags = is_array($dec) ? $dec : array_values(array_filter(explode(',', (string)$sc['tags'])));
}
$rImgs = [];
$mediaList = [];
if (!empty($sc['images'])) {
$decImgs = json_decode((string)$sc['images'], true);
$rawImgArr = is_array($decImgs) ? $decImgs : array_values(array_filter(explode(',', (string)$sc['images'])));
foreach ($rawImgArr as $idx => $imgItem) {
$imgItem = trim((string)$imgItem);
if ($imgItem !== '') {
$fullUrl = cdnurl($imgItem, true);
$rImgs[] = $fullUrl;
$mediaList[] = [
'id' => $idx + 1,
'type' => 'image',
'url' => $fullUrl,
'tag' => '晒单实拍',
];
}
}
}
$dateText = !empty($sc['createtime']) ? date('Y-m-d', (int)$sc['createtime']) : date('Y-m-d');
$catName = $sc['cat_name'] ?: '上门服务';
$serviceName = $sc['service_name'] ?: '上门服务';
$this->success('', [
'order' => [
'id' => (int)$sc['id'],
'service_id' => (int)$sc['service_id'],
'service_name' => $serviceName,
'cat_id' => (int)$sc['cat_id'],
'cat_name' => $catName,
'image_url' => $imageUrl,
'status_text' => '业主晒单',
'location' => $sc['region'] ?: '同城服务',
'finish_text' => $dateText,
'media' => $mediaList,
],
'master' => [
'realname' => $sc['master_name'] ?: '优匠师傅',
'score' => (float)($sc['master_score'] > 0 ? $sc['master_score'] : 5.0),
],
'review' => [
'id' => (int)$sc['id'],
'score' => (int)$sc['score'] ?: 5,
'tags' => $tags,
'content' => $sc['content'] ?: '师傅很专业,准时上门,施工规范细致,验收很满意!',
'images' => $rImgs,
'user_name' => $sc['user_name'] ?: '匿名业主',
'user_avatar' => $sc['user_avatar'] ? cdnurl($sc['user_avatar'], true) : '',
'time_text' => $dateText,
],
'service_info' => [
'cat_id' => (int)$sc['cat_id'],
'cat_name' => $catName,
'service_id' => (int)$sc['service_id'],
'service_name' => $serviceName,
'goods_name' => $serviceName,
'base_price' => $basePrice,
]
]);
}
}