236 lines
7.2 KiB
PHP
236 lines
7.2 KiB
PHP
<?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 support\Db;
|
|
use support\Request;
|
|
use support\Response;
|
|
use ZipArchive;
|
|
|
|
class SkuController extends BaseController
|
|
{
|
|
use CrudControllerTrait;
|
|
|
|
protected $noNeedLogin = ['template'];
|
|
|
|
protected $noNeedHeaderData = ['template'];
|
|
|
|
protected $service;
|
|
|
|
public function __construct()
|
|
{
|
|
$this->service = new SkuService();
|
|
}
|
|
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().$e->getLine().$e->getFile());
|
|
}
|
|
}
|
|
/**
|
|
* 列表页数据格式化
|
|
*
|
|
* @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);
|
|
}
|
|
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);
|
|
}
|
|
}
|
|
if (!empty($data['main_image'])){
|
|
$data['main_image_pull'] = $ossservice->generatePrivateUrl($data['main_image']);
|
|
}
|
|
return $data;
|
|
}
|
|
|
|
|
|
|
|
public function import(Request $request)
|
|
{
|
|
// ini_set('memory_limit', '512M');
|
|
$file = $request->file('file');
|
|
if (!$file) return $this->error('未上传文件');;
|
|
|
|
$zipPath = runtime_path('upload/' . uniqid() . '.zip');
|
|
$file->move($zipPath);
|
|
|
|
$extractTo = runtime_path('upload/import/');
|
|
|
|
clearstatcache(true, $zipPath);
|
|
$this->unzipPackage($zipPath,$extractTo);
|
|
|
|
$path = runtime_path('upload/import/product.xlsx');
|
|
$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);
|
|
// $attributeFields = [
|
|
// '外观' => '外观',
|
|
// '产品尺寸(宽*高*深)' => '产品尺寸(宽*高*深)',
|
|
// '开孔尺寸(宽*高*深)' => '开孔尺寸(宽*高*深)',
|
|
// '容积' => '容积',
|
|
// '产品卖点' => '产品卖点',
|
|
// ];
|
|
// $attributeFieldsName = array_flip($attributeFields);
|
|
|
|
$insertData = [];
|
|
$now = time();
|
|
|
|
Db::beginTransaction();
|
|
$uploadService = new UploadService();
|
|
try {
|
|
for ($row = 2; $row <= $highestRow; $row++) {
|
|
$rowData = $sheet->rangeToArray(
|
|
"A{$row}:{$highestCol}{$row}", null, true, false
|
|
)[0];
|
|
|
|
$data = [];
|
|
$attributes = [];
|
|
foreach ($header as $i => $field) {
|
|
if (in_array($field, $allowFields)) {
|
|
$data[$fieldsName[$field]] = trim((string)($rowData[$i] ?? ''));
|
|
}
|
|
|
|
//商品属性
|
|
// if (in_array($field, $attributeFields) && !empty($rowData[$i])) {
|
|
// $attributes[$attributeFieldsName[$field]] = trim((string)($rowData[$i] ?? ''));
|
|
// }
|
|
}
|
|
|
|
if (empty($data['product_name'])) {
|
|
continue;
|
|
}
|
|
|
|
$data['category_id'] = PostCategory::where('name', $rowData[4])->value('id')??0;
|
|
|
|
|
|
// $sku = Sku::where('model', $data['model'])->first();
|
|
// $sku->spec_json = $data['spec_json'];
|
|
// $sku->save();
|
|
|
|
$data['code'] = $this->service->generateUniqueCode();
|
|
$data['brand'] = $data['brand'] ?: '西门子';
|
|
$data['price'] = $data['price'] ?: 0;
|
|
$data['status'] = $data['status'] ?? 1;
|
|
|
|
// 图片
|
|
//$data['main_image'] = $rowImages[$row] ?? null;
|
|
|
|
$data['created_at'] = $now;
|
|
$data['updated_at'] = $now;
|
|
|
|
$insertData[] = $data;
|
|
|
|
if (count($insertData) >= 200) {
|
|
Sku::insert($insertData);
|
|
// Db::table('sku')->insert($insertData);
|
|
$insertData = [];
|
|
}
|
|
}
|
|
@unlink($zipPath);
|
|
|
|
if ($insertData) {
|
|
Sku::insert($insertData);
|
|
// Db::table('sku')->insert($insertData);
|
|
}
|
|
|
|
Db::commit();
|
|
} catch (\Throwable $e) {
|
|
Db::rollBack();
|
|
return $this->error($e->getMessage().$e->getLine().$e->getFile());
|
|
} finally {
|
|
@unlink($path);
|
|
}
|
|
|
|
return $this->success([], '导入成功');
|
|
}
|
|
|
|
/**
|
|
* 解压 zip 文件
|
|
*
|
|
* @param string $zipPath zip 文件绝对路径
|
|
* @param string $extractTo 解压目录
|
|
* @return bool
|
|
*/
|
|
function unzipPackage(string $zipPath, string $extractTo): bool
|
|
{
|
|
if (!file_exists($zipPath)) {
|
|
throw new \Exception('ZIP 文件不存在');
|
|
}
|
|
|
|
if (!is_dir($extractTo)) {
|
|
mkdir($extractTo, 0755, true);
|
|
}
|
|
|
|
$zip = new ZipArchive();
|
|
if ($zip->open($zipPath) !== true) {
|
|
throw new \Exception('ZIP 文件打开失败');
|
|
}
|
|
|
|
$zip->extractTo($extractTo);
|
|
$zip->close();
|
|
|
|
return true;
|
|
}
|
|
|
|
|
|
/**
|
|
* 下载 Excel 示例模板
|
|
*/
|
|
public function template(Request $request): Response
|
|
{
|
|
$filePath = runtime_path() . '/upload/import.zip';
|
|
|
|
if (!file_exists($filePath)) {
|
|
return response('文件不存在', 404);
|
|
}
|
|
|
|
return response()->download(
|
|
$filePath,
|
|
'导入示例.zip' // 下载时显示的文件名
|
|
);
|
|
}
|
|
} |