Files
useds/app/common/controller/UsedCarController.php
T

517 lines
19 KiB
PHP
Raw Normal View History

2026-01-05 15:28:19 +08:00
<?php
namespace app\common\controller;
2026-01-09 13:08:17 +08:00
use app\common\model\UsedCar;
2026-01-12 11:52:07 +08:00
use app\common\model\UsedCarPdfLog;
use app\common\model\User;
2026-01-05 16:15:27 +08:00
use app\common\service\OssService;
2026-01-14 18:37:15 +08:00
use app\common\service\SparkService;
2026-01-05 15:28:19 +08:00
use app\common\traits\crud\CrudControllerTrait;
use app\common\service\UsedCarService;
2026-01-16 18:02:30 +08:00
use app\common\utils\crawl\service\UsedCarCrawlSingle;
2026-01-09 13:08:17 +08:00
use app\common\utils\pdf\service\MpdfDriver;
2026-01-09 16:17:50 +08:00
use support\exception\BusinessException;
2026-01-08 14:30:42 +08:00
use support\Request;
2026-01-05 15:28:19 +08:00
class UsedCarController extends BaseController
{
use CrudControllerTrait;
protected $service;
2026-01-09 15:03:30 +08:00
protected $noNeedLogin = ['downloadPdf'];
protected $noNeedHeaderData = ['downloadPdf'];
2026-01-14 18:37:15 +08:00
protected $lang = [
'en' => '英语',
'ru' => '俄语',
'es' => '西班牙语',
'ar' => '阿拉伯语',
];
protected $currency = [
'USD' => '$',
'RUB' => '₽',
'AED' => 'د.إ',
'EUR' => '€',
2026-01-16 11:35:50 +08:00
'CNY' => '¥',
2026-01-14 18:37:15 +08:00
];
2026-01-05 15:28:19 +08:00
public function __construct()
{
$this->service = new UsedCarService();
}
2026-01-16 15:15:36 +08:00
/**
* 更新状态
* @return \support\Response
*/
public function status(Request $request){
try {
$data = $request->post();
$res = $this->service->serviceUpdateStatus($request, $data);
return $this->success([], '更新成功');
} catch (\Throwable $e) {
return $this->error($e->getMessage());
}
}
2026-01-05 15:28:19 +08:00
/**
* 列表页数据格式化
*
* @param array $data
* @return array
*/
2026-01-05 16:15:27 +08:00
protected function indexFormat($data)
{
if (isset($data['created_at']))
$data['created_at'] = date('Y-m-d H:i:s', $data['created_at']);
if (isset($data['updated_at']))
$data['updated_at'] = date('Y-m-d H:i:s', $data['updated_at']);
if (!empty($data['images'])){
$images = explode(',', $data['images']);
$ossService = new OssService();
$images_pull = [];
foreach ($images as $image){
$images_pull[] = $ossService->generatePrivateUrl($image);
}
$data['images_pull'] = $images_pull;
}
return $data;
}
2026-01-05 17:30:53 +08:00
/**
* 列表页数据格式化
*
* @param array $data
* @return array
*/
protected function showFormat($data)
{
if (isset($data['created_at']))
$data['created_at'] = date('Y-m-d H:i:s', $data['created_at']);
if (isset($data['updated_at']))
$data['updated_at'] = date('Y-m-d H:i:s', $data['updated_at']);
if (!empty($data['images'])){
$images = explode(',', $data['images']);
$ossService = new OssService();
$images_pull = [];
2026-01-19 09:50:18 +08:00
//图片压缩参数 resize,w_1200:最大宽度1200px,quality,Q_50:图片质量如压缩到50%,format,webp:自动转 WebP
2026-01-22 14:01:41 +08:00
$process = 'image/resize,w_800/quality,Q_50/format,webp';
2026-01-05 17:30:53 +08:00
foreach ($images as $image){
2026-01-19 09:50:18 +08:00
$images_pull[] = $ossService->generatePrivateUrlResize($image,3600,$process);
2026-01-05 17:30:53 +08:00
}
$data['images_pull'] = $images_pull;
2026-01-09 15:32:27 +08:00
}else{
$data['images_pull'] = [];
2026-01-09 13:08:17 +08:00
}
if (!empty($data['attachment'])){
2026-01-09 15:03:30 +08:00
//$attachments = explode(',', $data['attachment']);
$attachments = json_decode($data['attachment'], true);
2026-01-09 13:08:17 +08:00
$ossService = new OssService();
$attachment_pull = [];
foreach ($attachments as $attachment){
2026-01-09 15:03:30 +08:00
$attachment_pull[] = [
'name'=>$attachment['name'],
2026-01-15 13:10:44 +08:00
'src'=>$attachment['src'],
'src_pull'=>$ossService->generatePrivateUrl($attachment['src']),
2026-01-09 15:03:30 +08:00
];
2026-01-09 13:08:17 +08:00
}
$data['attachment_pull'] = $attachment_pull;
2026-01-09 15:32:27 +08:00
}else{
$data['attachment_pull'] = [];
2026-01-05 17:30:53 +08:00
}
2026-01-09 15:32:27 +08:00
2026-01-05 17:30:53 +08:00
return $data;
}
2026-01-08 14:30:42 +08:00
2026-01-16 18:02:30 +08:00
public function crawlCar(Request $request)
{
try {
$url = $request->get('url');
if (empty($url)){
throw new BusinessException('url不能为空');
}
$info = (new UsedCarCrawlSingle())->crawlCar($url);
$data = [
'user_id' => $request->user['id'],
'product_name' => $info['title'],
'price' => $info['price']<200 ? $info['price']*10000 : $info['price'],
'source_place' => $info['source_place'],
'displacement' => $info['capacity'], //排量
'mileage' => $info['usage_mileage']*10000, //里程
'power' => $info['horsepower'], //马力
'body_color' => $info['body_color'],
'images' => $info['image'],
'image_pull' => $info['image_pull'],
'condition_desc' => $info['condition_desc'],
'attachment' => '',
'source_url' => $url,
'crawl_car_id' => $info['car_id'],
2026-01-19 10:08:50 +08:00
'crawl_title' => $info['car_name'],
2026-01-16 18:02:30 +08:00
'crawl_brand_id' => $info['brand_id'],
2026-01-19 10:08:50 +08:00
'crawl_brand' => $info['brand_name'],
2026-01-16 18:02:30 +08:00
'crawl_series_id' => $info['series_id'],
2026-01-19 10:08:50 +08:00
'crawl_series' => $info['series_name'],
2026-01-16 18:02:30 +08:00
'used_car_id' => $info['used_car_id'],
2026-01-19 10:23:31 +08:00
'crawl_year' => $info['year'],
2026-01-16 18:25:25 +08:00
'plate_time' => $info['plate_time'],
2026-01-16 18:02:30 +08:00
];
return $this->success($data);
} catch (\Throwable $e) {
2026-01-19 14:53:28 +08:00
if (str_contains($e->getMessage(), '404 Not Found')){
return $this->error('车辆已下架或找不到页面');
}
return $this->error($e->getMessage());
2026-01-16 18:02:30 +08:00
}
}
2026-01-08 14:30:42 +08:00
public function crawlKeyword(Request $request){
try {
// $keyword = $request->get('keyword');
$data = $this->service->crawlKeyword($request);
return $this->success($data);
} catch (\Throwable $e) {
return $this->error($e->getMessage());
}
}
2026-01-09 13:08:17 +08:00
2026-01-12 11:52:07 +08:00
/**
* 生成pdf
* @param Request $request
* @return \support\Response
*/
2026-01-09 13:08:17 +08:00
public function producePdf(Request $request){
try {
2026-01-22 14:09:49 +08:00
set_time_limit(40);
2026-01-12 11:52:07 +08:00
$price = $request->get('price');
2026-01-14 18:37:15 +08:00
$lang = $request->get('lang');
$currency = $request->get('currency');
2026-01-16 14:29:48 +08:00
$trade = $request->get('trade_term');
2026-01-12 11:52:07 +08:00
if(empty($price)){
throw new BusinessException("请输入生成pdf中的价格");
}
2026-01-14 18:37:15 +08:00
if(empty($lang) || empty($this->lang[$lang])){
throw new BusinessException("语种错误");
}
if(empty($currency) || empty($this->currency[$currency])){
throw new BusinessException("币种错误");
}
2026-01-09 13:08:17 +08:00
$raw = $this->service->serviceShow($request);
$data = $this->transformData($raw, method_exists($this, 'showFormat')
? [$this, 'showFormat']
: null);
$images = [];
2026-01-12 11:52:07 +08:00
foreach ($data['images_pull'] as $image){
2026-01-09 13:08:17 +08:00
$images[] = $this->service->downloadImage($image);
}
$data['images'] = $images;
2026-01-09 15:03:30 +08:00
$attachments = [];
foreach ($data['attachment_pull'] as $attachment){
// 方法1:使用 pathinfo
$path = parse_url($attachment['src'], PHP_URL_PATH); // 获取路径部分
$extension = pathinfo($path, PATHINFO_EXTENSION); // 获取扩展名
if (strtolower($extension) === 'pdf') { //如果是pdf则下载到本地
$attachments[] = $this->service->downloadAttachment($attachment['src']);
}
}
$data['attachment'] = $attachments;
2026-01-12 13:40:57 +08:00
$data['price'] = $price;
$user = User::where('id',$request->user['id'])->first();
$contact = $user['email'] ?? $user['phone'] ?? $user['whatsapp'] ?? null;
if(!empty($user['social_code'])){
$ossService = new OssService();
$user['social_code'] = $ossService->generatePrivateUrl($user['social_code']);
$user['social_code'] = $this->service->downloadImage($user['social_code']);
}
2026-01-14 18:37:15 +08:00
$field = $this->field($lang);//字段相关外文
$field['currency'] = $this->currency[$currency];
2026-01-19 10:23:31 +08:00
$data['product_name'] = $data['crawl_brand'].' '.$data['crawl_series'].' '. $data['crawl_year'] .'款 '.$data['crawl_title'];
2026-01-14 18:37:15 +08:00
$data = $this->fanyi($data, $lang);//车辆字段翻译外文
$contactField = $this->contact($lang); //名片相关外文
2026-01-16 14:29:48 +08:00
$data['trade'] = $trade;
2026-01-15 10:30:48 +08:00
$pdf = (new MpdfDriver())->exportUsedCarPdf($field,$data,$user,$contactField,$contact,$lang);
2026-01-09 13:08:17 +08:00
UsedCar::where('id', $data['id'])->update(['pdf_src' => $pdf]);
array_map('unlink', glob(runtime_path('pdf/images/*.jpg')));
2026-01-09 15:03:30 +08:00
array_map('unlink', glob(runtime_path('pdf/attachment/*.pdf')));
2026-01-12 11:52:07 +08:00
UsedCarPdfLog::create([
'user_id' => $request->user['id'],
'used_car_id' => $request->get('id'),
'price_snapshot' => $price,
'pdf_path' => $pdf,
]);
2026-01-09 13:08:17 +08:00
return $this->success($pdf);
} catch (\Throwable $e) {
2026-01-14 18:37:15 +08:00
return $this->error($e->getMessage().$e->getLine().$e->getFile());
2026-01-09 13:08:17 +08:00
}
}
public function downloadPdf(Request $request){
$raw = $this->service->serviceShow($request);
2026-01-09 15:03:30 +08:00
$filePath = runtime_path('pdf') .'/'. $raw['pdf_src'];
2026-01-09 13:08:17 +08:00
if (!file_exists($filePath)) {
2026-01-09 15:03:30 +08:00
return response($filePath.'文件不存在', 404);
2026-01-09 13:08:17 +08:00
}
return response()->download(
$filePath,
2026-01-19 10:23:31 +08:00
$raw['product_name']. '-' .$raw['code'].'-'.$raw['id'].'.pdf' // 下载时显示的文件名
2026-01-09 13:08:17 +08:00
);
}
2026-01-09 16:17:50 +08:00
2026-01-14 18:37:15 +08:00
public function fanyi($data, $to){
foreach ($data as $k => $v) {
2026-01-19 13:41:50 +08:00
if (in_array($k, ['product_name', 'source_place', 'body_color', 'condition_desc', 'displacement']) && !empty(trim($v))) {
2026-01-14 18:37:15 +08:00
// $xunfei = new XunfeiFanyi();
// $data[$k] = $xunfei->fanyi($v, $from = 'cn', $to);
$toLang = $this->lang[$to];
$spark = new SparkService();
$str = $spark->chat("将“{$v}”翻译为{$toLang},不要有多余的描述");
2026-01-15 09:40:58 +08:00
if(!empty($str)){
$str = preg_replace('/[\x{4e00}-\x{9fa5}]/u', '', $str);
$data[$k] =str_replace(['(',')','(',')','"'], '', $str);
}else{
$data[$k] = '';
}
2026-01-14 18:37:15 +08:00
}
}
return $data;
}
/**
* 字段名
* @param $data
* @param $to
* @return mixed
*/
public function field($to){
$field = [
'cn' => [
'price' => '车价',
'source_place' => '车源地',
'plate_time' => '上牌时间',
'displacement' => '排量',
'mileage' => '里程',
'power' => '马力',
'body_color' => '车身颜色',
'created_at' => '创建时间',
'condition_desc' => '车况介绍',
'images' => '产品图',
2026-01-16 14:29:48 +08:00
'trade' => '贸易条款',
2026-01-14 18:37:15 +08:00
],
'en' => [
'price' => 'Price',
'source_place' => 'Vehicle Location',
'plate_time' => 'Registration Date',
'displacement' => 'Engine Displacement',
'mileage' => 'Mileage',
'power' => 'Horsepower',
'body_color' => 'Body Color',
'created_at' => 'Created At',
'condition_desc' => 'Vehicle Condition',
2026-01-15 10:30:48 +08:00
'images' => 'Product image',
2026-01-16 14:29:48 +08:00
'trade' => 'Trade terms',
2026-01-14 18:37:15 +08:00
],
'ru' => [
'price' => 'Цена',
'source_place' => 'Местонахождение автомобиля',
'plate_time' => 'Дата регистрации',
'displacement' => 'Объём двигателя',
'mileage' => 'Пробег',
'power' => 'Мощность',
'body_color' => 'Цвет кузова',
'created_at' => 'Дата создания',
'condition_desc' => 'Состояние автомобиля',
'images' => 'Фотографии',
2026-01-16 14:29:48 +08:00
'trade' => 'Условия торговли',
2026-01-14 18:37:15 +08:00
],
'es' => [
'price' => 'Precio',
'source_place' => 'Ubicación del vehículo',
'plate_time' => 'Fecha de matriculación',
'displacement' => 'Cilindrada',
'mileage' => 'Kilometraje',
'power' => 'Potencia',
'body_color' => 'Color de la carrocería',
'created_at' => 'Fecha de creación',
'condition_desc' => 'Estado del vehículo',
2026-01-15 10:30:48 +08:00
'images' => 'Imagen del producto',
2026-01-16 14:29:48 +08:00
'trade' => 'Условия торговли',
2026-01-14 18:37:15 +08:00
],
'ar' => [
'price' => 'السعر',
'source_place' => 'موقع السيارة',
'plate_time' => 'تاريخ التسجيل',
'displacement' => 'سعة المحرك',
'mileage' => 'المسافة المقطوعة',
'power' => 'قوة المحرك',
'body_color' => 'لون الهيكل',
'created_at' => 'تاريخ الإنشاء',
'condition_desc' => 'حالة السيارة',
2026-01-15 10:30:48 +08:00
'images' => 'خريطة المنتج',
2026-01-16 14:29:48 +08:00
'trade' => 'شروط التجارة',
2026-01-14 18:37:15 +08:00
],
];
return $field[$to];
// foreach ($field as $k => $v) {
//// $xunfei = new XunfeiFanyi();
//// $field[$k] = $xunfei->fanyi($v, $from = 'cn', $to);
// $toLang = $this->lang[$to];
// $spark = new SparkService();
// $field[$k] = $spark->chat("“{$v}”翻译为{$toLang},不要有多余的描述");
// }
// return $field;
}
/**
* 名片外文
*/
public function contact($to){
$contactField = [
'cn' => [
'title' => '联系人名片',
'name' => '姓名',
'email' => '邮箱',
'phone' => '电话',
'WhatsApp' => 'WhatsApp',
'code' => '二维码',
2026-01-15 10:30:48 +08:00
'left' => '扫码即可联系本人',
'right' => '本资料随PDF自动生成',
2026-01-14 18:37:15 +08:00
],
'en' => [
'title' => 'Contact Name Card',
'name' => 'Name',
'email' => 'Email',
'phone' => 'Phone',
'WhatsApp' => 'WhatsApp',
'code' => 'QR Code',
2026-01-15 10:30:48 +08:00
'left' => 'Scan the code to contact me',
'right' => 'This information is automatically generated with the PDF',
2026-01-14 18:37:15 +08:00
],
'ru' => [
'title' => 'Контактная карточка',
'name' => 'Имя',
'email' => 'Электронная почта',
'phone' => 'Телефон',
'WhatsApp' => 'WhatsApp',
'code' => 'QR-код',
2026-01-15 10:30:48 +08:00
'left' => 'Код позволяет связаться с самим собой.',
'right' => 'Эта информация автоматически генерируется с помощью PDF',
2026-01-14 18:37:15 +08:00
],
'es' => [
'title' => 'Tarjeta de visita de contacto',
'name' => 'Nombre',
'email' => 'Correo electrónico',
'phone' => 'Teléfono',
'WhatsApp' => 'WhatsApp',
'code' => 'Código QR',
2026-01-15 10:30:48 +08:00
'left' => 'Escanee el Código para contactarme.',
'right' => 'Esta información se genera automáticamente con pdf',
2026-01-14 18:37:15 +08:00
],
'ar' => [
'title' => 'بطاقة الاتصال',
'name' => 'الاسم',
'email' => 'البريد الإلكتروني',
'phone' => 'الهاتف',
'WhatsApp' => 'واتساب',
'code' => 'رمز QR',
2026-01-15 10:30:48 +08:00
'left' => 'اكتساح رمز الاتصال بي',
'right' => 'هذه المعلومات تلقائيا مع قوات الدفاع الشعبي',
2026-01-14 18:37:15 +08:00
],
];
return $contactField[$to];
}
2026-01-09 16:17:50 +08:00
public function getPdf(Request $request)
{
try {
$raw = $this->service->serviceShow($request);
$filePath = runtime_path('pdf') . '/' . $raw['pdf_src'];
if (empty($raw['pdf_src']) || !file_exists($filePath)) {
throw new BusinessException('文件不存在');
}
// 确保 public/pdf 存在
$publicDir = public_path('pdf');
if (!is_dir($publicDir)) {
mkdir($publicDir, 0755, true);
}
// 拷贝到 public 目录
$publicFile = $publicDir . '/' . $raw['pdf_src'];
if (!file_exists($publicFile)) {
copy($filePath, $publicFile);
}
// 返回访问地址
2026-01-15 10:54:21 +08:00
$baseUrl = 'https://' . request()->header('host');
2026-01-09 16:17:50 +08:00
$url = $baseUrl . '/pdf/' . $raw['pdf_src'];
return $this->success([
'pdf_url' => $url,
2026-01-19 10:23:31 +08:00
'file_name' => $raw['product_name']. '-' .$raw['code']. '-' . $raw['id'] . '.pdf'
2026-01-09 16:17:50 +08:00
]);
} catch (\Throwable $e) {
return $this->error($e->getMessage());
}
}
2026-01-15 11:42:02 +08:00
/**
* 预览pdf
*/
function previewPdf($request) {
try {
$raw = $this->service->serviceShow($request);
$filePath = runtime_path('pdf') . '/' . $raw['pdf_src'];
if (empty($raw['pdf_src']) || !file_exists($filePath)) {
throw new BusinessException('文件不存在');
}
// 确保 public/pdf 存在
$publicDir = public_path('pdf');
if (!is_dir($publicDir)) {
mkdir($publicDir, 0755, true);
}
// 拷贝到 public 目录
$publicFile = $publicDir . '/' . $raw['pdf_src'];
if (!file_exists($publicFile)) {
copy($filePath, $publicFile);
}
$path = public_path('pdf/' . basename($raw['pdf_src']));
return response(file_get_contents($path), 200, [
'Content-Type' => 'application/pdf',
'Access-Control-Allow-Origin' => '*', // 或指定前端域名
'Access-Control-Allow-Methods' => 'GET, OPTIONS',
'Access-Control-Allow-Headers' => '*',
]);
} catch (\Throwable $e) {
return $this->error($e->getMessage());
}
}
2026-01-05 15:28:19 +08:00
}