<?php

namespace App\Distributor\Controllers;


use App\Distributor\Repositories\DistAdminUsersSetting;
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 AdminDistController
{
    protected function title()
    {
        return admin_trans('admin.video_list');
    }

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


    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(DistVideo::with(['distVideoCategory']), function (Grid $grid) {
            //默认分页条数
            $grid->paginate(config('admin.per_page'));
            $grid->column('id')->display(function () {
                return $this->_index+1;
            });
            $grid->column('title')->width('25%');
            $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');
            $grid->column('enabled')->switch();
            $grid->column('created_at')->sortable();
            $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(admin_trans_array( config('dictionary.enabled')))->width(2);


            });
            //权限与排序
            $grid->model()->orderBy("order",'desc');
            $grid->model()->where('dist_id', getDistributorId());
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, DistVideo::with(['distVideoCategory']), function (Show $show) {
            $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'=>admin_trans_label('video_url'),
                    'content'=>$content
                ]);
            });
            $show->field('video_url',admin_trans_label('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('created_at');
            $show->field('updated_at');
            // SEO
            $show->field('seo_title');
            $show->field('seo_keywords');
            $show->field('seo_description');
            $show->field('slug',admin_trans_label('url_and_handle'))->as(function ($value) {
                return getSiteDomain().config('dictionary.site_url.pages').'/'.$value;
            });
            $show->field('order');
            $show->field('enabled')->using(admin_trans_array(config('dictionary.enabled')));
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new DistVideo(), function (Form $form) {
            //$form->display('id');
            $help = admin_trans_label('video_help');
            $inputFormat = admin_trans_label('input_format');
            $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'))
                ->retainable()//禁止删OSS图
                ->autoUpload()
                ->uniqueName()
                ->accept(config('distributor.upload.oss_image.accept'))
                ->maxSize(config('distributor.upload.oss_image.max_size'))
                ->dir(config("distributor.upload.directory.image").'/video/'.date("Ymd"));//
            $form->text("video_url", admin_trans_label('video_url'))
                ->required()
                ->help('<a href="/help/youtube_url/index.html" target="_blank">'.$help. ' </a>, '.$inputFormat.' : https://www.youtube.com/embed/xxxxxxxx');
            $form->editor('remark');
            //SEO
            $form->text('seo_title');
            $form->text('seo_keywords');
            $form->text('seo_description');
            $form->text('slug',admin_trans_label('url_and_handle'))->width(4, 2)->prepend(getSiteDomain().config('dictionary.site_url.video').'/');
            $form->number('order')
                ->default(0)
                ->rules('numeric');
            $form->switch('enabled')->default(1);
            //隐藏
            $form->hidden('dist_id'); // 隐藏dist_id字段,用于保存

            //新建时插入JS
            $form->creating(function (Form $form) {
                CommonHelper::seoReplace();
            });
            $form->saving(function (Form $form) {
                $form->dist_id =getDistributorId();//保存时直接写死dist_id

                //slug配置是否重复
                $id = $form->getKey();
                //slug配置是否重复
                $form->slug=trim($form->slug);
                if ($form->slug != '') {
                    //把slug中的空格替换成-，多个空格在一起只用一个-，大写字母转换成小写
                    $form->slug = preg_replace('/\s+/', '-', $form->slug);
                    $form->slug = strtolower($form->slug);
                    if (DistVideo::isRepeatedSlug($id, $form->slug)) {
                        //slug重复
                        return $form->response()->error(admin_trans_label('url_repeated'));
                    }
                }
                //当slug为空时生成slug
                if ($form->slug == '') {
                    $form->slug = DistVideo::generateSlug($form->title, $id);
                }
                //seo_title不能为空
                if ($form->seo_title == '') {
                    $form->seo_title = $form->title;
                }
                //替换youtube URL
                if (strpos($form->video_url, '<iframe') !== false) {
                    // 使用正则表达式提取 src 属性的值
                    if (preg_match('/<iframe[^>]+src="([^"]+)"/', $form->video_url, $matches)) {
                        $src = $matches[1];
                        $form->video_url = $src;
                    }
                }
            });
        });
    }
}
