<?php

namespace App\Admin\Controllers\Advert;

use App\Models\Advert;
use App\Models\Category;
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 Advert);

        $grid->actions(function ($actions) {
            $actions->disableView();
        });

        $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('cover', '图片')->image('', 60, 60);
        $grid->column('category.title', '分类名称');
        $grid->column('title', '广告名称');
        $grid->column('url', '地址');
        $grid->column('sort', '排序');

        return $grid;
    }

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

        $form->text('title', '广告名称')->required();
        $form->select('category_id', '所属分类')
            ->options(Category::selectOptions(function ($model) {
                return $model->where('status', 1)->where('type', Category::TYPE_ADVERT);
            }, '选择分类'))
            ->rules('required|min:1', [
                'required' => '必须选择所属分类',
                'min'      => '必须选择所属分类',
            ]);
        $form->image('cover', '封面图片')
            ->rules(function ($form) {
                if ($form->model()->cover != []) {
                    return 'nullable|image';
                } else {
                    return 'required';
                }
            })
            ->move('images/' . date('Y/m/d'))
            ->removable()
            ->uniqueName();
        $form->text('url', '链接地址');
        $form->number('sort', '排序')
            ->default(1)
            ->required()
            ->help('数字越大越靠前');

        return $form;
    }

}
