<?php

namespace App\Distributor\Controllers;

use App\Admin\Repositories\BaseProductImage;
use App\Distributor\Actions\Extensions\DistProductImport;
use App\Distributor\Repositories\DistProduct;
use App\Distributor\Repositories\DistProductCategory;
use App\Libraries\CommonHelper;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Show;
use Illuminate\Http\Request;

class DistProductController extends AdminController
{
    /**
     * page index
     */
    public function index(Content $content)
    {
        return $content
            ->header(admin_trans( 'admin.products_list'))
            ->description(admin_trans('admin.all'))
            ->description('all')
            //->breadcrumb(['text'=>'Product Management','url'=>''])

            ->body($this->grid());

    }

    /**
     * Edit interface.
     *
     * @param  mixed  $id
     * @param  Content  $content
     * @return Content
     */
    public function edit($id, Content $content)
    {

        return $content
            ->translation($this->translation())
            ->title(admin_trans('admin.product'))
            ->description($this->description()['edit'] ?? trans('admin.edit'))
            ->body($this->form()->edit($id));
    }

    /**
     * Create interface.
     *
     * @param  Content  $content
     * @return Content
     */
    public function create(Content $content)
    {
        return $content
            ->header('Product')
            ->translation($this->translation())
            ->title(admin_trans('admin.product'))
            ->description($this->description()['create'] ?? trans('admin.create'))
            ->body($this->form());
    }
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(DistProduct::with(['distProductCategory','images']), function (Grid $grid) {
            $grid->model()->where('dist_id', getDistributorId());
            $grid->column('id','ID')->sortable();
            $grid->column('title');
            $grid->column('sku');
            $grid->column('dist_product_category.name',admin_trans_label('category_name'));
            $grid->column('issuance_date');
            $grid->column('images')->display(function ($images) {

                $images = $images->toArray();
                $dataImages = array_column($images, 'image_url');

                // 限制最多显示2个缩略图
                $dataImages = array_slice($dataImages, 0, 2);

                return CommonHelper::displayImage($dataImages,60);



            });
            //$grid->column('order')->orderable();
            $grid->column('is_pinned')->switch();
            $grid->column('enabled')->switch();
            $grid->column('created_at');
            $grid->column('updated_at')->sortable();
            // 筛选
            $grid->filter(function (Grid\Filter $filter) {
                $filter->panel();
                $filter->expand();
                $filter->like('title')->width(2);
                $filter->equal('sku')->width(2);
                $filter->equal('category_id',admin_trans_label('category'))->select(DistProductCategory::selectOptions())->width(2);;
                $filter->equal('enabled', admin_trans_label('enabled'))->select(array_map('admin_trans_label', config('dictionary.enabled')))->width(2);;
            });
            //排序
            $grid->model()->orderBy("is_pinned",'desc')->orderBy("order",'desc');
            // 传入数组
            $grid->tools([
                new DistProductImport(),
            ]);

        });

    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, DistProduct::with(['distProductCategory','images']), function (Show $show) {
            // 比较 dist_id 和 getDistributorId()，如果不相同则返回 404
            if ($show->model()->dist_id !== getDistributorId()) {
                abort(404);
            }
            $show->field('id');
            $show->field('title');
            $show->field('keywords');
            $show->field('description');
            $show->field('sku');
            $show->field('dist_product_category.name',admin_trans_label('category_name'));
            $show->field('issuance_date');
            $show->field('parameters')->as(function ($items) {
                if (is_array($items)) {
                    // 创建表格的表头
                    $table = '<table class="table">';
                    $table .= '<tr><th>'.admin_trans_field('key').'</th><th>'.admin_trans_field('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('created_at');
            $show->field('updated_at');
            $show->field('order');
            $show->field('enabled')->using(config('dictionary.enabled'));
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(DistProduct::with('images'), function (Form $form) {
            $form->display('id');
            $form->select('category_id', admin_trans_label('category_name'))
                ->options(DistProductCategory::selectOptions())
                ->required();
            $form->text('title')->required();
            $form->text('keywords');
            $form->textarea('description');
            $form->text('sku')->required();
            $form->date('issuance_date');
            $form->table('parameters',admin_trans_label('parameters'), function (Form\NestedForm $table) {
                $table->text('key',admin_trans_field('key'))->required();
                $table->text('value',admin_trans_field('value'))->required();
            });
            // 多图上传
            $form->multipleImage('images', admin_trans_label('images'))
                ->sortable() // 可拖动排序
                ->removable() // 可移除图片
                ->autoUpload() // 自动上传
                ->uniqueName()
                ->accept(config('distributor.upload.oss_image.accept'))
                ->maxSize(config('distributor.upload.oss_image.max_size'))
                ->dir('dist_images/product/'.date("Ymd"))
                ->customFormat(function () {
                    // 数据格式化为数组['1.jpg','2.jpg'] 编辑时用到
                    return array_column($this->images, 'image_url');
                })
                ->saving(function ($images) {
                    return array_map(function($image) {
                        return ['image_url' => $image];
                    }, $images);
                });
            $form->editor('content');
            $form->switch('is_pinned')->default(0);
            $form->switch('enabled')->default(1);
            $form->hidden('dist_id'); // 隐藏dist_id字段,用于保存

            //插入JS
            $this->addParametersJs();
            // 在保存时进行验证
            $form->saving(function (Form $form) {
                $form->dist_id =getDistributorId();//保存时直接写死dist_id

                if (!$form->isCreating()) {
                    // 验证主键 ID 的 dist_id 是否与 session 的 dist_id 一致
                    $currentDistProduct = DistProduct::findById($form->getKey());
                    if ($currentDistProduct && $currentDistProduct->dist_id !== $form->dist_id) {
                        throw new \Exception('Unable to modify the product because the distributor ID does not match.');
                    }
                }

                //保存前回调删除图片
                if (!$form->isCreating()) {
                    //清空图片
                    $id = $form->getKey();
                    $baseProductImage = new BaseProductImage();
                    $baseProductImage->model()->where('product_id', $id)->delete();
                }


            });
        });
    }

    /*
     * 以json型式返回产品参数
     */
    public static function parameter(Request $request)
    {
        $id = $request->query('q');
        $content = DistProductCategory::getParameter($id);
        return $content;
    }
    /**
     * 分类与参数联动JS
     * @return void
     */
    private function addParametersJs()
    {
        $prefix = config('admin.route.prefix');
        //插入JS
        Admin::script(
            <<<JS


JS
        );
    }
}
