Browse Source

产品管理

moshaorui 6 months ago
parent
commit
4dc31d2336

+ 86 - 30
app/Admin/Controllers/BaseProductController.php

@@ -3,6 +3,7 @@
 namespace App\Admin\Controllers;
 
 use App\Admin\Repositories\BaseProduct;
+use App\Models\BaseProduct as baseProductModel;
 use Dcat\Admin\Admin;
 use Dcat\Admin\Form;
 use Dcat\Admin\Form\NestedForm;
@@ -10,11 +11,12 @@ use Dcat\Admin\Grid;
 use Dcat\Admin\Show;
 use Dcat\Admin\Http\Controllers\AdminController;
 use App\Admin\Repositories\BaseProductCategory;
+use App\Admin\Repositories\BaseProductImage;
 use Illuminate\Http\Request;
+use App\Libraries\CommonHelper;
 class BaseProductController extends AdminController
 {
 
-
     /**
      * Make a grid builder.
      *
@@ -22,12 +24,17 @@ class BaseProductController extends AdminController
      */
     protected function grid()
     {
-        return Grid::make(BaseProduct::with('baseProductCategory'), function (Grid $grid) {
+        return Grid::make(BaseProduct::with(['baseProductCategory','images']), function (Grid $grid) {
             $grid->column('id','ID')->sortable();
             $grid->column('title');
             $grid->column('sku');
-            $grid->column('baseProductCategory.name','Category Name');
+            $grid->column('base_product_category.name','Category Name');
             $grid->column('issuance_date');
+            $grid->column('images')->display(function ($images) {
+                $images = $images->toArray();
+                $dataImages = array_column($images, 'image_url');
+                return CommonHelper::displayImage($dataImages,80);
+            });
             $grid->column('order')->orderable();
             $grid->column('enabled')->switch();
             $grid->column('created_at');
@@ -62,23 +69,49 @@ class BaseProductController extends AdminController
      */
     protected function detail($id)
     {
-        return Show::make($id, new BaseProduct(), function (Show $show) {
+        return Show::make($id, BaseProduct::with(['baseProductCategory','images']), function (Show $show) {
             $show->field('id');
             $show->field('title');
             $show->field('keywords');
             $show->field('description');
             $show->field('sku');
-            $show->field('baseProductCategory.name','Category Name');
+            $show->field('base_product_category.name','Category Name');
             $show->field('issuance_date');
-            $show->field('order');
-            $show->field('enabled');
+            $show->field('parameters')->as(function ($items) {
+                if (is_array($items)) {
+                    // 创建表格的表头
+                    $table = '<table class="table">';
+                    $table .= '<tr><th>key</th><th>value</th></tr>';
+                    // 遍历数组并将数据填充到表格中
+                    foreach ($items as $item) {
+                        $table .= '<tr>';
+                        $table .= '<td>' . $item['key'] . '</td>';    // 商品名称
+                        $table .= '<td>' . $item['value'] . '</td>'; // 数量
+                        $table .= '</tr>';
+                    }
+                    $table .= '</table>';
+                    return $table;
+                }
+
+                return ''; // 当没有数组数据时
+            })->unescape();
+            $show->field('images')->as(function ($images) {
+                // 开始生成 HTML
+                $dataImages = array_column($images, 'image_url');
+                return CommonHelper::displayImage($dataImages,150);
+            })->unescape();
             $show->field('content');
-            $show->field('parameters');
             $show->field('created_at');
             $show->field('updated_at');
+            $show->field('order');
+            $show->field('enabled')->using([
+                '0' => 'No',   // 显示的状态名称
+                '1' => 'Yes',
+            ]);
         });
     }
 
+
     /**
      * Make a form builder.
      *
@@ -86,32 +119,46 @@ class BaseProductController extends AdminController
      */
     protected function form()
     {
-        return Form::make(new BaseProduct(), function (Form $form) {
+        return Form::make(BaseProduct::with('images'), function (Form $form) {
+            $form->display('id');
             $form->select('category_id', 'Category Name')
                 ->options(BaseProductCategory::selectOptions())
                 ->required();
-//            $form->select('city');
-//            $form->text('title')->required();
-//            $form->text('keywords');
-//            $form->text('description');
-//            $form->text('sku')->required();
-//            $form->date('issuance_date');
-//            $form->table('parameters','Parameters', function (Form\NestedForm $table) {
-//                $table->text('key')->required();
-//                $table->text('value')->required();
-//            });
-//            $form->editor('content');
-//            $form->number('order');
-//            $form->switch('enabled')->default(1);
-
+            $form->text('title')->required();
+            $form->text('keywords');
+            $form->textarea('description');
+            $form->text('sku')->required();
+            $form->date('issuance_date');
             $form->table('parameters','Parameters', function (Form\NestedForm $table) {
                 $table->text('key')->required();
                 $table->text('value')->required();
-            })->default([
-                ['key' => 'color', 'value' => 'white'],
-            ]);
+            });
+            // 多图上传
+            $form->multipleImage('images', 'images')
+                ->sortable() // 可拖动排序
+                ->removable() // 可移除图片
+                ->customFormat(function () {
+                    // 数据格式化为数组['1.jpg','2.jpg']
+                    return array_column($this->images, 'image_url');
+                })
+                ->saving(function ($paths) {
+                    $paths =  array_column($paths, 'id');
+                    return $paths;
+                });
+            $form->editor('content');
+            $form->number('order');
+            $form->switch('enabled')->default(1);
             //插入JS
             $this->addParametersJs();
+            //保存后执行
+            $form->saved(function (Form $form) {
+                $productId =  $form->getKey();
+                $images = explode(',',$form->input('images'));
+                //删除旧的图片记录
+                BaseProductImage::deleteByProductId($productId);
+                //插入新的图片记录
+                BaseProductImage::saveProductImages($productId, $images);
+            });
         });
 
     }
@@ -126,8 +173,13 @@ class BaseProductController extends AdminController
         return $content;
     }
 
+    /**
+     * 分类与参数联动JS
+     * @return void
+     */
     private function addParametersJs()
     {
+        $prefix = config('admin.route.prefix');
         //插入JS
         Admin::script(
             <<<JS
@@ -136,21 +188,25 @@ var fill_param = function (key,val) {
     lastForm.find('input').eq(0).val(key);
     lastForm.find('input').eq(1).val(val);
 }
+
 $('select[name="category_id"]').on('change', function() {
     var category_id = $(this).val();
     // 清空现有的表格行
     $('.has-many-table-parameters-form').remove();
     if (category_id > 0) {
         $.ajax({
-            url: '/prime-control/base-product/parameter',      // 请求的 URL
+            url: '/{$prefix}/base-product/parameter',
             data: { q: category_id},
-            type: 'GET',              // GET 请求
-            success: function(data) { // 成功时执行的代码
+            dataType: 'json',
+            type: 'GET',              // GET
+            success: function(data) { // success
+                if (Array.isArray(data) && data.length === 0) {
+                    return null;
+                }
                 // 动态添加新数据到表格
                 $.each(data, function(index, item) {
                     $(".has-many-table-parameters").find(".add").click();
                     fill_param(item.key,item.value);
-                    console.log(item);
                 });
             },
             error: function(error) {  // 错误时执行的代码

+ 20 - 1
app/Admin/Repositories/BaseProduct.php

@@ -3,6 +3,7 @@
 namespace App\Admin\Repositories;
 
 use App\Models\BaseProduct as Model;
+use Dcat\Admin\Form;
 use Dcat\Admin\Repositories\EloquentRepository;
 
 class BaseProduct extends EloquentRepository
@@ -14,5 +15,23 @@ class BaseProduct extends EloquentRepository
      */
     protected $eloquentClass = Model::class;
 
-
+    /*
+     * 重写保存方法
+     */
+//    public function store(Form $form)
+//    {
+//        exit;
+//        $form->ignore(['images']);
+//        return parent::store($form);
+//    }
+//
+//    public function update(Form $form)
+//    {
+//        echo ' bb---------';
+//        $form->prepare('images');
+//        echo ' ---updates------';
+//        var_dump($form->updates());
+//        exit;
+//        return parent::store($form);
+//    }
 }

+ 41 - 0
app/Admin/Repositories/BaseProductImage.php

@@ -0,0 +1,41 @@
+<?php
+
+namespace App\Admin\Repositories;
+
+use App\Models\BaseProductImage as Model;
+use Dcat\Admin\Repositories\EloquentRepository;
+use Carbon\Carbon;
+
+class BaseProductImage extends EloquentRepository
+{
+    /**
+     * Model.
+     *
+     * @var string
+     */
+    protected $eloquentClass = Model::class;
+
+
+    public static function deleteByProductId($productId)
+    {
+        Model::where('product_id', $productId)->delete();
+    }
+
+    public static function saveProductImages($productId, $imageUrls)
+    {
+        // 准备数据集合
+        $data = [];
+        foreach ($imageUrls as $imageUrl) {
+            $data[] = [
+                'product_id' => $productId,
+                'image_url' => $imageUrl,
+                'created_at' => Carbon::now(),
+                'updated_at' => Carbon::now(),
+            ];
+        }
+        // 批量插入
+        return Model::insert($data);
+    }
+
+
+}

+ 26 - 0
app/Libraries/CommonHelper.php

@@ -0,0 +1,26 @@
+<?php
+
+// app/Libraries/CommonHelper.php
+namespace App\Libraries;
+
+class CommonHelper
+{
+
+    /*
+     * $images 格式:['image.jpg','image2.jpg']
+     * 返回显示的HTML
+     */
+    public static function displayImage($images,$size=150)
+    {
+        $html = '<div style="display: flex; flex-wrap: wrap; gap: 5px;">';
+        foreach ($images as $image) {
+            $html .= "<div style='flex: 1 0 150px; max-width: {$size}px; max-height: {$size}px; padding: 10px; border: 1px solid #ddd; border-radius: 5px; background-color: #f9f9f9; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); display: flex; align-items: center; justify-content: center;'>
+                    <img  data-action='preview-img' src='" . asset('storage/' . $image) . "' style='max-width: 100%; max-height: 100%; object-fit: contain;'>
+                  </div>";
+        }
+        $html .= '</div>';
+        return $html;
+    }
+
+}
+

+ 6 - 0
app/Models/BaseProduct.php

@@ -11,6 +11,7 @@ class BaseProduct extends Model
 	use HasDateTimeFormatter;
     protected $table = 'base_product';
 
+    protected  $fillable = ['id', 'title', 'keywords', 'description', 'sku', 'category_id', 'issuance_date', 'order', 'enabled', 'content', 'parameters', 'created_at', 'updated_at'];
     protected $casts = [
         'created_at' => 'datetime:Y-m-d H:i:s',
         'updated_at' => 'datetime:Y-m-d H:i:s',
@@ -22,4 +23,9 @@ class BaseProduct extends Model
         return $this->hasOne(BaseProductCategory::class,'id','category_id');
     }
 
+    // 一对多关联
+    public function images()
+    {
+        return $this->hasMany(BaseProductImage::class, 'product_id');
+    }
 }

+ 23 - 0
app/Models/BaseProductImage.php

@@ -0,0 +1,23 @@
+<?php
+
+namespace App\Models;
+
+use Dcat\Admin\Traits\HasDateTimeFormatter;
+use Illuminate\Database\Eloquent\Model;
+
+class BaseProductImage extends Model
+{
+	use HasDateTimeFormatter;
+    protected $table = 'base_product_image';
+
+    protected $casts = [
+        'created_at' => 'datetime:Y-m-d H:i:s',
+        'updated_at' => 'datetime:Y-m-d H:i:s',
+    ];
+
+    // 反向关联,属于某个产品
+    public function product()
+    {
+        return $this->belongsTo(BaseProduct::class, 'id');
+    }
+}