425 lines
14 KiB
PHP
425 lines
14 KiB
PHP
<?php
|
|
|
|
namespace app\common\service;
|
|
|
|
use app\common\validate\UsedCarValidate;
|
|
use app\common\traits\crud\CrudServiceTrait;
|
|
use app\common\model\UsedCar;
|
|
use GuzzleHttp\Client;
|
|
use support\exception\BusinessException;
|
|
use support\Log;
|
|
use support\Request;
|
|
use app\common\model\User;
|
|
use support\Redis;
|
|
|
|
class UsedCarService
|
|
{
|
|
|
|
use CrudServiceTrait;
|
|
|
|
/**
|
|
* 指定当前要操作的模型
|
|
*/
|
|
protected string $modelClass = UsedCar::class;
|
|
|
|
/**
|
|
* 验证器
|
|
*/
|
|
protected $validator = UsedCarValidate::class;
|
|
|
|
/**
|
|
* 获取验证器
|
|
*/
|
|
public function getValidator()
|
|
{
|
|
return new $this->validator;
|
|
}
|
|
|
|
/**
|
|
* 构造 CrudUtil 查询配置
|
|
*/
|
|
protected function buildQueryConfig(Request $request, string $scene = 'default'): array
|
|
{
|
|
$p = $request->all();
|
|
|
|
$config = [];
|
|
$config['model'] = $this->modelClass;
|
|
switch ($scene) {
|
|
case 'default':
|
|
$config['where']['status'] = 1;
|
|
$config['order']['sort'] = 'desc';
|
|
$config['order']['id'] = 'desc';
|
|
break;
|
|
case 'index':
|
|
$config['where']['role'] = 2;
|
|
$config['where']['status'] = 1;
|
|
if (isset($p['status']) && $p['status']=='archive') {
|
|
$config['where']['status'] = ['in', [2, 3]];
|
|
}elseif (isset($p['status'])) {
|
|
$config['where']['status'] = $p['status'];
|
|
}
|
|
|
|
if (isset($p['scene']) && $p['scene'] == 'self') {
|
|
$config['where']['user_id'] = $request->user['id'];
|
|
unset($config['where']['role']);
|
|
unset( $config['where']['status']);
|
|
}
|
|
|
|
// 关键字
|
|
if (isset($p['keyword']) && $p['keyword']) {
|
|
$k = '%' . $p['keyword'] . '%';
|
|
foreach (['product_name','code'] as $col) {
|
|
$config['orWhere'][] = [$col, 'like', $k];
|
|
}
|
|
}
|
|
$config['order']['sort'] = 'desc';
|
|
$config['order']['id'] = 'desc';
|
|
break;
|
|
case 'show':
|
|
$config['where']['id'] = $p['id'];
|
|
$config['where']['status'] = 1;
|
|
break;
|
|
case 'store':
|
|
break;
|
|
case 'update':
|
|
$config['where']['id'] = $p['id'];
|
|
break;
|
|
case 'destroy':
|
|
$config['where']['id'] = $p['id'];
|
|
break;
|
|
}
|
|
|
|
return $config;
|
|
}
|
|
|
|
|
|
public function beforeServiceStore($data, Request $request): array
|
|
{
|
|
if (empty($data['product_name'])) {
|
|
throw new BusinessException('产品名称不能为空');
|
|
}
|
|
if (empty($data['images'])) {
|
|
throw new BusinessException('产品图片不能为空');
|
|
}
|
|
if (empty($data['price'])) {
|
|
$data['price'] = 0;
|
|
}
|
|
if (!empty($data['attachment'])) {
|
|
$data['attachment'] = json_encode($data['attachment']);
|
|
}else{
|
|
$data['attachment'] = '';
|
|
}
|
|
$data['user_id'] = $request->user['id'];
|
|
$user = User::where('id', $request->user['id'])->first();
|
|
$data['role'] = $user['role'];
|
|
if(!empty($data['source_url'])){
|
|
$used = UsedCar::where('source_url', $data['source_url']);
|
|
if ($data['role'] == 1) {
|
|
$used = $used->where('user_id', $data['user_id']);
|
|
}
|
|
$count = $used->count();
|
|
if ($count) {
|
|
throw new BusinessException('该车源已收录');
|
|
}
|
|
}
|
|
$data['code'] = $this->getcode($request->user['id']);
|
|
$data['mileage'] = str_replace(['K','M','k','m'], '', $data['mileage']);
|
|
return $data;
|
|
}
|
|
|
|
public function beforeServiceUpdate($data, Request $request): array
|
|
{
|
|
if (empty($data['product_name'])) {
|
|
throw new BusinessException('产品名称不能为空');
|
|
}
|
|
if (empty($data['images'])) {
|
|
throw new BusinessException('产品图片不能为空');
|
|
}
|
|
if (empty($data['price'])) {
|
|
$data['price'] = 0;
|
|
}
|
|
if (!empty($data['attachment'])) {
|
|
$data['attachment'] = json_encode($data['attachment']);
|
|
}else{
|
|
$data['attachment'] = '';
|
|
}
|
|
$data['mileage'] = str_replace(['K','M','k','m'], '', $data['mileage']);
|
|
return $data;
|
|
}
|
|
|
|
public function serviceUpdateStatus(Request $request, array $data)
|
|
{
|
|
if (empty($data['id'])) {
|
|
throw new BusinessException('id不能为空');
|
|
}
|
|
if (!isset($data['status'])) {
|
|
throw new BusinessException('status错误');
|
|
}
|
|
return UsedCar::where('id', $data['id'])->update(['status' => $data['status']]);
|
|
}
|
|
|
|
public function getcode($userId){
|
|
$userCount = Redis::get('used_car_count_'.$userId, 0);
|
|
$todayStart = strtotime('today');
|
|
$count = UsedCar::where('user_id',$userId)->where('created_at','>=',$todayStart)->count();
|
|
$count = $count<$userCount ? $userCount +1 : $count +1;
|
|
$countCode = str_pad($count, 3, '0', STR_PAD_LEFT);
|
|
$userCode = str_pad($userId, 3, '0', STR_PAD_LEFT);
|
|
Redis::set('used_car_count_'.$userId, $count, 86400);
|
|
$user = User::where('id',$userId)->first();
|
|
$nameInitials = $this->getNameInitials($user['name']);
|
|
return $nameInitials . $userCode . date('Ymd') . $countCode;
|
|
}
|
|
|
|
|
|
/**
|
|
* 获取中文名拼音首字母
|
|
*/
|
|
function getNameInitials(string $name): string
|
|
{
|
|
$initials = '';
|
|
$len = mb_strlen($name);
|
|
for ($i = 0; $i < $len; $i++) {
|
|
$char = mb_substr($name, $i, 1);
|
|
$initials .= $this->getFirstChar($char);
|
|
}
|
|
return strtoupper($initials);
|
|
}
|
|
|
|
function getFirstChar(string $char): string
|
|
{
|
|
$s = iconv('UTF-8', 'GB2312//IGNORE', $char);
|
|
$asc = ord($s[0]);
|
|
|
|
if ($asc >= 65 && $asc <= 90) return $char;
|
|
|
|
// 转码失败或长度不足
|
|
if ($s === false || strlen($s) < 2) {
|
|
return '';
|
|
}
|
|
$code = ord($s[0]) * 256 + ord($s[1]) - 65536;
|
|
|
|
$map = [
|
|
[-20319, -20284, 'A'],
|
|
[-20283, -19776, 'B'],
|
|
[-19775, -19219, 'C'],
|
|
[-19218, -18711, 'D'],
|
|
[-18710, -18527, 'E'],
|
|
[-18526, -18240, 'F'],
|
|
[-18239, -17923, 'G'],
|
|
[-17922, -17418, 'H'],
|
|
[-17417, -16475, 'J'],
|
|
[-16474, -16213, 'K'],
|
|
[-16212, -15641, 'L'],
|
|
[-15640, -15166, 'M'],
|
|
[-15165, -14923, 'N'],
|
|
[-14922, -14915, 'O'],
|
|
[-14914, -14631, 'P'],
|
|
[-14630, -14150, 'Q'],
|
|
[-14149, -14091, 'R'],
|
|
[-14090, -13319, 'S'],
|
|
[-13318, -12839, 'T'],
|
|
[-12838, -12557, 'W'],
|
|
[-12556, -11848, 'X'],
|
|
[-11847, -11056, 'Y'],
|
|
[-11055, -10247, 'Z']
|
|
];
|
|
|
|
foreach ($map as [$start, $end, $letter]) {
|
|
if ($code >= $start && $code <= $end) {
|
|
return $letter;
|
|
}
|
|
}
|
|
return '';
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
* 抓取车型数据(通过接口)
|
|
* @param Request $request
|
|
* @return array
|
|
* @throws \Exception
|
|
*/
|
|
public function crawlKeyword(Request $request): array
|
|
{
|
|
$keyword = $request->get('keyword');
|
|
|
|
// 执行抓取
|
|
$crawlService = new CrawlService();
|
|
|
|
//懂车帝模糊搜索返回车系地址|单个车系id抓取
|
|
$href = $crawlService->modelSearch($keyword);
|
|
$seriesId = $this->extractSeriesId($href); //懂车帝车系id
|
|
|
|
// if (empty($seriesId)) { //没有抓取到懂车帝系列id时,按关键词为品牌名抓取所有的系列名
|
|
// $crawlSeries = $crawlService->brandSeries($keyword);
|
|
// }
|
|
//按关键词为品牌名抓取所有的系列名
|
|
// $crawlSeries = $crawlService->brandSeries($keyword);
|
|
|
|
if (empty($seriesId)) {
|
|
throw new \Exception('抓取失败,请使用更精确的关键词');
|
|
}
|
|
|
|
// $brandSerieses = [];
|
|
// if(empty($seriesId) && !empty($crawlSeries) || count($crawlSeries)>1){ //关键词为品牌名时抓取所有车系的懂车帝id
|
|
// $href = $crawlService->modelSearch($crawlSeries[0]);
|
|
// $seriesId = $this->extractSeriesId($href); //懂车帝车系id
|
|
// //抓取品牌与系列
|
|
// $brandSeries = $crawlService->crawlBrandSeries($seriesId);
|
|
// foreach ($crawlSeries as $item) {
|
|
//// $brandSerieses[] = $crawlService->brandSeries($keyword);
|
|
// $brandSerieses[] = ['brand' => $brandSeries['brand'], 'series' => $item];
|
|
// }
|
|
// }elseif (!empty($seriesId) && empty($crawlSeries)){
|
|
// //抓取品牌与系列
|
|
// $brandSerieses[] = $crawlService->crawlBrandSeries($seriesId);
|
|
// }
|
|
//抓取品牌与系列
|
|
$brandSerieses[] = $crawlService->crawlBrandSeries($seriesId);
|
|
|
|
$result = [];
|
|
try {
|
|
foreach ($brandSerieses as $brandSeries) {
|
|
$item = [];
|
|
$item['brand'] = ['brand_name' => $brandSeries['brand']];
|
|
$item['series'] = ['series_name' => $brandSeries['series']];
|
|
|
|
//获取车型数据
|
|
$item['model'] = [];
|
|
if (count($brandSerieses) < 2) {
|
|
$item['model'] = $this->crawlSeriesModel($seriesId);
|
|
}
|
|
$result[] = $item;
|
|
}
|
|
|
|
return $result[0];
|
|
} catch (\Exception $e) {
|
|
throw new \Exception($e->getMessage());
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 获取车系下车型数据
|
|
* @return array
|
|
* @throws \GuzzleHttp\Exception\GuzzleException
|
|
*/
|
|
public function crawlSeriesModel($seriesId)
|
|
{
|
|
$client = new Client([
|
|
'verify' => false, // 禁用 SSL 验证
|
|
'timeout' => 10
|
|
]);
|
|
try {
|
|
$response = $client->get('https://www.dongchedi.com/motor/pc/car/series/car_list', [
|
|
'query' => ['series_id' => $seriesId],
|
|
'headers' => [
|
|
'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
|
|
]
|
|
]);
|
|
$data = json_decode($response->getBody()->getContents(), true);
|
|
if ($data['status'] != 0 || (!isset($data['data']) && !isset($data['data']['tab_list']))) {
|
|
Log::error('抓取车型数据失败' . $data['message'], $data);
|
|
throw new \Exception('抓取车型数据失败' . $data['message']);
|
|
}
|
|
$models = [];
|
|
foreach ($data['data']['tab_list'] as $item) {
|
|
if ($item['tab_text'] == '在售' || $item['tab_text'] == '停售') {
|
|
unset($item['data'][0]);
|
|
$models = array_merge($models, $item['data']);
|
|
}
|
|
}
|
|
foreach ($models as $key => $model) {
|
|
if (!isset($model["info"]['car_name']) || $model['type'] != "1115") {
|
|
unset($models[$key]);
|
|
continue;
|
|
}
|
|
$official_price = 0;
|
|
if (!isset($model["info"]['official_price'])) {
|
|
$official_price = (int)(str_replace("万", "", $model["info"]['official_price_str']) * 10000) ?? 0;
|
|
} else {
|
|
$official_price = $model["info"]['official_price'] * 10000;
|
|
}
|
|
$models[$key] = [
|
|
'title' => $model["info"]['year'] . '款 ' . $model["info"]['car_name'],
|
|
'brand_id' => $model["info"]['brand_id'],
|
|
'brand_name' => $model["info"]['brand_name'],
|
|
'series_id' => $model["info"]['series_id'],
|
|
'series_name' => $model["info"]['series_name'],
|
|
'year' => $model["info"]['year'],
|
|
'msrp' => $official_price,
|
|
'car_id' => $model["info"]['id'],
|
|
];
|
|
}
|
|
|
|
return array_values($models);
|
|
} catch (\Exception $e) {
|
|
throw new \Exception($e->getMessage());
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 从懂车帝URL中提取series ID
|
|
* @param string $url 完整的URL
|
|
* @return string|null series ID或null
|
|
*/
|
|
function extractSeriesId($url)
|
|
{
|
|
// 解析URL获取路径部分
|
|
$path = parse_url($url, PHP_URL_PATH);
|
|
|
|
if (!$path) {
|
|
return null;
|
|
}
|
|
|
|
// 按斜杠分割路径
|
|
$pathParts = explode('/', trim($path, '/'));
|
|
|
|
// 查找 'series' 的位置,下一个元素就是series ID
|
|
$seriesIndex = array_search('series', $pathParts);
|
|
|
|
if ($seriesIndex !== false && isset($pathParts[$seriesIndex + 1])) {
|
|
return $pathParts[$seriesIndex + 1];
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
function downloadImage(string $url): string
|
|
{
|
|
$dir = runtime_path('pdf/images/');
|
|
if (!is_dir($dir)) {
|
|
mkdir($dir, 0755, true);
|
|
}
|
|
|
|
$filename = md5($url) . '.jpg';
|
|
$path = $dir . $filename;
|
|
|
|
if (!file_exists($path)) {
|
|
$img = file_get_contents($url);
|
|
file_put_contents($path, $img);
|
|
}
|
|
|
|
return $path;
|
|
}
|
|
|
|
function downloadAttachment(string $url): string
|
|
{
|
|
$dir = runtime_path('pdf/attachment/');
|
|
if (!is_dir($dir)) {
|
|
mkdir($dir, 0755, true);
|
|
}
|
|
|
|
$filename = md5($url) . '.pdf';
|
|
$path = $dir . $filename;
|
|
|
|
if (!file_exists($path)) {
|
|
$img = file_get_contents($url);
|
|
file_put_contents($path, $img);
|
|
}
|
|
|
|
return $path;
|
|
}
|
|
}
|