<?php

namespace App\Distributor\Controllers;


use App\Distributor\Repositories\DistVideo;
use App\Distributor\Repositories\DistVideoCategory;
use App\Libraries\CommonHelper;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Layout\Content;

class DistVideoController extends AdminController
{

    /**
     * page index
     */
    public function index(Content $content)
    {
        return $content
            ->header(admin_trans('admin.video_list'))
            ->description(admin_trans('admin.all'))
            ->breadcrumb(['text'=>admin_trans('admin.video_list'),'url'=>''])
            ->body($this->grid());
    }

    public function create(Content $content)
    {
        return $content
            ->translation($this->translation())
            ->title(admin_trans('admin.video'))
            ->description($this->description()['create'] ?? trans('admin.create'))
            ->body($this->form());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(DistVideo::with(['distVideoCategory']), function (Grid $grid) {
            $grid->model()->where('dist_id', getDistributorId());

            $grid->column('id')->sortable();
            $grid->column('title');
            $grid->column('dist_video_category.name',admin_trans_label('category_name'));
            $grid->column('cover_image')->display(function ($image) {
                // 开始生成 HTML
                $dataImages = [$image];
                return CommonHelper::displayImage($dataImages,150);
            });
            $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->equal('sku')->width(2);
                $filter->like('title')->width(2);
                $filter->equal('category_id',admin_trans_label('category'))->select(DistVideoCategory::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');
            //按钮
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, DistVideo::with(['distVideoCategory']), function (Show $show) {

            // 比较 dist_id 和 getDistributorId()，如果不相同则返回 404
            if ($show->model()->dist_id !== getDistributorId()) {
                abort(404);
            }
            $show->field('id');
            $show->field('title');
            $show->field('dist_video_category.name',admin_trans_label('category_name'));
            $show->field('cover_image')->as(function ($image) {
                // 开始生成 HTML
                $dataImages = [$image];
                return CommonHelper::displayImage($dataImages,150);
            })->unescape();
            $show->html(function () {
                $content = $this->video_url;
                return view('admin::show.field', [
                    'wrapped'=>true,
                    'escape'=>false,
                    'width'=>['label' => '2','field'=>'8'],
                    'label'=>'Video Url',
                    'content'=>$content
                ]);
            });
            $show->field('video_url','Video player')->as(function ($value) {
                $html = '
                <iframe width="560" height="315" src="'.$value.'"
                        title="YouTube video player"
                        frameborder="0"
                        allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                        allowfullscreen>
                 </iframe>';
                return $html;
            })->unescape();
            $show->field('remark')->unescape();
            $show->field('enabled')->using(config('dictionary.enabled'));
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new DistVideo(), function (Form $form) {
            $form->display('id');
            $form->text('title')->required();
            $form->select('category_id', admin_trans_label('category_name'))
                ->options(DistVideoCategory::selectOptions())
                ->required();
            $form->image("cover_image", admin_trans_label('cover_image'))
                ->autoUpload()
                ->uniqueName()
                ->accept(config('admin.upload.oss_image.accept'))
                ->maxSize(config('admin.upload.oss_image.max_size'))
                ->dir('images/video/'.date("Ymd"));//
            $form->url("video_url", admin_trans_label('video_url'))->required();
            $form->editor('remark');
            $form->switch('is_pinned')->default(0);
            $form->switch('enabled')->default(1);
            $form->hidden('dist_id'); // 隐藏dist_id字段,用于保存
            $form->saving(function (Form $form) {
                $form->dist_id =getDistributorId();//保存时直接写死dist_id

                if (!$form->isCreating()) {
                    // 验证主键 ID 的 dist_id 是否与 session 的 dist_id 一致
                    $currentDistProduct = DistVideo::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.');
                    }
                }
            });
        });
    }
}
