<?php

namespace App\Admin\Controllers\Episode;

use App\Models\EpisodesCategory;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Dingo\Api\Http\Request;

class EpisodesCategoryController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new EpisodesCategory(), function (Grid $grid) {
            $grid->column('id')->sortable();
            $grid->column('name');
            $grid->column('pid','父分类')->display(function () {
                /* @var EpisodesCategory $this*/
                return $this->parent ?$this->parent->name : '';
            });
            $grid->column('created_at');

            $grid->disableRowSelector();
            $grid->disableViewButton();
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new EpisodesCategory(), function (Show $show) {
            $show->field('id');
            $show->field('name');
            $show->field('pid');
            $show->field('path');
            $show->field('sort');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new EpisodesCategory(), function (Form $form) {
            $categoryModel = app(\App\Models\EpisodesCategory::class);
            $options = $categoryModel::select(['id','name'])->where('pid',0)->get()->toArray();
            array_unshift($options,['id' => 0, 'name' => '顶级分类']);
            $options = array_column($options,'name','id');
            $form->display('id');
            $form->select('pid')->options($options);
            $form->text('name');
        });
    }

    public function options(Request $request)
    {
        $q = $request->get('q');
        $categoryModel = app(\App\Models\EpisodesCategory::class);
        return $categoryModel->where('name', 'like', "%$q%")->paginate(null, ['id', 'name as text']);
    }
}
