<?php

namespace App\Admin\Controllers\Episode;

use App\Models\Episode;
use App\Models\EpisodesCategory;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Http\Controllers\AdminController;

class EpisodesCategoryController extends AdminController
{
    public function destroy($id)
    {
        $childIds   = EpisodesCategory::where('pid', $id)->get()->pluck('id');
        $childIds[] = $id;

        $hasEpisode = Episode::whereIn('category_id', $childIds)->count();
        if ($hasEpisode) {
            $form     = new Form();
            $response = $form->response();

            return $response->error('当前分类或子分类存在短剧，前先删除短剧后再删除分类');
        }

        return $this->form()->destroy($id);
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new EpisodesCategory(), function (Grid $grid) {
            $grid->model()->orderByDesc('sort');
            $grid->column('id')->sortable();
            $grid->column('name');
            // $grid->column('level')->using(config('global.cat_level'));
            //            $grid->column('pid','父分类')->display(function () {
            //                /* @var EpisodesCategory $this*/
            //                return $this->parent ?$this->parent->name : '';
            //            });
            $grid->column('sort')->editable();
            // $grid->column('created_at');

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

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new EpisodesCategory(), function (Form $form) {
            $form->display('id');
            //            $form->radio('level')
            //                ->when(2, function (Form $form){
            //                    $options = EpisodesCategory::select(['id','name'])
            //                        ->where('level',1)
            //                        ->get()
            //                        ->pluck('name', 'id');
            //                    $form->select('pid')->options($options);
            //                })
            //                ->options(config('global.cat_level'))
            //                ->default(1);

            $form->text('level')->value(1)->display(false);

            $form->text('name')->required();
            $form->number('sort');

            $form->disableViewButton();
            $form->disableDeleteButton();
            $form->disableListButton();
            $form->disableEditingCheck();
            $form->disableViewCheck();
            $form->disableCreatingCheck();
        });
    }
}
