<?php

namespace App\Admin\Controllers\Video;

use App\Models\Advert;
use App\Models\Category;
use App\Models\Video;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;

class IndexController extends AdminController
{

    protected $title = '视频资源';

    protected function grid()
    {
        $grid = new Grid(new Video());

        $grid->filter(function ($filter) {
            $filter->column(1 / 2, function ($filter) {
                $filter->like('title', '视频名称');
                $filter->like('category.id', '分类名称')
                       ->select(Category::selectOptions(function ($model) {
                           return $model->where('status', 1)->where('type', Category::TYPE_ADVERT);
                       }, '所有分类'));
            });
            $filter->disableIdFilter();
        });

        $grid->column('id');
        $grid->column('title', '视频名称');
        $grid->column('cover', '封面')->image();
        $grid->column('link', '视频地址')->downloadable();
        $grid->column('category.title', '分类名称');
        $grid->column('sort', '排序');

        return $grid;
    }

    /**
     * Make a form builder.
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new Video());

        $form->text('title', '视频名称')->required();

        $form->select('category_id', '所属分类')
             ->options(function () {
                 return Category::query()
                                ->where('status', 1)
                                ->where('type', Category::TYPE_VIDEO)
                                ->pluck('title', 'id');
             })
             ->rules('required|min:1', [
                 'required' => '必须选择所属分类',
                 'min'      => '必须选择所属分类',
             ]);

        $form->file('cover', '封面')
             ->rules(function ($form) {
                 if ($form->model()->cover != []) {
                     return 'nullable|image';
                 } else {
                     return 'required';
                 }
             })
             ->move('images/' . date('Y/m/d'))
             ->removable()
             ->uniqueName();

        $form->file('link', '视频')
             ->rules(function ($form) {
                 if ($form->model()->cover != []) {
                     return 'nullable|image';
                 } else {
                     return 'required';
                 }
             })
             ->move('videos/' . date('Y/m/d'))
             ->removable()
             ->uniqueName();

        $form->number('sort', '排序')
             ->default(1)
             ->required()
             ->help('数字越大越靠前');

        return $form;
    }

}
