<?php

namespace App\Admin\Controllers\Article;

use App\Admin\Selectable\CategorySelectAble;
use App\Models\Article;
use App\Models\Category;
use App\Models\CategoryOld;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;

class IndexController extends AdminController
{

    protected $title = '内容管理';

    public function grid()
    {
        $grid = new Grid(new Article);
        $grid->model()->orderBy('id', 'desc');
        $grid->filter(function ($filter) {
            $filter->column(1 / 2, function ($filter) {
                $filter->like('title', '文章标题');
                $filter->equal('category_id', '所属分类')->select(Category::selectOptions(function ($model) {
                    return $model->where('status', 1)->whereIn('type', [Category::TYPE_ARTICLE, Category::TYPE_SHOW]);
                }, '所有分类'));

            });

            $filter->disableIdFilter();
        });

        $grid->column('id', '#ID#');
        $grid->column('cover', '封面图片')->image('', 100);
        $grid->column('category.title', '所属分类');
        $grid->column('title', '文章标题');
        $grid->column('文章前台地址')
             ->display(function () {
                 return $this->link;
             })
             ->hide();
        $states = [
            'on'  => ['value' => 1, 'text' => '打开', 'color' => 'primary'],
            'off' => ['value' => 2, 'text' => '关闭', 'color' => 'default'],
        ];
        $grid->column('status', '状态')->switch($states);
        $grid->column('recommen', '推荐')->switch();
        $grid->column('sort', '序号');
        $grid->column('created_at', '创建时间');

        return $grid;
    }

    public function form()
    {
        $form = new Form(new Article);

        $form->text('title', '文章标题')->rules('min:2');
        $form->text('remark', '子标题');
        $form->select('category_id', '所属分类')
             ->options(Category::selectOptions(function ($model) {
                 return $model->where('status', 1)->whereIn('type', [Category::TYPE_ARTICLE, Category::TYPE_SHOW]);
             }, '一级分类'));

        $form->textarea('description', '内容简介');
        $form->image('cover', '封面')
             ->move('images/' . date('Y/m/d'))
             ->removable()
             ->uniqueName();
        $form->image('logo', 'logo')
             ->move('images/' . date('Y/m/d'))
             ->removable()
             ->uniqueName();
        $form->ueditor('content', '文章内容')->rules('required', ['required' => '详情不能为空']);
        $form->number('sort', '序号')->default(0)->rules('required', ['required' => '序号必须填写'])->help('倒序优先');
        $states = [
            'on'  => ['value' => 1, 'text' => '打开', 'color' => 'success'],
            'off' => ['value' => 0, 'text' => '关闭', 'color' => 'danger'],
        ];
        $form->datetime('created_at', '发布时间');
        $form->switch('status', '状态')->states($states)->default(1);
        $form->switch('recommen', '推荐')->default(0);

        return $form;
    }

}
