Files
bsh_sample/app/admin/controller/SkuController.php
T
2025-12-15 14:52:43 +08:00

241 lines
7.6 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace app\admin\controller;
use app\common\controller\BaseController;
use app\common\model\PostCategory;
use app\common\model\Sku;
use app\common\model\SkuAttribute;
use app\common\service\OssService;
use app\common\service\UploadService;
use app\common\traits\crud\CrudControllerTrait;
use app\common\service\SkuService;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;
use support\Db;
use support\Request;
use support\Response;
class SkuController extends BaseController
{
use CrudControllerTrait;
protected $noNeedLogin = ['template'];
protected $noNeedHeaderData = ['template'];
protected $service;
public function __construct()
{
$this->service = new SkuService();
}
/**
* 创建
*
* @param Request $request 请求对象
* @return mixed 返回创建成功的数据或信息
*/
public function store(Request $request)
{
try {
$data = $this->validate($this->service->getValidator(), $request->post(), 'store');
$res = $this->service->serviceStore($request, $data);
return $this->success($res, '创建成功');
} catch (\Throwable $e) {
return $this->error($e->getMessage());
}
}
/**
* 列表页数据格式化
*
* @param array $data
* @return array
*/
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 (isset($data['spec_json'])){
$data['spec'] = json_decode($data['spec_json'], true);
foreach ($data['spec'] as $k=>$v){
$data['spec'][$k]['attr_type'] = SkuAttribute::where('id', $v['attr_id'])->value('attr_type');
}
}
if (isset($data['category_id']))
$data['category_name'] = PostCategory::where('id', $data['category_id'])->value('name');
$ossservice = new OssService();
if (!empty($data['image'])){
$data['image'] = explode(',',$data['image']);
foreach ($data['image'] as $key => $image){
$data['image_pull'][$key] = $ossservice->generatePrivateUrl($image);
}
}else{
$data['image'] = [];
$data['image_pull'] = [];
}
if (!empty($data['main_image'])){
$data['main_image_pull'] = $ossservice->generatePrivateUrl($data['main_image']);
} else {
$data['main_image_pull'] = [];
}
return $data;
}
public function import(Request $request)
{
$file = $request->file('file');
if (!$file) return json(['code'=>1,'msg'=>'未上传文件']);
$path = runtime_path('upload/' . uniqid() . '.xlsx');
$file->move($path);
$spreadsheet = IOFactory::load($path);
$sheet = $spreadsheet->getActiveSheet();
// 提取图片(按行号)
$rowImages = $this->extractImages($sheet);
$highestRow = $sheet->getHighestRow();
$highestCol = $sheet->getHighestColumn();
$header = $sheet->rangeToArray("A1:{$highestCol}1")[0];
// $header = array_map('trim', $header);
$allowFields = [
'product_name' => '产品名称',
'model' => '产品型号',
'brand' => '品牌',
'category_id' => '分类',
'price' => '价格',
// 'spec_json' => '商品属性'
];
$fieldsName = array_flip($allowFields);
$insertData = [];
$now = time();
Db::beginTransaction();
try {
for ($row = 2; $row <= $highestRow; $row++) {
$rowData = $sheet->rangeToArray(
"A{$row}:{$highestCol}{$row}", null, true, false
)[0];
$data = [];
foreach ($header as $i => $field) {
if (in_array($field, $allowFields)) {
$data[$fieldsName[$field]] = trim((string)($rowData[$i] ?? ''));
}
}
if (empty($data['product_name'])) {
continue;
}
$data['category_id'] = PostCategory::where('name', $rowData[3])->value('id')??0;
if(!empty($rowData[5])){
$speci = explode(';', $rowData[5]);
$spec = [];
foreach ($speci as $k => $v){
$item = explode(':', $v);
if (count($item) != 2) {
continue;
}
$attr = ['attr_name'=>$item[0],'attr_value'=>$item[1]];
$skuAttribute = SkuAttribute::where('attr_name', $item[0])->first();
if (empty($skuAttribute)) {
continue;
}
$attr['attr_id'] = $skuAttribute->id;
$attr['category_id'] = $skuAttribute->category_id;
$spec[] = $attr;
$data['spec_json'] = json_encode($spec);
}
}
$data['code'] = $this->service->generateUniqueCode();
$data['brand'] = $data['brand'] ?: '西门子';
$data['price'] = $data['price'] ?: 0;
$data['status'] = $data['status'] ?? 2;
// 图片
$data['main_image'] = $rowImages[$row] ?? null;
$data['created_at'] = $now;
$data['updated_at'] = $now;
$insertData[] = $data;
var_dump($insertData);
if (count($insertData) >= 200) {
Sku::insert($insertData);
// Db::table('sku')->insert($insertData);
$insertData = [];
}
}
if ($insertData) {
Sku::insert($insertData);
// Db::table('sku')->insert($insertData);
}
Db::commit();
} catch (\Throwable $e) {
Db::rollBack();
return $this->error($e->getMessage());
} finally {
@unlink($path);
}
return $this->success([], '导入成功');
}
private function extractImages($sheet): array
{
$images = [];
$uploadService = new UploadService();
foreach ($sheet->getDrawingCollection() as $drawing) {
if ($drawing instanceof Drawing) {
// 取行号
preg_match('/\d+/', $drawing->getCoordinates(), $m);
$row = (int)$m[0];
// Excel 临时图片路径
$tmpPath = $drawing->getPath();
if (!is_file($tmpPath)) {
continue;
}
// 上传到 OSS
$ossUrl = $uploadService->uploadLocalFile(['path' => $tmpPath, 'scene' => 'sku']);
// 一行只保留一张主图
$images[$row] = $ossUrl['file_url'];
}
}
return $images;
}
/**
* 下载 Excel 示例模板
*/
public function template(Request $request): Response
{
$filePath = runtime_path() . '/upload/import.xlsx';
if (!file_exists($filePath)) {
return response('文件不存在', 404);
}
return response()->download(
$filePath,
'导入示例.xlsx' // 下载时显示的文件名
);
}
}